main.py 536 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import re
  8. import secrets
  9. import time
  10. from contextlib import asynccontextmanager
  11. from datetime import datetime, timedelta, timezone
  12. from logging.handlers import RotatingFileHandler
  13. from pathlib import Path, PurePosixPath
  14. from urllib.parse import urlparse
  15. from fastapi import FastAPI
  16. from fastapi.responses import FileResponse
  17. from fastapi.staticfiles import StaticFiles
  18. from sqlalchemy import delete, or_, select, text
  19. from backend.app.api.routes import (
  20. ams_history,
  21. announcements,
  22. api_keys,
  23. archive_purge,
  24. archives,
  25. auth,
  26. bug_report,
  27. camera,
  28. camwall,
  29. cloud,
  30. connected_apps,
  31. discovery,
  32. external_links,
  33. filaments,
  34. finance,
  35. firmware,
  36. github_backup,
  37. groups,
  38. ha_sensors,
  39. inventory,
  40. kprofiles,
  41. labels,
  42. library,
  43. library_tags,
  44. library_trash,
  45. library_variants,
  46. local_backup,
  47. local_presets,
  48. location_ha_sensors,
  49. maintenance,
  50. makerworld,
  51. manyfold,
  52. metrics,
  53. mfa,
  54. notification_templates,
  55. notifications,
  56. obico,
  57. orca_cloud,
  58. overlay_branding,
  59. pending_uploads,
  60. pipeline_runs,
  61. print_log,
  62. print_queue,
  63. printer_locations,
  64. printer_sensor_history,
  65. printers,
  66. projects,
  67. scheduled_dryings,
  68. settings as settings_routes,
  69. slice_jobs,
  70. slicer_pipelines,
  71. slicer_presets,
  72. smart_plugs,
  73. sponsor_prompt,
  74. spoolbuddy,
  75. spoolman,
  76. spoolman_inventory,
  77. support,
  78. system,
  79. updates,
  80. user_notifications,
  81. users,
  82. virtual_printers,
  83. webhook,
  84. websocket,
  85. )
  86. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  87. from backend.app.api.routes.support import init_debug_logging
  88. from backend.app.core.config import APP_VERSION, settings as app_settings
  89. from backend.app.core.database import async_session, engine, init_db
  90. from backend.app.core.static_assets import AssetStaticFiles
  91. from backend.app.core.tasks import spawn_background_task
  92. from backend.app.core.websocket import ws_manager
  93. from backend.app.services import kprofile_drift, print_dispatch_context, slot_unlink_grace
  94. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  95. from backend.app.services.archive_purge import archive_purge_service
  96. from backend.app.services.bambu_ftp import (
  97. FileNotOnPrinterError,
  98. cache_3mf_download,
  99. clear_3mf_cache,
  100. download_file_async,
  101. download_file_try_paths_async,
  102. ftps_handshake_blocked,
  103. get_cached_3mf,
  104. get_ftp_retry_settings,
  105. normalize_3mf_name,
  106. with_ftp_retry,
  107. )
  108. from backend.app.services.bambu_mqtt import PrinterState
  109. from backend.app.services.camera_light import camera_light
  110. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  111. from backend.app.services.github_backup import github_backup_service
  112. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  113. from backend.app.services.homeassistant import homeassistant_service
  114. from backend.app.services.library_trash import library_trash_service
  115. from backend.app.services.local_backup import local_backup_service
  116. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  117. from backend.app.services.mqtt_relay import mqtt_relay
  118. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  119. from backend.app.services.notification_service import notification_service
  120. from backend.app.services.obico_detection import obico_detection_service
  121. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  122. from backend.app.services.print_scheduler import scheduler as print_scheduler
  123. from backend.app.services.print_storage import (
  124. REASON_FTP_TRANSFER_FAILED,
  125. REASON_FTPS_COOLOFF,
  126. external_storage_present,
  127. ftp_probe_paths,
  128. print_file_reachable_over_ftp,
  129. )
  130. from backend.app.services.printer_manager import (
  131. init_printer_connections,
  132. parse_plate_id,
  133. printer_manager,
  134. printer_state_to_dict,
  135. resolve_plate_id,
  136. )
  137. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  138. from backend.app.services.slot_nozzle import (
  139. nozzle_diameter_for_extruder,
  140. nozzle_flow_for_extruder,
  141. resolve_slot_nozzle,
  142. )
  143. from backend.app.services.smart_plug_manager import smart_plug_manager
  144. from backend.app.services.spool_assignment_notifications import (
  145. notify_missing_spool_assignments_on_print_start,
  146. )
  147. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  148. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  149. from backend.app.services.spoolman_tracking import (
  150. cleanup_tracking as _cleanup_spoolman_tracking,
  151. report_usage as _report_spoolman_usage,
  152. store_print_data as _store_spoolman_print_data,
  153. )
  154. from backend.app.services.tasmota import tasmota_service
  155. from backend.app.services.telegram_reactions import telegram_reaction_poller
  156. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  157. from backend.app.utils.ams_humidity import ams_humidity_percent
  158. from backend.app.utils.filament_types import printer_filament_type
  159. from backend.app.utils.fts_routing import extruder_for_inlet
  160. from backend.app.utils.local_time import utcnow_naive
  161. from backend.app.utils.print_jobs import is_internal_printer_job
  162. # =============================================================================
  163. # Dependency Check - runs before other imports to give helpful error messages
  164. # =============================================================================
  165. def _start_error_server(missing_packages: list):
  166. """Start a minimal HTTP server to display dependency errors in browser."""
  167. import os
  168. import signal
  169. from http.server import BaseHTTPRequestHandler, HTTPServer
  170. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  171. html = f"""<!DOCTYPE html>
  172. <html>
  173. <head>
  174. <title>Bambuddy - Setup Required</title>
  175. <style>
  176. body {{
  177. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  178. background: #0f172a; color: #e2e8f0;
  179. display: flex; justify-content: center; align-items: center;
  180. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  181. }}
  182. .container {{
  183. background: #1e293b; border-radius: 12px; padding: 40px;
  184. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  185. }}
  186. h1 {{ color: #f87171; margin-bottom: 10px; }}
  187. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  188. .packages {{
  189. background: #0f172a; border-radius: 8px; padding: 20px;
  190. margin: 20px 0; text-align: left;
  191. }}
  192. .packages ul {{ margin: 0; padding-left: 20px; }}
  193. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  194. .command {{
  195. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  196. margin: 15px 0; font-family: monospace; color: #4ade80;
  197. text-align: left; overflow-x: auto;
  198. }}
  199. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  200. </style>
  201. </head>
  202. <body>
  203. <div class="container">
  204. <h1>Setup Required</h1>
  205. <h2>Missing Python packages</h2>
  206. <div class="packages"><ul>{packages_html}</ul></div>
  207. <p>To fix, run this command on your server:</p>
  208. <div class="command">pip install -r requirements.txt</div>
  209. <p>Or if using a virtual environment:</p>
  210. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  211. <p class="note">After installing, restart Bambuddy:<br>
  212. <code>sudo systemctl restart bambuddy</code></p>
  213. </div>
  214. </body>
  215. </html>"""
  216. class ErrorHandler(BaseHTTPRequestHandler):
  217. def do_GET(self):
  218. self.send_response(503)
  219. self.send_header("Content-type", "text/html")
  220. self.end_headers()
  221. self.wfile.write(html.encode())
  222. def log_message(self, format, *args):
  223. print(f"[Error Server] {args[0]}")
  224. port = int(os.environ.get("PORT", 8000))
  225. print(f"\nStarting error server on http://0.0.0.0:{port}")
  226. print("Visit this URL in your browser to see the error details.\n")
  227. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  228. def shutdown(signum, frame):
  229. print("\nShutting down error server...")
  230. raise SystemExit(0)
  231. signal.signal(signal.SIGTERM, shutdown)
  232. signal.signal(signal.SIGINT, shutdown)
  233. server.serve_forever()
  234. def check_dependencies():
  235. """Check that all required packages are installed."""
  236. missing = []
  237. # Map of import name -> package name (for pip install)
  238. required = {
  239. "jwt": "PyJWT",
  240. "fastapi": "fastapi",
  241. "uvicorn": "uvicorn",
  242. "sqlalchemy": "sqlalchemy",
  243. "aiosqlite": "aiosqlite",
  244. "pydantic": "pydantic",
  245. "paho.mqtt": "paho-mqtt",
  246. }
  247. for module, package in required.items():
  248. try:
  249. __import__(module)
  250. except ImportError:
  251. missing.append(package)
  252. if missing:
  253. print("\n" + "=" * 60)
  254. print("ERROR: Missing required Python packages!")
  255. print("=" * 60)
  256. print(f"\nMissing packages: {', '.join(missing)}")
  257. print("\nTo fix, run:")
  258. print(" pip install -r requirements.txt")
  259. print("\nOr if using a virtual environment:")
  260. print(" ./venv/bin/pip install -r requirements.txt")
  261. print("=" * 60 + "\n")
  262. _start_error_server(missing)
  263. check_dependencies()
  264. # =============================================================================
  265. # Import settings first for logging configuration
  266. # Configure logging based on settings
  267. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  268. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  269. log_level = getattr(logging, log_level_str, logging.INFO)
  270. # Trace ID column ([-] when no request scope is active — startup, MQTT
  271. # callbacks, scheduled tasks not chained from a request — so the column
  272. # stays visually aligned and missing values are obvious in grep). See
  273. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  274. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  275. # Create root logger
  276. root_logger = logging.getLogger()
  277. root_logger.setLevel(log_level)
  278. # Trace-ID injection: this filter populates record.trace_id from the
  279. # per-request ContextVar so the format string above can reference it.
  280. # Attached to each HANDLER (not the root logger) because Python's
  281. # logging semantics only invoke a logger's filters on records that
  282. # *originated* at that logger — records propagated up from child
  283. # loggers (every named logger in the app) never trigger root's filter.
  284. # Putting it on the handlers means every record any handler emits gets
  285. # trace_id injected just before the formatter runs, regardless of which
  286. # logger created the record. Without this, the formatter raises
  287. # KeyError on every child-logger record and the record is silently
  288. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  289. # partially" bug we hit. See backend/app/core/trace.py for the
  290. # ContextVar the filter reads.
  291. from backend.app.core.trace import TraceIDFilter
  292. _trace_id_filter = TraceIDFilter()
  293. # Console handler - always enabled
  294. console_handler = logging.StreamHandler()
  295. console_handler.setLevel(log_level)
  296. console_handler.setFormatter(logging.Formatter(log_format))
  297. console_handler.addFilter(_trace_id_filter)
  298. root_logger.addHandler(console_handler)
  299. # File handler - only in production or if explicitly enabled
  300. if app_settings.log_to_file:
  301. log_file = app_settings.log_dir / "bambuddy.log"
  302. file_handler = RotatingFileHandler(
  303. log_file,
  304. maxBytes=app_settings.log_max_bytes,
  305. backupCount=app_settings.log_backup_count,
  306. encoding="utf-8",
  307. )
  308. file_handler.setLevel(log_level)
  309. file_handler.setFormatter(logging.Formatter(log_format))
  310. file_handler.addFilter(_trace_id_filter)
  311. root_logger.addHandler(file_handler)
  312. logging.info("Logging to file: %s", log_file)
  313. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  314. # access logger with propagate=False by default, so without this attach
  315. # there is no on-disk record of which endpoint triggered a server-state
  316. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  317. # for exactly this reason. Filtered to write methods only
  318. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  319. # frontend don't churn the rotation window faster than it's useful.
  320. from backend.app.core.logging_filters import (
  321. CancelledPoolNoiseFilter,
  322. WriteRequestsOnlyFilter,
  323. )
  324. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  325. uvicorn_access_logger.addHandler(file_handler)
  326. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  327. # Uvicorn's access logger has propagate=False (its own default), so the
  328. # root-attached TraceIDFilter never sees these records. Attach a
  329. # second instance directly so HTTP access lines carry the same trace
  330. # ID column as the application logs they correlate with.
  331. uvicorn_access_logger.addFilter(TraceIDFilter())
  332. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  333. # BaseHTTPMiddleware cancelling the inner task scope on client
  334. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  335. # underlying transaction leak; this filter only suppresses the residual
  336. # log records that pre-existing pools still emit during their cleanup.
  337. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  338. # Reduce noise from third-party libraries in production
  339. if not app_settings.debug:
  340. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  341. logging.getLogger("httpcore").setLevel(logging.WARNING)
  342. logging.getLogger("httpx").setLevel(logging.WARNING)
  343. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  344. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  345. # Track active prints: {(printer_id, filename): archive_id}
  346. _active_prints: dict[tuple[int, str], int] = {}
  347. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  348. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  349. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  350. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  351. # instead of running its own grab-now chain when present, so the finish photo
  352. # captures the better-framed pre-bed-drop moment without us having to force
  353. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  354. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  355. #
  356. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  357. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  358. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  359. # bank and the others are not — so the consumer can't tell them apart and
  360. # must not rotate again.
  361. _stage22_finish_frames: dict[int, bytes] = {}
  362. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  363. # `finally` block (whether it captured a frame or not). The consumer in
  364. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  365. # so the FINISH-state fallback path — where moment and completion are dispatched
  366. # back-to-back — doesn't race past the producer with an empty pop, and the
  367. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  368. # grab (Bambu printers allow only one RTSP client at a time).
  369. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  370. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  371. # layer-change and on print-progress advances (#2547) while the model is still
  372. # printing, then consumed by the FINISH-state finish-photo path when the
  373. # dispatcher recorded that it injected End G-code into this print. Bambu
  374. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  375. # plate-swap) has run, so a live grab there would capture the swapped/empty
  376. # plate.
  377. #
  378. # The load-bearing property: both drivers are print telemetry that stops before
  379. # the End G-code executes — no further layer_num increases, and mc_percent
  380. # freezes — so the last banked frame is always the finished print before the
  381. # swap. Anything added as a third driver must hold that same property.
  382. _inprint_frame_bank: dict[int, bytes] = {}
  383. # Monotonic timestamp of the last banked frame per printer — throttles banking
  384. # so tall prints don't add a camera grab on every layer.
  385. _inprint_frame_bank_ts: dict[int, float] = {}
  386. # Minimum seconds between banked frames, except the final object layer which
  387. # always refreshes for the best framing.
  388. _INPRINT_BANK_MIN_INTERVAL = 25.0
  389. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  390. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  391. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  392. # the first connected status update for that connection; transitions back
  393. # to False whenever we observe `state.connected = False` so the next
  394. # reconnect re-arms reconciliation. Keyed by printer_id.
  395. _printer_reconciled_since_connect: dict[int, bool] = {}
  396. # Same edge, same keying, for priming the printer's calibration table exactly
  397. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  398. # is otherwise filled only when someone opens the Profiles page or Configure
  399. # Slot, when a GitHub backup runs, or when the printer happens to answer
  400. # somebody else's query on the report topic. Until then the AMS slot card has
  401. # no K value to show on the printers whose trays carry none of their own
  402. # (#2854 — H2-series report cali_idx and nothing more).
  403. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  404. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  405. # {(printer_id, filename): archive_id}
  406. _expected_prints: dict[tuple[int, str], int] = {}
  407. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  408. # Used by usage tracker to map 3MF slots to physical AMS trays
  409. _print_ams_mappings: dict[int, list[int]] = {}
  410. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  411. _print_cost_center_ids: dict[int, int] = {}
  412. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  413. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  414. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  415. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  416. # for the queue path. Cleared on print completion or TTL eviction.
  417. _print_plate_ids: dict[int, int] = {}
  418. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  419. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  420. _last_progress_milestone: dict[int, int] = {}
  421. # Track whether first layer complete notification has been sent for current print
  422. _first_layer_notified: dict[int, bool] = {}
  423. # Track whether we already sent a kill-switch stop for the current unauthorized print
  424. _unauthorized_print_kill_sent: set[int] = set()
  425. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  426. # lookup briefly so an unknown active print does not query the database on
  427. # every status frame. A short TTL keeps settings changes responsive.
  428. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  429. _kill_switch_setting_cache: tuple[bool, float] | None = None
  430. # Provider notification started when the kill switch stops a print. The later
  431. # MQTT print-complete callback awaits this task and only sends its regular
  432. # provider notification when the immediate attempt failed.
  433. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  434. # HMS faults already notified, with when each was last seen:
  435. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  436. # fault that flickers beside a held notice was forgotten on every gap and
  437. # notified on every return (#3226). The window is long because the measured
  438. # gaps reach 64 s.
  439. _notified_hms_errors: dict[int, dict[str, float]] = {}
  440. _HMS_CLEAR_GRACE_SECONDS = 600.0
  441. # The print state each printer was last seen in, and the faults recorded before
  442. # it last changed, which are forgotten as soon as they are gone (see
  443. # _take_new_hms_faults).
  444. _hms_print_state: dict[int, str] = {}
  445. _hms_forget_when_gone: dict[int, set[str]] = {}
  446. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  447. # Used for snapshot-diff detection at print completion
  448. _timelapse_baselines: dict[int, set[str]] = {}
  449. # Track printers waiting for bed to cool after print completion.
  450. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  451. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  452. _bed_cool_waiters: dict[int, dict] = {}
  453. # Track printers where the user explicitly stopped the print from the queue UI.
  454. # When on_print_complete fires with status "failed" for these printers we treat it
  455. # as "cancelled" (stopped by user) so the correct notification email is sent.
  456. _user_stopped_printers: set[int] = set()
  457. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  458. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  459. # holds the previous observation so we only fire on the True → False edge (a
  460. # False → False repeat doesn't notify; an initial False at startup doesn't
  461. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  462. # holds the per-printer pending asyncio task that fires the notification
  463. # after a debounce window — cancelled if the printer reconnects before the
  464. # window elapses, so transient MQTT blips don't flood the user.
  465. _printer_last_connected: dict[int, bool] = {}
  466. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  467. # Debounce: a printer must stay offline this long before we notify. Sized
  468. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  469. # so a single stale-trigger cooldown isn't enough to fire — only a real
  470. # offline that survives one reconnect attempt notifies.
  471. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  472. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  473. # when status="failed" to label the print's failure_reason in archives.
  474. #
  475. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  476. # which is wrong on two counts:
  477. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  478. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  479. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  480. # the public wiki) as part of its user-cancel sequence. Matching on the module
  481. # alone caused user-cancellations to be archived as "Layer shift" failures.
  482. # We now match by full short code only — anything not in this map leaves
  483. # failure_reason=None rather than guessing.
  484. # Values are the canonical camelCase failure-reason keys, NOT display labels
  485. # (issue #2974). The vocabulary is enforced on writes by
  486. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  487. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  488. # Statistics breakdown. Storing a label here instead put a second spelling of
  489. # the same cause into one column: the Failure Analysis widget groups on the raw
  490. # value, so a print the backend classified and an identical one a user
  491. # classified counted as two different reasons, and the label form could never
  492. # be translated because there was no key for ``t()`` to resolve.
  493. _HMS_FAILURE_REASONS: dict[str, str] = {
  494. # Layer shift / step loss
  495. "0300_4057": "layerShift",
  496. "0300_4068": "layerShift",
  497. "0300_800C": "layerShift",
  498. # Filament runout (printer-side & per-AMS-slot)
  499. "0300_8004": "filamentRunout",
  500. "0700_8011": "filamentRunout",
  501. "0701_8011": "filamentRunout",
  502. "0702_8011": "filamentRunout",
  503. "0703_8011": "filamentRunout",
  504. "0704_8011": "filamentRunout",
  505. "0705_8011": "filamentRunout",
  506. "0706_8011": "filamentRunout",
  507. "0707_8011": "filamentRunout",
  508. "07FF_8011": "filamentRunout",
  509. # Clogged nozzle / extruder
  510. "0300_4006": "cloggedNozzle",
  511. "0300_8016": "cloggedNozzle",
  512. "0300_801C": "cloggedNozzle",
  513. "0700_8003": "cloggedNozzle",
  514. "0700_8007": "cloggedNozzle",
  515. "0700_8013": "cloggedNozzle",
  516. "0701_8003": "cloggedNozzle",
  517. "0701_8007": "cloggedNozzle",
  518. "0701_8013": "cloggedNozzle",
  519. "0702_8003": "cloggedNozzle",
  520. # AI print monitoring — spaghetti / the model coming off the plate.
  521. # `spaghettiDetached` is a key the archive editor already offers for this
  522. # failure mode, not a new one, so a derived reason opens the dropdown on
  523. # that option rather than blank — and survives the next save, which clears
  524. # any value the editor does not recognise.
  525. #
  526. # A module-0x0C row is safe here despite the warning above: that warning is
  527. # about matching on the module alone, and 0C00_8042 is a full short code
  528. # with a documented meaning ("The AI print monitor has detected a spaghetti
  529. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  530. # cannot collide.
  531. #
  532. # 0300_8003's own text ends "before continuing your print", but on an X2D
  533. # it arrives with the print already paused, offering only
  534. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  535. #
  536. # Two neighbours are left out on purpose, so this does not get re-derived:
  537. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  538. # reads as a warning about a print that is still running, not a halt.
  539. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  540. # the waste chute. That is not the print failing.
  541. #
  542. # That line is drawn from the text, not from `severity`, because severity
  543. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  544. # module/error word with no level in it, and bambu_mqtt.py gives every
  545. # print_error entry a flat severity=3. Matching on the short code alone is
  546. # the right shape for derive_failure_reason, not an omission.
  547. "0300_8003": "spaghettiDetached",
  548. "0C00_8042": "spaghettiDetached",
  549. }
  550. def _hms_short_code(attr: int, code: int | str) -> str:
  551. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  552. if isinstance(code, str):
  553. code_int = int(code.replace("0x", ""), 16) if code else 0
  554. else:
  555. code_int = int(code or 0)
  556. attr_int = int(attr or 0)
  557. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  558. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  559. """Derive the failure_reason key for an archived print.
  560. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  561. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  562. no HMS code matches (don't guess — null is honest). The keys are the
  563. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  564. translated at render time.
  565. """
  566. if status in ("aborted", "cancelled"):
  567. return "userCancelled"
  568. if status != "failed":
  569. return None
  570. for err in hms_errors or []:
  571. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  572. if short_code in _HMS_FAILURE_REASONS:
  573. return _HMS_FAILURE_REASONS[short_code]
  574. return None
  575. # Track created_by_id for expected prints so the user email can be sent even when
  576. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  577. # {(printer_id, filename): created_by_id}
  578. _expected_print_creators: dict[tuple[int, str], int] = {}
  579. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  580. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  581. # updates for the same printer in quick succession (~30 ms apart, observed in
  582. # the wild on H2D + dual AMS).
  583. #
  584. # Without this serialisation, two concurrent on_ams_change callbacks each read
  585. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  586. # the second commit hits
  587. # IntegrityError: duplicate key value violates unique constraint
  588. # "spool_assignment_printer_id_ams_id_tray_id_key"
  589. # SQLite's WAL serial-write semantics had been silently swallowing the race
  590. # until optional Postgres support landed (asyncpg allows true concurrent
  591. # transactions and surfaces the constraint violation).
  592. #
  593. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  594. # assign) are inside the lock. The Spoolman sync block further down stays
  595. # concurrent because it's network-bound and idempotent.
  596. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  597. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  598. """Return the per-printer assignment lock, creating it on first use."""
  599. lock = _ams_assignment_locks.get(printer_id)
  600. if lock is None:
  601. lock = asyncio.Lock()
  602. _ams_assignment_locks[printer_id] = lock
  603. return lock
  604. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  605. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  606. # tag tuple changes for the slot. Cleared when the slot is reported empty
  607. # so remove + reinsert reliably re-prompts the UI.
  608. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  609. async def _broadcast_unknown_tag(
  610. *,
  611. printer_id: int,
  612. ams_id: int,
  613. tray_id: int,
  614. tag_uid: str,
  615. tray_uuid: str,
  616. tray_type: str | None = None,
  617. tray_color: str | None = None,
  618. tray_sub_brands: str | None = None,
  619. tray_count: int | None = None,
  620. ) -> None:
  621. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  622. _logger = logging.getLogger(__name__)
  623. slot_key = (ams_id, tray_id)
  624. tag_key = (tag_uid or "", tray_uuid or "")
  625. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  626. if per_printer.get(slot_key) == tag_key:
  627. _logger.debug(
  628. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  629. printer_id,
  630. ams_id,
  631. tray_id,
  632. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  633. )
  634. return
  635. _logger.info(
  636. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  637. printer_id,
  638. ams_id,
  639. tray_id,
  640. tray_type,
  641. tray_color,
  642. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  643. )
  644. # Broadcast first; only commit the dedup if the WS write succeeds.
  645. # If broadcast raises, the next MQTT push retries instead of being
  646. # permanently silenced by a poisoned dedup entry.
  647. await ws_manager.broadcast(
  648. {
  649. "type": "unknown_tag",
  650. "printer_id": printer_id,
  651. "ams_id": ams_id,
  652. "tray_id": tray_id,
  653. "tag_uid": tag_uid,
  654. "tray_uuid": tray_uuid,
  655. "tray_type": tray_type,
  656. "tray_color": tray_color,
  657. "tray_sub_brands": tray_sub_brands,
  658. "tray_count": tray_count,
  659. }
  660. )
  661. per_printer[slot_key] = tag_key
  662. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  663. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  664. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  665. if per_printer is None:
  666. return
  667. per_printer.pop((ams_id, tray_id), None)
  668. # TTL for expected-print entries: evict registrations older than this to prevent
  669. # unbounded growth when a print is registered but never starts (e.g. printer
  670. # disconnect, app restart, print started from the printer panel).
  671. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  672. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  673. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  674. # Cleanup loop interval
  675. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  676. _expected_prints_cleanup_task: asyncio.Task | None = None
  677. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  678. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  679. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  680. possible_keys: list[tuple[int, str]] = []
  681. filename = (state.gcode_file or state.current_print or "").strip()
  682. subtask_name = (state.subtask_name or "").strip()
  683. if subtask_name:
  684. possible_keys.append((printer_id, subtask_name))
  685. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  686. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  687. if filename:
  688. base_name = filename.rsplit("/", 1)[-1]
  689. if base_name.endswith(".gcode.3mf"):
  690. root_name = base_name[: -len(".gcode.3mf")]
  691. possible_keys.append((printer_id, root_name))
  692. possible_keys.append((printer_id, base_name))
  693. possible_keys.append((printer_id, f"{root_name}.gcode"))
  694. possible_keys.append((printer_id, f"{root_name}.3mf"))
  695. elif base_name.endswith(".3mf"):
  696. root_name = base_name[: -len(".3mf")]
  697. possible_keys.append((printer_id, root_name))
  698. possible_keys.append((printer_id, base_name))
  699. elif base_name.endswith(".gcode"):
  700. root_name = base_name[: -len(".gcode")]
  701. possible_keys.append((printer_id, root_name))
  702. possible_keys.append((printer_id, f"{root_name}.3mf"))
  703. possible_keys.append((printer_id, base_name))
  704. else:
  705. possible_keys.append((printer_id, base_name))
  706. possible_keys.append((printer_id, f"{base_name}.3mf"))
  707. return possible_keys
  708. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  709. """Check the cheap, process-local print ownership signals."""
  710. if printer_manager.get_current_print_user(printer_id):
  711. return True
  712. return any(key in _expected_prints or key in _active_prints for key in _build_status_print_keys(printer_id, state))
  713. async def _is_printer_kill_switch_enabled_cached() -> bool:
  714. """Return the kill-switch setting without querying on every MQTT frame."""
  715. global _kill_switch_setting_cache
  716. now = time.monotonic()
  717. if _kill_switch_setting_cache is not None:
  718. enabled, expires_at = _kill_switch_setting_cache
  719. if now < expires_at:
  720. return enabled
  721. async with async_session() as db:
  722. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  723. enabled = await is_printer_kill_switch_enabled(db)
  724. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  725. return enabled
  726. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  727. """Resolve whether the current print was started by Bambuddy.
  728. ``None`` means identity is not yet safe to decide. The kill switch must
  729. defer in that case: stopping a print is irreversible, and the first status
  730. frames after a restart may arrive before all subtask fields are populated.
  731. """
  732. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  733. return True
  734. possible_keys = _build_status_print_keys(printer_id, state)
  735. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  736. # is on disk. subtask_id is minted per print and pins the answer to the job
  737. # actually running, rather than to an unrelated one that reuses a filename.
  738. raw_subtask_id = getattr(state, "subtask_id", None)
  739. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  740. if subtask_id in ("", "0"):
  741. return None
  742. from backend.app.models.archive import PrintArchive
  743. result = await db.execute(
  744. select(PrintArchive)
  745. .where(
  746. PrintArchive.printer_id == printer_id,
  747. PrintArchive.status == "printing",
  748. PrintArchive.subtask_id == subtask_id,
  749. )
  750. .order_by(PrintArchive.created_at.desc())
  751. .limit(1)
  752. )
  753. archive = result.scalar_one_or_none()
  754. # An archive row on its own proves nothing: `on_print_start` archives every
  755. # print it observes, including ones started from Bambu Studio or Handy, and
  756. # stamps them with the same status and subtask_id. Authorizing on its mere
  757. # existence would disable the kill switch the moment the 3MF finishes
  758. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  759. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  760. # (carried over from the queue item that started it).
  761. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  762. # Rehydrate the fast in-memory path for subsequent status frames. Include
  763. # both the archive filename and every normalized key reported by MQTT.
  764. _active_prints[(printer_id, archive.filename)] = archive.id
  765. for key in possible_keys:
  766. _active_prints[key] = archive.id
  767. return True
  768. # No dispatch marker. Before calling this someone else's print, check whether
  769. # Bambuddy has a job of its own running on this printer: a library-file
  770. # dispatch has no archive at send time, and an archive created seconds later
  771. # by `on_print_start` carries neither marker. The queue row, which the
  772. # scheduler commits to status="printing" before the MQTT send, is the one
  773. # durable record every Bambuddy print has. It cannot be tied to this
  774. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  775. # print is irreversible, and refusing to act costs nothing but a log line.
  776. from backend.app.models.print_queue import PrintQueueItem
  777. dispatched_here = await db.scalar(
  778. select(PrintQueueItem.id)
  779. .where(
  780. PrintQueueItem.printer_id == printer_id,
  781. PrintQueueItem.status == "printing",
  782. )
  783. .limit(1)
  784. )
  785. if dispatched_here is not None:
  786. return None
  787. return False
  788. async def _send_kill_switch_provider_notification(
  789. printer_id: int,
  790. printer_name: str,
  791. data: dict,
  792. ) -> bool:
  793. """Send the immediate print-stopped provider notification.
  794. Returning a success flag lets the normal MQTT completion path retry when
  795. this early notification could not be delivered.
  796. """
  797. logger = logging.getLogger(__name__)
  798. try:
  799. async with async_session() as db:
  800. await notification_service.on_print_complete(
  801. printer_id,
  802. printer_name,
  803. "stopped",
  804. data,
  805. db,
  806. )
  807. return True
  808. except Exception as e:
  809. logger.warning(
  810. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  811. printer_id,
  812. e,
  813. )
  814. return False
  815. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  816. """Wait for an immediate kill-switch notification, if one was scheduled."""
  817. if task is None:
  818. return False
  819. try:
  820. return await task
  821. except Exception as e:
  822. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  823. return False
  824. async def _get_plug_energy(plug, db) -> dict | None:
  825. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  826. For HA plugs, configures the service with current settings from DB.
  827. For MQTT plugs, returns data from the subscription service.
  828. For REST plugs, polls the status URL with JSON path extraction.
  829. """
  830. if plug.plug_type == "homeassistant":
  831. from backend.app.api.routes.settings import get_homeassistant_settings
  832. ha_settings = await get_homeassistant_settings(db)
  833. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  834. return await homeassistant_service.get_energy(plug)
  835. elif plug.plug_type == "mqtt":
  836. # MQTT plugs report "today" energy, not lifetime total
  837. # For per-print tracking, we use "today" as the counter (resets at midnight)
  838. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  839. if mqtt_data:
  840. return {
  841. "power": mqtt_data.power,
  842. "today": mqtt_data.energy,
  843. "total": mqtt_data.energy, # Use today as total for per-print calculations
  844. }
  845. return None
  846. elif plug.plug_type == "rest":
  847. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  848. return await rest_smart_plug_service.get_energy(plug)
  849. else:
  850. return await tasmota_service.get_energy(plug)
  851. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  852. """Capture the smart plug lifetime counter on the archive at print start.
  853. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  854. tracking survives a backend restart mid-print. The print-end handler reads
  855. this value back from the DB and computes the delta against the current
  856. plug counter.
  857. """
  858. _logger = logging.getLogger(__name__)
  859. try:
  860. candidates = await energy_plug_candidates(db, printer_id)
  861. if not candidates:
  862. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  863. return False
  864. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  865. if selected is None:
  866. # Naming the plugs matters here: with several linked to one printer
  867. # this is the difference between "the meter is offline" and "you
  868. # linked only accessories" (#2859).
  869. _logger.warning(
  870. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  871. printer_id,
  872. archive.id,
  873. ", ".join(plug.name for plug in candidates),
  874. )
  875. return False
  876. plug, energy = selected
  877. archive.energy_start_kwh = float(energy["total"])
  878. # With the plug's snapshots, what lets the cost follow the price over
  879. # the print rather than take the price at its end (#1251). A price that
  880. # can't be had must not cost the print its energy reading.
  881. archive.energy_start_at = utcnow_naive()
  882. archive.energy_start_plug_id = plug.id
  883. try:
  884. from backend.app.services.energy_price import current_price
  885. archive.energy_start_price = await current_price(db)
  886. except Exception as e:
  887. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  888. archive.energy_start_price = None
  889. await db.commit()
  890. _logger.info(
  891. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  892. f" ({context})" if context else "",
  893. archive.id,
  894. plug.name,
  895. energy["total"],
  896. )
  897. return True
  898. except Exception as e:
  899. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  900. return False
  901. def register_expected_print(
  902. printer_id: int,
  903. filename: str,
  904. archive_id: int,
  905. ams_mapping: list[int] | None = None,
  906. created_by_id: int | None = None,
  907. cost_center_id: int | None = None,
  908. plate_id: int | None = None,
  909. ):
  910. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  911. # Store with multiple filename variations to catch different naming patterns
  912. _expected_prints[(printer_id, filename)] = archive_id
  913. # Also store without .3mf extension if present
  914. if filename.endswith(".3mf"):
  915. base = filename[:-4]
  916. _expected_prints[(printer_id, base)] = archive_id
  917. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  918. # Store AMS mapping for usage tracking at print completion
  919. if ams_mapping is not None:
  920. _print_ams_mappings[archive_id] = ams_mapping
  921. if cost_center_id is not None:
  922. _print_cost_center_ids[archive_id] = cost_center_id
  923. # Store plate_id for usage tracking when this is a single-plate dispatch from
  924. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  925. # file's filament total to the spool instead of just the printed plate (#1697).
  926. if plate_id is not None:
  927. _print_plate_ids[archive_id] = plate_id
  928. # Store created_by_id so the user start email can be sent even when the archive
  929. # itself has no created_by_id (e.g. library-file-based queue prints)
  930. if created_by_id is not None:
  931. _expected_print_creators[(printer_id, filename)] = created_by_id
  932. if filename.endswith(".3mf"):
  933. base = filename[:-4]
  934. _expected_print_creators[(printer_id, base)] = created_by_id
  935. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  936. # Record registration time for TTL-based eviction
  937. _registered_at = time.monotonic()
  938. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  939. if filename.endswith(".3mf"):
  940. base = filename[:-4]
  941. _expected_print_registered_at[(printer_id, base)] = _registered_at
  942. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  943. logging.getLogger(__name__).info(
  944. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  945. )
  946. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  947. """Undo :func:`register_expected_print` when the print never went out.
  948. Registration has to happen *before* the MQTT print command, because the
  949. printer can report the print before the line after the send executes. So
  950. every path that registers and then fails to send — a cancel winning the
  951. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  952. between — leaves an expectation for a print that will never arrive.
  953. The TTL sweep evicts those after two hours, which is far longer than it
  954. takes a user to react to a failed dispatch by pressing print again: that
  955. reprint would be folded into the *old* archive and take the stale
  956. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  957. Mirrors the sweep's rules, including the one that is easy to get wrong:
  958. ``_print_ams_mappings`` / ``_print_plate_ids`` are keyed by archive, not by
  959. file, so they may only be dropped once no live key still points at that
  960. archive.
  961. """
  962. keys = [(printer_id, filename)]
  963. if filename.endswith(".3mf"):
  964. base = filename[:-4]
  965. keys.append((printer_id, base))
  966. keys.append((printer_id, f"{base}.gcode"))
  967. removed = False
  968. for key in keys:
  969. if _expected_prints.pop(key, None) is not None:
  970. removed = True
  971. _expected_print_creators.pop(key, None)
  972. _expected_print_registered_at.pop(key, None)
  973. if archive_id not in set(_expected_prints.values()):
  974. _print_ams_mappings.pop(archive_id, None)
  975. _print_plate_ids.pop(archive_id, None)
  976. if removed:
  977. logging.getLogger(__name__).info(
  978. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  979. printer_id,
  980. filename,
  981. archive_id,
  982. )
  983. def _compute_run_filament_grams(
  984. status: str,
  985. archive_filament_used_grams: float | None,
  986. progress: float | int | None,
  987. usage_results: list[dict] | None,
  988. ) -> float | None:
  989. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  990. Priority for every status:
  991. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  992. weight delta — same source that drives "Total Consumed" on the
  993. Inventory page, so Stats and Inventory totals stay aligned).
  994. 2. For ``completed``: the slicer estimate (no tracker available, fall
  995. back to the canonical "this print used X" value).
  996. 3. For partial statuses: ``estimate * progress%``.
  997. 4. ``None`` if nothing is known.
  998. """
  999. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1000. if tracked_grams > 0:
  1001. return round(tracked_grams, 1)
  1002. if status == "completed":
  1003. return archive_filament_used_grams
  1004. if archive_filament_used_grams:
  1005. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1006. if scale > 0:
  1007. return round(archive_filament_used_grams * scale, 1)
  1008. return None
  1009. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  1010. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1011. stored_ams_mapping = data.get("ams_mapping")
  1012. if not stored_ams_mapping and archive_id:
  1013. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  1014. return stored_ams_mapping
  1015. def _get_start_plate_id(archive_id: int | None) -> int | None:
  1016. """Resolve plate_id for print start without consuming stored direct-Print state.
  1017. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1018. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1019. read it back at print-start without popping (the entry is popped on print
  1020. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1021. """
  1022. if archive_id is None:
  1023. return None
  1024. return _print_plate_ids.get(archive_id)
  1025. def _partial_progress_scale(progress: int | float | None) -> float:
  1026. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1027. Used by every site that multiplies a "would-have-used" slicer estimate
  1028. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1029. so the three sites in ``_background_notifications`` (and the per-plate
  1030. override helper) can't drift apart on the coercion shape.
  1031. """
  1032. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1033. def _scope_notification_archive_data_to_plate(
  1034. archive_data: dict,
  1035. archive_file_path: str | None,
  1036. plate_id: int | None,
  1037. print_status: str,
  1038. progress: int | float | None,
  1039. base_dir: Path,
  1040. ) -> dict:
  1041. """Override summed-across-plates totals in ``archive_data`` with the values
  1042. for ``plate_id`` so the completion notification reports what was actually
  1043. printed, not the whole project (#1785).
  1044. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1045. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1046. the archive card's "whole project" headline, wrong for the completion
  1047. notification of a single-plate print. The queue UI already re-reads the
  1048. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1049. notification payload (filament grams, time estimate, per-slot breakdown).
  1050. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1051. no per-plate values — in every fail case the original ``archive_data`` is
  1052. returned unchanged so the notification still sends.
  1053. """
  1054. if plate_id is None or not archive_file_path:
  1055. return archive_data
  1056. from backend.app.utils.threemf_tools import (
  1057. extract_filament_usage_from_3mf,
  1058. extract_print_time_from_3mf,
  1059. )
  1060. archive_path = base_dir / archive_file_path
  1061. if not archive_path.exists():
  1062. return archive_data
  1063. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1064. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1065. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1066. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1067. if plate_time:
  1068. archive_data["print_time_seconds"] = plate_time
  1069. # Gate both the grams headline AND the per-slot breakdown on the same
  1070. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1071. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1072. # to the project-level grams the archive columns already provide rather
  1073. # than ship a project-level headline next to an all-zero per-plate
  1074. # breakdown.
  1075. if plate_grams > 0:
  1076. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1077. archive_data["filament_slots"] = [
  1078. {
  1079. "slot_id": s.get("slot_id"),
  1080. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1081. "type": s.get("type", ""),
  1082. "color": s.get("color", ""),
  1083. }
  1084. for s in plate_slots
  1085. ]
  1086. return archive_data
  1087. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1088. """Best-effort filament metadata from the MQTT print-start snapshot.
  1089. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1090. file during print, see #1533) so the fallback PrintArchive still has
  1091. enough filament info to support the inventory views and AMS-expansion
  1092. planning the operator opens it for. Returns a dict with optional
  1093. ``filament_type`` and ``filament_color`` keys in the same
  1094. comma-separated format the 3MF extractor produces, so the rest of the
  1095. codebase treats the fallback archive identically to a normal one.
  1096. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1097. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1098. entries). When supplied, only the slots actually consumed by this
  1099. print contribute. Without it the function falls back to every loaded
  1100. AMS slot — less accurate but still useful.
  1101. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1102. that the unit tests pass directly, AND the on_print_start callback
  1103. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1104. bambu_mqtt service hands to main.py at runtime. The original
  1105. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1106. handled the inner shape and silently returned ``{}`` for every real
  1107. print start, leaving fallback archives' filament fields NULL — the
  1108. exact regression the fix was meant to close. Reported with a log
  1109. proving the AMS state was right there at
  1110. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1111. """
  1112. result: dict[str, str] = {}
  1113. # Look at the on_print_start wrapper first, then the inner shape.
  1114. raw_data = (data or {}).get("raw_data")
  1115. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1116. if not isinstance(ams_root, dict):
  1117. ams_root = (data or {}).get("ams") or {}
  1118. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1119. if not isinstance(ams_units, list) or not ams_units:
  1120. return result
  1121. # Map global tray id (unit * 4 + tray) → (type, color).
  1122. loaded: dict[int, tuple[str, str]] = {}
  1123. for unit in ams_units:
  1124. if not isinstance(unit, dict):
  1125. continue
  1126. try:
  1127. unit_id = int(unit.get("id", 0))
  1128. except (TypeError, ValueError):
  1129. continue
  1130. for tray in unit.get("tray") or []:
  1131. if not isinstance(tray, dict):
  1132. continue
  1133. try:
  1134. tray_id = int(tray.get("id", 0))
  1135. except (TypeError, ValueError):
  1136. continue
  1137. ttype = (tray.get("tray_type") or "").strip()
  1138. tcolor = (tray.get("tray_color") or "").strip().upper()
  1139. if not ttype:
  1140. continue # Empty / unloaded slot.
  1141. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  1142. if not loaded:
  1143. return result
  1144. if ams_mapping:
  1145. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1146. filaments = [loaded[g] for g in used_ids if g in loaded]
  1147. if not filaments:
  1148. return result # Mapping points entirely at slots we have no data for.
  1149. else:
  1150. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1151. types_joined = ",".join(f[0] for f in filaments)
  1152. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1153. # Column limits per backend/app/models/archive.py: filament_type=50,
  1154. # filament_color=200.
  1155. if types_joined:
  1156. result["filament_type"] = types_joined[:50]
  1157. if colors_joined:
  1158. result["filament_color"] = colors_joined[:200]
  1159. return result
  1160. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1161. """Start a layer-timelapse session for *archive_id* when the printer has
  1162. an external camera configured. Returns True if a session was started.
  1163. Three call sites in on_print_start (expected-archive promotion, fallback
  1164. archive creation, fresh-archive creation) used to inline this same
  1165. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1166. on the first pass). Centralising the conditional + call here makes the
  1167. contract testable in isolation and keeps the three sites locked in step.
  1168. """
  1169. if not (printer.external_camera_enabled and printer.external_camera_url):
  1170. return False
  1171. from backend.app.services.layer_timelapse import start_session
  1172. start_session(
  1173. printer_id,
  1174. archive_id,
  1175. printer.external_camera_url,
  1176. printer.external_camera_type or "mjpeg",
  1177. snapshot_url=printer.external_camera_snapshot_url,
  1178. rotation=getattr(printer, "camera_rotation", 0),
  1179. )
  1180. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1181. return True
  1182. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1183. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1184. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1185. — since #2926 — the description the parser already resolved, which is preferred
  1186. when present so the queue's failure reason reads the same as the status
  1187. response. The short code still produces the bracketed label, and still
  1188. resolves the sentence for a caller whose entries predate the field. An entry
  1189. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1190. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1191. label when no description is on file. Returns None for an empty list so
  1192. callers can leave error_message unset.
  1193. """
  1194. if not hms_errors:
  1195. return None
  1196. from backend.app.services.hms_errors import get_error_description
  1197. parts: list[str] = []
  1198. for err in hms_errors:
  1199. try:
  1200. # `_hms_short_code` rather than a local derivation: this one used to
  1201. # format the error without masking it to 16 bits, so an `hms[]` entry
  1202. # whose code carries an alert-level group produced a five-digit label
  1203. # like "0500_3000A" — not a code the user can look up, and never a
  1204. # catalogue key, so the sentence was lost with it.
  1205. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1206. except (TypeError, ValueError):
  1207. continue
  1208. description = err.get("description") or get_error_description(short_code)
  1209. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1210. # groups and is not a code anyone can look up; its full code in the
  1211. # printer screen's four groups is (#2728).
  1212. full_code = str(err.get("full_code") or "")
  1213. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1214. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1215. return "; ".join(parts) if parts else None
  1216. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1217. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1218. print completes successfully. Gated to status=='completed': failed, cancelled
  1219. and aborted prints do not count as usage. Caller is responsible for committing
  1220. the session. No-op when the queue item has no linked library file (e.g. reprints
  1221. from an archive). See #1008."""
  1222. if queue_status != "completed" or item.library_file_id is None:
  1223. return
  1224. from backend.app.models.library import LibraryFile
  1225. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1226. if lib_file is None:
  1227. return
  1228. lib_file.print_count = (lib_file.print_count or 0) + 1
  1229. lib_file.last_printed_at = datetime.now(timezone.utc)
  1230. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1231. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1232. When on_print_complete fires with status 'failed' for a printer in this set we
  1233. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1234. rather than a 'print failed' notification.
  1235. """
  1236. _user_stopped_printers.add(printer_id)
  1237. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1238. _last_status_broadcast: dict[int, str] = {}
  1239. # Track printers where we've updated nozzle_count
  1240. _nozzle_count_updated: set[int] = set()
  1241. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1242. """Wait the debounce window then fire `on_printer_offline` if the printer
  1243. is still offline.
  1244. Scheduled by `on_printer_status_change` on the connected → disconnected
  1245. edge (#1752). Cancelled by the same handler if the printer reconnects
  1246. before the window elapses, so a single MQTT blip + recovery doesn't
  1247. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1248. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1249. route through the same status-change callback, so this covers both.
  1250. """
  1251. logger = logging.getLogger(__name__)
  1252. try:
  1253. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1254. still_offline = not printer_manager.is_connected(printer_id)
  1255. logger.info(
  1256. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1257. printer_id,
  1258. still_offline,
  1259. )
  1260. if not still_offline:
  1261. return
  1262. async with async_session() as db:
  1263. from backend.app.models.printer import Printer
  1264. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1265. printer = result.scalar_one_or_none()
  1266. if not printer:
  1267. logger.warning(
  1268. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1269. printer_id,
  1270. )
  1271. return
  1272. logger.info(
  1273. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1274. printer_id,
  1275. printer.name,
  1276. )
  1277. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1278. except asyncio.CancelledError:
  1279. raise
  1280. except Exception as e:
  1281. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1282. finally:
  1283. _printer_offline_notify_tasks.pop(printer_id, None)
  1284. def _hms_notify_key(error) -> str:
  1285. """What identifies a fault for notification de-duplication.
  1286. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1287. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1288. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1289. and -0006 together) shared a key and only the first was ever notified. An
  1290. entry without a full code falls back to attr and code together.
  1291. """
  1292. full_code = getattr(error, "full_code", "") or ""
  1293. if full_code:
  1294. return full_code.upper()
  1295. return f"{error.attr:08X}:{error.code}"
  1296. def _hms_fault_counts(error) -> bool:
  1297. """Whether a fault counts as a problem: the same rule the frontend's
  1298. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1299. It counts when Bambu publishes text for it or it offers action buttons, and
  1300. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1301. no actions does not count: those are things like "the top cover is open" or
  1302. "the chamber is hot, fan speed increased", which a printer can hold through
  1303. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1304. it always has; those are prompts such as "unable to start drying" (#2728).
  1305. """
  1306. if error.severity < 1:
  1307. return False
  1308. has_actions = bool(getattr(error, "actions", None))
  1309. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1310. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1311. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1312. """The new faults that count (see ``_hms_fault_counts``).
  1313. These go to the MQTT relay; the caller also needs a description before it
  1314. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1315. used to read ``severity >= 2`` when severity held the part byte; on the real
  1316. level that would drop the task-stopping errors (#2728).
  1317. """
  1318. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1319. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1320. """The faults on this printer not notified yet, and record them as notified.
  1321. Tracking is updated before anything is sent, so concurrent status callbacks
  1322. cannot notify the same fault twice. A notified fault is forgotten once it
  1323. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1324. and on is notified once (#3226), while one that clears and comes back much
  1325. later is notified again.
  1326. When ``print_state`` changes (a print resumed, started or finished), every
  1327. fault recorded so far is forgotten the first time it is gone, without the
  1328. wait: a runout fixed before resuming must be notified if it happens again a
  1329. few minutes later, while the printer sits paused. Not only the faults gone
  1330. at the change itself, because the update that flips the state can still
  1331. carry the old fault (a ``print_error`` entry stays until a payload brings
  1332. ``hms``).
  1333. """
  1334. now = time.time()
  1335. current = {_hms_notify_key(e) for e in errors}
  1336. seen = _notified_hms_errors.setdefault(printer_id, {})
  1337. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1338. if print_state is not None:
  1339. print_state = print_state.upper()
  1340. if _hms_print_state.get(printer_id, print_state) != print_state:
  1341. forget_when_gone.update(seen)
  1342. _hms_print_state[printer_id] = print_state
  1343. for key, last_seen in list(seen.items()):
  1344. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1345. del seen[key]
  1346. forget_when_gone.discard(key)
  1347. new = current - seen.keys()
  1348. for key in current:
  1349. seen[key] = now
  1350. if not seen:
  1351. _notified_hms_errors.pop(printer_id, None)
  1352. if not forget_when_gone:
  1353. _hms_forget_when_gone.pop(printer_id, None)
  1354. return _hms_errors_to_notify(errors, new)
  1355. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1356. # "Printing", -1 and 255 are "no stage" (#3211).
  1357. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1358. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1359. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1360. Records it as notified. Called only for a printing state with progress above 0.
  1361. Progress before the first layer is not progress through the print (#3211).
  1362. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1363. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1364. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1365. 75% notification together with Print Started, and since 75 was then on
  1366. record, 25 and 50 could never fire. So nothing counts while the printer
  1367. reports a layer count but has not started layer 1.
  1368. Without a layer count -- a print whose first frame carried no
  1369. ``total_layer_num``, until the pushall that asks for it is answered
  1370. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1371. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1372. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1373. reports neither keeps the old behaviour rather than never notifying.
  1374. """
  1375. if (state.layer_num or 0) < 1:
  1376. if (state.total_layers or 0) > 0:
  1377. return None
  1378. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1379. return None
  1380. progress = state.progress or 0
  1381. current_milestone = 0
  1382. if progress >= 75:
  1383. current_milestone = 75
  1384. elif progress >= 50:
  1385. current_milestone = 50
  1386. elif progress >= 25:
  1387. current_milestone = 25
  1388. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1389. _last_progress_milestone[printer_id] = current_milestone
  1390. return current_milestone
  1391. return None
  1392. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1393. """Handle printer status changes - broadcast via WebSocket."""
  1394. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1395. # transitions disconnected → connected — which covers both Bambuddy
  1396. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1397. # `reconcile_stale_active_prints` exactly once for this connection so
  1398. # any archive still in `status="printing"` that can't actually be
  1399. # running anymore (printer IDLE / different subtask / empty subtask)
  1400. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1401. # finished during a disconnect window + a smart-plug power cycle
  1402. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1403. # next boot. Reconciliation runs concurrently — it must not block the
  1404. # WebSocket dedup / broadcast logic below, and the connected edge is
  1405. # marked True BEFORE the await so concurrent status updates inside
  1406. # the same connection don't re-trigger reconciliation.
  1407. #
  1408. # Wait for a real push_status before reconciling (#1679): MQTT
  1409. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1410. # the connection, BEFORE `_request_push_all` round-trips. At that
  1411. # instant the `PrinterState` is still on construction defaults — most
  1412. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1413. # If reconcile spawns here, every in-flight archive falls through to
  1414. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1415. # creates a duplicate archive on the real PRINT COMPLETE and
  1416. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1417. # keeps the #1542 mechanism intact: once the first real push_status
  1418. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1419. # fires again with the flag still False — reconcile then runs against
  1420. # actual evidence.
  1421. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1422. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1423. _printer_reconciled_since_connect[printer_id] = True
  1424. spawn_background_task(
  1425. reconcile_stale_active_prints(printer_id),
  1426. name=f"reconcile-stale-prints-{printer_id}",
  1427. )
  1428. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1429. # Re-arm so the next reconnect triggers reconciliation again.
  1430. _printer_reconciled_since_connect[printer_id] = False
  1431. # Same edge, for the calibration table the AMS card reads its K values from.
  1432. #
  1433. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1434. # tables to ask for. A `state_known` gate alone is not enough: the first
  1435. # real push_status is what makes the state known, and the nozzle fields do
  1436. # not always arrive in it. Latching there would spend this connection's one
  1437. # attempt on a printer that could not yet say what was fitted.
  1438. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1439. if (
  1440. state.connected
  1441. and state_known
  1442. and nozzle_known
  1443. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1444. ):
  1445. _printer_kprofiles_primed_since_connect[printer_id] = True
  1446. spawn_background_task(
  1447. prime_kprofile_table(printer_id),
  1448. name=f"prime-kprofiles-{printer_id}",
  1449. )
  1450. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1451. _printer_kprofiles_primed_since_connect[printer_id] = False
  1452. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1453. # else in the AMS report changing -- a power cycle does it to every slot --
  1454. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1455. # while the printer is idle; needs_check is cheap and throttled per slot.
  1456. # Guarded: nothing here may stop the status broadcast below.
  1457. try:
  1458. if not state.connected:
  1459. kprofile_drift.forget_printer(printer_id)
  1460. elif kprofile_drift.needs_check(printer_id, state):
  1461. spawn_background_task(
  1462. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1463. name=f"reapply-kprofiles-{printer_id}",
  1464. )
  1465. except Exception:
  1466. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1467. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1468. # connected → disconnected. The "back online" channel is already covered
  1469. # by the print-failure notification (firmware reports gcode_state=FAILED
  1470. # on reconnect of an interrupted print), so we don't add a symmetric
  1471. # online event here.
  1472. prev_connected = _printer_last_connected.get(printer_id)
  1473. _printer_last_connected[printer_id] = state.connected
  1474. if prev_connected is True and not state.connected:
  1475. existing = _printer_offline_notify_tasks.get(printer_id)
  1476. if existing is None or existing.done():
  1477. logging.getLogger(__name__).info(
  1478. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1479. printer_id,
  1480. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1481. )
  1482. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1483. _maybe_notify_printer_offline(printer_id),
  1484. name=f"printer-offline-notify-{printer_id}",
  1485. )
  1486. elif state.connected:
  1487. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1488. if pending is not None and not pending.done():
  1489. logging.getLogger(__name__).info(
  1490. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1491. printer_id,
  1492. )
  1493. pending.cancel()
  1494. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1495. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1496. temps = state.temperatures or {}
  1497. nozzle_temp = round(temps.get("nozzle", 0))
  1498. bed_temp = round(temps.get("bed", 0))
  1499. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1500. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1501. # Auto-detect dual-nozzle printers from MQTT temperature data
  1502. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1503. _nozzle_count_updated.add(printer_id)
  1504. # Update nozzle_count in database
  1505. async with async_session() as db:
  1506. from backend.app.models.printer import Printer
  1507. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1508. printer = result.scalar_one_or_none()
  1509. if printer and printer.nozzle_count != 2:
  1510. printer.nozzle_count = 2
  1511. await db.commit()
  1512. logging.getLogger(__name__).info(
  1513. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1514. )
  1515. # Include target temps for heating phase detection
  1516. bed_target = round(temps.get("bed_target", 0))
  1517. nozzle_target = round(temps.get("nozzle_target", 0))
  1518. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1519. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1520. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1521. #
  1522. # dry_countdown_stalled rides along because it is the one drying signal the
  1523. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1524. # dry_time stopped moving, so on the frame that flips it every other member
  1525. # of this key is identical and the push would be deduplicated away. Mid-print
  1526. # a temperature would eventually break the tie, but a parked command on an
  1527. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1528. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1529. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1530. ams_dry_key = (
  1531. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1532. if state.raw_data
  1533. else ()
  1534. )
  1535. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1536. #
  1537. # The filament identity fields are here because Configure Slot writes
  1538. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1539. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1540. # matched, this function returned before broadcasting, and the card kept
  1541. # showing the old filament until the 30s fallback poll or a page reload —
  1542. # even though the configure route asks the printer for a fresh pushall and
  1543. # that push does carry the new values. Reset always worked, because it
  1544. # clears tray_type.
  1545. #
  1546. # These fields only change when someone configures a slot or swaps a spool,
  1547. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1548. ams_tray_key = (
  1549. tuple(
  1550. (
  1551. t.get("id"),
  1552. t.get("tray_type", ""),
  1553. t.get("state"),
  1554. t.get("tray_color", ""),
  1555. t.get("tray_info_idx", ""),
  1556. t.get("tray_sub_brands", ""),
  1557. t.get("cali_idx"),
  1558. )
  1559. for a in (state.raw_data.get("ams") or [])
  1560. for t in a.get("tray", [])
  1561. )
  1562. if state.raw_data
  1563. else ()
  1564. )
  1565. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1566. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1567. # in the AMS change-hash (tray fields only, and widening that would fire
  1568. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1569. # screen changed no key at all and the card's inlet badges sat stale until a
  1570. # reload. Like the filament-backup flag, these only move when someone
  1571. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1572. fts_key = (
  1573. state.fila_switch.installed if state.fila_switch else False,
  1574. tuple(sorted(state.ams_switch_inlet.items())),
  1575. # Which hotend holds which slot. Unlike the two above this does move
  1576. # mid-print, on every filament change — but only between discrete slots,
  1577. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1578. # it live: it decides which hotend the Load dialog may offer and whether
  1579. # Unload has anything to act on.
  1580. tuple(
  1581. sorted(
  1582. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1583. # Sort on the extruder id alone: the other members are nullable
  1584. # and comparing None with an int raises.
  1585. key=lambda entry: entry[0],
  1586. )
  1587. ),
  1588. )
  1589. status_key = (
  1590. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1591. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1592. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1593. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1594. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1595. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1596. )
  1597. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1598. if not is_active_print:
  1599. _unauthorized_print_kill_sent.discard(printer_id)
  1600. elif printer_id in _unauthorized_print_kill_sent:
  1601. # stop_print() was already sent for this print; avoid all further
  1602. # ownership and settings work until the printer leaves an active state.
  1603. pass
  1604. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1605. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1606. _unauthorized_print_kill_sent.discard(printer_id)
  1607. else:
  1608. kill_switch_enabled = False
  1609. authorization: bool | None = None
  1610. status_logger = logging.getLogger(__name__)
  1611. try:
  1612. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1613. if kill_switch_enabled:
  1614. async with async_session() as db:
  1615. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1616. except Exception as e:
  1617. # Fail safe: a database/reconciliation error must never turn into an
  1618. # irreversible stop of a print whose ownership is still unknown.
  1619. authorization = None
  1620. status_logger.warning(
  1621. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1622. )
  1623. if not kill_switch_enabled or authorization is True:
  1624. _unauthorized_print_kill_sent.discard(printer_id)
  1625. elif authorization is None:
  1626. _unauthorized_print_kill_sent.discard(printer_id)
  1627. status_logger.debug(
  1628. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1629. printer_id,
  1630. )
  1631. else:
  1632. try:
  1633. stopped = printer_manager.stop_print(printer_id)
  1634. if stopped:
  1635. _unauthorized_print_kill_sent.add(printer_id)
  1636. printer_info = printer_manager.get_printer(printer_id)
  1637. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1638. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1639. notification_data = {
  1640. "status": "stopped",
  1641. "filename": state.gcode_file or state.current_print or "",
  1642. "subtask_name": state.subtask_name or "",
  1643. "progress": state.progress,
  1644. "reason": "unauthorized_print",
  1645. }
  1646. status_logger.warning(
  1647. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1648. printer_id,
  1649. state.state,
  1650. )
  1651. try:
  1652. await ws_manager.broadcast(
  1653. {
  1654. "type": "kill_switch_triggered",
  1655. "printer_id": printer_id,
  1656. "printer_name": printer_name,
  1657. "filename": filename,
  1658. "reason": "unauthorized_print",
  1659. }
  1660. )
  1661. except Exception as e:
  1662. status_logger.warning(
  1663. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1664. )
  1665. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1666. if previous_task is not None and not previous_task.done():
  1667. previous_task.cancel()
  1668. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1669. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1670. name=f"kill-switch-notification-{printer_id}",
  1671. )
  1672. else:
  1673. status_logger.warning(
  1674. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1675. printer_id,
  1676. state.state,
  1677. )
  1678. except Exception as e:
  1679. status_logger.warning(
  1680. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1681. )
  1682. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1683. try:
  1684. printer_info = printer_manager.get_printer(printer_id)
  1685. if printer_info:
  1686. await mqtt_relay.on_printer_status(
  1687. printer_id,
  1688. state,
  1689. printer_info.name,
  1690. printer_info.serial_number,
  1691. printer_manager.is_awaiting_plate_clear(printer_id),
  1692. )
  1693. except Exception:
  1694. pass # Don't fail status callback if MQTT fails
  1695. if _last_status_broadcast.get(printer_id) == status_key:
  1696. return # No change, skip WebSocket broadcast
  1697. _last_status_broadcast[printer_id] = status_key
  1698. # Check for progress milestone notifications (25%, 50%, 75%)
  1699. progress = state.progress or 0
  1700. is_printing = state.state in ("RUNNING", "PRINTING")
  1701. if is_printing and progress > 0:
  1702. current_milestone = _progress_milestone_to_notify(printer_id, state)
  1703. if current_milestone is not None:
  1704. try:
  1705. from backend.app.models.printer import Printer
  1706. # Read the printer in a short session and release the connection
  1707. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1708. # pinned a pooled connection per milestone, per printer (issue #2572).
  1709. async with async_session() as db:
  1710. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1711. printer = result.scalar_one_or_none()
  1712. printer_name = printer.name if printer else f"Printer {printer_id}"
  1713. filename = state.subtask_name or state.gcode_file or "Unknown"
  1714. # remaining_time is in minutes, convert to seconds for notification
  1715. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1716. # Capture camera snapshot for notification image attachment (no DB held).
  1717. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1718. # Notification send needs a session (provider/template lookups).
  1719. async with async_session() as db:
  1720. await notification_service.on_print_progress(
  1721. printer_id,
  1722. printer_name,
  1723. filename,
  1724. current_milestone,
  1725. db,
  1726. remaining_time_seconds,
  1727. image_data=image_data,
  1728. )
  1729. except Exception as e:
  1730. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1731. elif progress < 5:
  1732. # Reset milestone tracking when print restarts or new print begins
  1733. _last_progress_milestone[printer_id] = 0
  1734. _first_layer_notified[printer_id] = False
  1735. # HMS error codes that should not trigger notifications even though they
  1736. # have known descriptions (e.g. user-initiated actions, not real errors).
  1737. _HMS_NOTIFICATION_SUPPRESS = {
  1738. "0500_400E", # Printing was cancelled (user action, not an error)
  1739. }
  1740. # Check for new HMS errors and send notifications
  1741. current_hms_errors = getattr(state, "hms_errors", []) or []
  1742. if current_hms_errors:
  1743. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  1744. if new_errors:
  1745. try:
  1746. from backend.app.models.printer import Printer
  1747. # Read the printer in a short session and release the connection
  1748. # BEFORE the ~15s camera snapshot below (issue #2572).
  1749. async with async_session() as db:
  1750. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1751. printer = result.scalar_one_or_none()
  1752. printer_name = printer.name if printer else f"Printer {printer_id}"
  1753. # Format error details for notification
  1754. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1755. module_names = {
  1756. 0x03: "Print/Task",
  1757. 0x05: "Nozzle/Extruder",
  1758. 0x07: "AMS/Filament",
  1759. 0x0C: "Motion Controller",
  1760. 0x12: "Chamber",
  1761. }
  1762. # Capture camera snapshot once for all error notifications (no DB held).
  1763. error_image_data = await _capture_snapshot_for_notification(
  1764. printer_id, printer, logging.getLogger(__name__)
  1765. )
  1766. # Notification sends need a session (provider/template lookups).
  1767. async with async_session() as db:
  1768. sent_count = 0
  1769. for error in new_errors:
  1770. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1771. # Build short code like "0700_8010"
  1772. # Mask to 16 bits to handle printers that send larger values
  1773. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1774. error_code_masked = error_code_int & 0xFFFF
  1775. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1776. # Only notify for errors Bambu publishes text for — printers
  1777. # send undocumented codes that aren't real errors, and Bambu
  1778. # lists some with empty text. Resolved at parse time (#2926);
  1779. # short_code is still needed for the suppression set below.
  1780. description = error.description
  1781. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1782. continue
  1783. error_type = f"{module_name} Error"
  1784. error_detail = description
  1785. await notification_service.on_printer_error(
  1786. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1787. )
  1788. sent_count += 1
  1789. if sent_count:
  1790. logging.getLogger(__name__).info(
  1791. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1792. )
  1793. # Also publish to MQTT relay (no DB): every new fault that
  1794. # counts, with or without text, the same set the UI counts.
  1795. printer_info = printer_manager.get_printer(printer_id)
  1796. if printer_info:
  1797. errors_data = [
  1798. {
  1799. "code": e.code,
  1800. "attr": e.attr,
  1801. "module": e.module,
  1802. "severity": e.severity,
  1803. }
  1804. for e in new_errors
  1805. ]
  1806. await mqtt_relay.on_printer_error(
  1807. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1808. )
  1809. except Exception as e:
  1810. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1811. else:
  1812. # No HMS errors: nothing to send, but faults gone long enough (or gone
  1813. # across a print state change) are forgotten. Some codes, e.g. chamber
  1814. # temperature regulation during PETG prints, toggle every few seconds.
  1815. _take_new_hms_faults(printer_id, [], state.state)
  1816. await ws_manager.send_printer_status(
  1817. printer_id,
  1818. printer_state_to_dict(
  1819. state,
  1820. printer_id,
  1821. printer_manager.get_model(printer_id),
  1822. printer_manager.get_drying_targets(printer_id),
  1823. ),
  1824. )
  1825. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1826. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1827. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1828. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  1829. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  1830. K-profiles are per-nozzle and the printer's calibration table is numbered
  1831. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  1832. switch's other inlet therefore silently invalidates every configured slot in
  1833. it: the index stays put and now resolves against the other nozzle's table.
  1834. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  1835. and 0.020 on the right kept the left profile after the move, and a manual
  1836. RFID re-read only re-asserted the same wrong one.
  1837. Configuring a slot is a deliberate preparation step, so this re-selects
  1838. rather than re-configures: only the calibration binding moves, and only for
  1839. slots whose spool already has a stored profile for the new nozzle. A slot
  1840. Bambuddy knows nothing about is left exactly as the operator left it.
  1841. """
  1842. logger = logging.getLogger(__name__)
  1843. target_extruder = extruder_for_inlet(inlet)
  1844. if target_extruder is None:
  1845. return
  1846. client = printer_manager.get_client(printer_id)
  1847. state = printer_manager.get_status(printer_id)
  1848. if not client or not state or not state.raw_data:
  1849. return
  1850. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  1851. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  1852. # the nozzle width, which changes both the K profile to select and the
  1853. # preset the slot should carry.
  1854. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  1855. ams_raw = state.raw_data.get("ams")
  1856. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  1857. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  1858. if not unit:
  1859. return
  1860. try:
  1861. async with async_session() as db:
  1862. for tray in unit.get("tray", []):
  1863. tray_id = int(tray.get("id", -1))
  1864. if tray_id < 0 or not tray.get("tray_type"):
  1865. continue
  1866. current_idx = tray.get("cali_idx")
  1867. profile = await find_slot_kprofile_for_extruder(
  1868. db,
  1869. printer_id,
  1870. ams_id,
  1871. tray_id,
  1872. target_extruder,
  1873. nozzle_diameter,
  1874. printer_manager.get_model(printer_id),
  1875. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  1876. )
  1877. if profile is None or profile.cali_idx is None:
  1878. continue
  1879. if current_idx == profile.cali_idx:
  1880. continue # Already on the right one.
  1881. logger.info(
  1882. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  1883. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  1884. printer_id,
  1885. ams_id,
  1886. tray_id,
  1887. inlet,
  1888. target_extruder,
  1889. profile.name,
  1890. current_idx,
  1891. profile.cali_idx,
  1892. profile.k_value,
  1893. )
  1894. client.extrusion_cali_sel(
  1895. ams_id=ams_id,
  1896. tray_id=tray_id,
  1897. cali_idx=profile.cali_idx,
  1898. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  1899. nozzle_diameter=nozzle_diameter,
  1900. )
  1901. except Exception as e:
  1902. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  1903. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  1904. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  1905. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  1906. from the delayed re-check -- which is why it takes the AMS data and print
  1907. state as arguments instead of reading them from the push (#3186).
  1908. """
  1909. logger = logging.getLogger(__name__)
  1910. from backend.app.utils.color_utils import colors_similar as _colors_similar
  1911. # Auto-unlink spool assignments with stale fingerprints. Under the
  1912. # per-printer assignment lock since #3186: the held-removal re-check runs
  1913. # this outside any MQTT push, so it can now overlap one.
  1914. try:
  1915. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  1916. from sqlalchemy.orm import selectinload
  1917. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  1918. from backend.app.models.spool import Spool as _Spool
  1919. from backend.app.models.spool_assignment import SpoolAssignment as SA
  1920. from backend.app.services.ams_slot_presence import spool_present
  1921. from backend.app.services.inventory_mode import spoolman_owns_assignments
  1922. # Built-in assignments only. Since #2812 they survive a switch to
  1923. # Spoolman mode rather than being deleted by it, and this pass ends
  1924. # in ``db.delete`` — left ungated it would unlink them one slot at a
  1925. # time as the AMS contents changed under the other mode, undoing the
  1926. # preservation more slowly but just as completely.
  1927. assignments = []
  1928. if not await spoolman_owns_assignments(db):
  1929. result = await db.execute(
  1930. select(SA)
  1931. .where(SA.printer_id == printer_id)
  1932. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  1933. )
  1934. assignments = result.scalars().all()
  1935. # ``printing_now`` (top of this function) keeps a runout from
  1936. # unlinking the spool that fed the print — the next idle-time pass
  1937. # unlinks it if the user really did take it out.
  1938. stale = []
  1939. # Removals this pass is holding rather than unlinking (#3186).
  1940. held: set[tuple] = set()
  1941. for assignment in assignments:
  1942. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  1943. if assignment.ams_id == 255:
  1944. ps = printer_manager.get_status(printer_id)
  1945. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  1946. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  1947. current_tray = None
  1948. for vt in vt_tray_raw:
  1949. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  1950. current_tray = vt
  1951. break
  1952. if not current_tray:
  1953. # vt_tray data may not have arrived yet — keep assignment
  1954. continue
  1955. else:
  1956. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  1957. if not current_tray:
  1958. if printing_now:
  1959. logger.info(
  1960. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  1961. assignment.spool_id,
  1962. assignment.ams_id,
  1963. assignment.tray_id,
  1964. )
  1965. continue
  1966. # A whole AMS unit can drop out of one push and come back in
  1967. # the next; only a slot that stays gone is a removal (#3186).
  1968. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  1969. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  1970. held.add(hold_key)
  1971. logger.info(
  1972. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  1973. "unlinking if it is still gone in %ds",
  1974. assignment.spool_id,
  1975. assignment.ams_id,
  1976. assignment.tray_id,
  1977. int(slot_unlink_grace.GRACE_SECONDS),
  1978. )
  1979. continue
  1980. logger.info(
  1981. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  1982. assignment.spool_id,
  1983. assignment.ams_id,
  1984. assignment.tray_id,
  1985. )
  1986. stale.append(assignment) # Slot empty
  1987. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  1988. # A Bambu Lab spool is in this slot — check if it's the same spool
  1989. # that's currently assigned. If yes, keep the assignment (avoids
  1990. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  1991. # the printer's filament preset on every startup).
  1992. tray_uuid = current_tray.get("tray_uuid", "")
  1993. tag_uid = current_tray.get("tag_uid", "")
  1994. spool = assignment.spool
  1995. spool_matches = False
  1996. if spool:
  1997. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  1998. spool.tag_uid
  1999. and tag_uid
  2000. and tag_uid != "0000000000000000"
  2001. and spool.tag_uid.upper() == tag_uid.upper()
  2002. ):
  2003. spool_matches = True
  2004. if spool_matches:
  2005. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2006. cur_color = current_tray.get("tray_color", "")
  2007. cur_type = current_tray.get("tray_type", "")
  2008. fp_color = assignment.fingerprint_color or ""
  2009. fp_type = assignment.fingerprint_type or ""
  2010. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2011. assignment.fingerprint_color = cur_color
  2012. assignment.fingerprint_type = cur_type
  2013. logger.debug(
  2014. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2015. assignment.spool_id,
  2016. assignment.ams_id,
  2017. assignment.tray_id,
  2018. )
  2019. continue
  2020. # Different BL spool or unrecognized — unlink so auto-assign can match
  2021. logger.info(
  2022. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2023. assignment.spool_id,
  2024. assignment.ams_id,
  2025. assignment.tray_id,
  2026. tray_uuid,
  2027. )
  2028. stale.append(assignment)
  2029. else:
  2030. cur_color = current_tray.get("tray_color", "")
  2031. cur_type = current_tray.get("tray_type", "")
  2032. cur_state = current_tray.get("state")
  2033. fp_color = assignment.fingerprint_color or ""
  2034. fp_type = assignment.fingerprint_type or ""
  2035. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2036. # the slot was empty when the user pre-assigned via SpoolBuddy
  2037. # (the firmware drops ams_filament_setting on empty slots, so
  2038. # MQTT was deferred). The moment any filament gets inserted
  2039. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2040. # reconfigured spool — fire the deferred configuration.
  2041. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2042. # extruder" code) OR, on firmwares that don't use the state
  2043. # enum meaningfully, a non-empty tray_type when state is
  2044. # NOT one of the firmware's explicit empty signals (9, 10).
  2045. # state-only was wrong for firmwares that never set 11 — A1
  2046. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2047. # always report state=3 — so the replay never fired for them
  2048. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2049. # explicit "empty" signals authoritative over any stale
  2050. # tray_type that might survive the relay's auto-clearing.
  2051. #
  2052. # tray_exist_bits comes first because that guard cannot tell
  2053. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2054. # writes state=9 when the bit is 0 and leaves it there when the
  2055. # bit returns. A non-RFID spool inserted into a pre-assigned
  2056. # slot brings no tray_type with it, so the stale 9 made this
  2057. # expression false forever and the deferred config never fired
  2058. # — the deadlock #1322 removed from the assign path, still in
  2059. # place here (#3084, #3100).
  2060. loaded = spool_present(current_tray) is True or (
  2061. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2062. )
  2063. if not fp_type.strip() and loaded and assignment.spool:
  2064. try:
  2065. from backend.app.api.routes.inventory import (
  2066. apply_spool_to_slot_via_mqtt,
  2067. )
  2068. await apply_spool_to_slot_via_mqtt(
  2069. db=db,
  2070. current_user=None,
  2071. spool=assignment.spool,
  2072. printer_id=printer_id,
  2073. ams_id=assignment.ams_id,
  2074. tray_id=assignment.tray_id,
  2075. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2076. current_tray_type=cur_type,
  2077. )
  2078. logger.info(
  2079. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2080. assignment.spool_id,
  2081. printer_id,
  2082. assignment.ams_id,
  2083. assignment.tray_id,
  2084. )
  2085. except Exception:
  2086. logger.exception(
  2087. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2088. assignment.spool_id,
  2089. printer_id,
  2090. assignment.ams_id,
  2091. assignment.tray_id,
  2092. )
  2093. assignment.fingerprint_color = cur_color
  2094. assignment.fingerprint_type = cur_type
  2095. continue
  2096. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2097. # Blank tray data mid-print is a runout, not a swap: the
  2098. # firmware clears colour and type when it unloads a spool
  2099. # it just emptied. Unlinking here would erase the record
  2100. # of which spool fed the print so far.
  2101. if printing_now and not cur_color.strip() and not cur_type.strip():
  2102. logger.info(
  2103. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2104. "(runout?)",
  2105. assignment.spool_id,
  2106. assignment.ams_id,
  2107. assignment.tray_id,
  2108. )
  2109. continue
  2110. # Same reasoning off the print, on firmware's own say-so:
  2111. # a blank tray report from a slot whose tray_exist_bits
  2112. # bit is set describes a spool the AMS cannot identify —
  2113. # a non-RFID one, or one whose slot was reset — not a
  2114. # spool that was taken out. Deleting the assignment there
  2115. # threw away the identity the user had supplied, which is
  2116. # the only place it existed (#3100). A slot the bit calls
  2117. # empty, or one that carries no bit at all, still unlinks.
  2118. #
  2119. # Unless the slot was reported empty first: a removal
  2120. # already held means a spool came out and another went
  2121. # in, so the blank report keeps the hold running below
  2122. # rather than cancelling it (#3186).
  2123. if (
  2124. spool_present(current_tray) is True
  2125. and not cur_color.strip()
  2126. and not cur_type.strip()
  2127. and not slot_unlink_grace.is_held(
  2128. printer_id,
  2129. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2130. )
  2131. ):
  2132. logger.info(
  2133. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2134. "tray reports no filament data yet",
  2135. assignment.spool_id,
  2136. assignment.ams_id,
  2137. assignment.tray_id,
  2138. )
  2139. continue
  2140. # A blank report the presence bit does not vouch for is
  2141. # still only one push. An idle X1C cleared a whole AMS
  2142. # unit's bits, colour and type for a moment and lost
  2143. # four saved assignments that way (#3186); unlink only
  2144. # if the slot is still blank after the grace period.
  2145. if not cur_color.strip() and not cur_type.strip():
  2146. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2147. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2148. held.add(hold_key)
  2149. logger.info(
  2150. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2151. "unlinking if it is still blank in %ds",
  2152. assignment.spool_id,
  2153. assignment.ams_id,
  2154. assignment.tray_id,
  2155. int(slot_unlink_grace.GRACE_SECONDS),
  2156. )
  2157. continue
  2158. # Fingerprint mismatch — but check if tray now matches the
  2159. # assigned spool (e.g. auto-configure changed the tray).
  2160. # Both sides are reduced to the type the slot can carry
  2161. # before comparing: the assign path writes that rather
  2162. # than the spool's raw material (#2902), so a spool whose
  2163. # material is a product line — "PLA+", "HTPLA" — reports
  2164. # back as "PLA" and would otherwise fail this check and
  2165. # be auto-unlinked from the slot it was just assigned to.
  2166. # Reducing the printer's side too keeps slots configured
  2167. # by an older Bambuddy, still reporting "PLA+", matching.
  2168. spool = assignment.spool
  2169. if spool:
  2170. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2171. # Two ways the assign path can have arrived at the
  2172. # slot's type, so both count as "we wrote this".
  2173. # The material column is one; the spool's preset is
  2174. # the other, and it outranks the material when the
  2175. # spool has one -- a spool whose material says PLA
  2176. # and whose preset is "Bambu PLA Aero" puts
  2177. # PLA-AERO in the slot (#2902). Read from the stored
  2178. # preset name rather than resolving the preset,
  2179. # because this runs on every AMS push and a cloud
  2180. # lookup here would be both slow and unavailable on
  2181. # the unauthenticated replay path.
  2182. spool_types = {printer_filament_type(spool.material).upper()}
  2183. if spool.slicer_filament_name:
  2184. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2185. # An imported local preset stores its type outright,
  2186. # which is what the assign path used -- and the name
  2187. # above may be unset. One keyed read, and only on a
  2188. # mismatch, which is rare.
  2189. #
  2190. # slicer_filament is free text up to fifty characters,
  2191. # so the digits have to be checked against the range
  2192. # of the integer primary key they are about to be
  2193. # compared with. Postgres raises on an out-of-range
  2194. # integer rather than simply not matching, and that
  2195. # would poison this session and abandon the rest of
  2196. # the cleanup pass.
  2197. lp_ref = (spool.slicer_filament or "").strip()
  2198. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2199. from backend.app.models.local_preset import LocalPreset as _LP
  2200. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2201. if lp_type:
  2202. spool_types.add(printer_filament_type(lp_type).upper())
  2203. if (
  2204. _colors_similar(cur_color, spool_color)
  2205. and printer_filament_type(cur_type).upper() in spool_types
  2206. ):
  2207. logger.info(
  2208. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2209. assignment.spool_id,
  2210. assignment.ams_id,
  2211. assignment.tray_id,
  2212. )
  2213. assignment.fingerprint_color = cur_color
  2214. assignment.fingerprint_type = cur_type
  2215. continue
  2216. logger.info(
  2217. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2218. assignment.spool_id,
  2219. assignment.ams_id,
  2220. assignment.tray_id,
  2221. cur_color,
  2222. cur_type,
  2223. fp_color,
  2224. fp_type,
  2225. spool.rgba if spool else "?",
  2226. spool.material if spool else "?",
  2227. )
  2228. stale.append(assignment) # Spool changed
  2229. slot_unlink_grace.settle(printer_id, "inventory", held)
  2230. # Snapshot slots before delete — ORM attribute access after the
  2231. # commit would refresh against a deleted row.
  2232. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2233. for a in stale:
  2234. await db.delete(a)
  2235. if stale:
  2236. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2237. # Commit any changes (stale deletions and/or fingerprint updates)
  2238. await db.commit()
  2239. # Tell open browsers the assignment is gone (#2575). Only the manual
  2240. # REST assign/unassign endpoints broadcast this event; without it the
  2241. # frontend's spool-assignments cache keeps rendering the unlinked
  2242. # spool on the slot until an unrelated refetch — which reads exactly
  2243. # like "the fix didn't work" (reporter verified: a browser refresh
  2244. # after the swap showed the correct state all along).
  2245. for ams_id, tray_id in unlinked_slots:
  2246. await ws_manager.broadcast(
  2247. {
  2248. "type": "spool_assignment_changed",
  2249. "printer_id": printer_id,
  2250. "ams_id": ams_id,
  2251. "tray_id": tray_id,
  2252. }
  2253. )
  2254. except Exception as e:
  2255. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2256. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2257. """Delete Spoolman slot rows whose held removal has run its grace period.
  2258. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2259. talks to Spoolman for every tray; this only needs the local rows, so it
  2260. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2261. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2262. not in a slot the presence bit calls occupied -- and nothing else.
  2263. """
  2264. logger = logging.getLogger(__name__)
  2265. try:
  2266. async with async_session() as db:
  2267. from backend.app.api.routes.settings import get_setting
  2268. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2269. from backend.app.services.ams_slot_presence import spool_present
  2270. enabled = await get_setting(db, "spoolman_enabled")
  2271. if not enabled or enabled.lower() != "true":
  2272. return
  2273. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2274. if sync_mode and sync_mode != "auto":
  2275. return
  2276. trays: dict[tuple[int, int], dict] = {}
  2277. for ams_unit in ams_data or []:
  2278. if not isinstance(ams_unit, dict):
  2279. continue
  2280. for tray in ams_unit.get("tray", []):
  2281. if isinstance(tray, dict):
  2282. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2283. rows = (
  2284. (
  2285. await db.execute(
  2286. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2287. )
  2288. )
  2289. .scalars()
  2290. .all()
  2291. )
  2292. held: set[tuple] = set()
  2293. expired: list[tuple[int, int]] = []
  2294. for row in rows:
  2295. tray = trays.get((row.ams_id, row.tray_id))
  2296. if tray is None or printing_now:
  2297. continue
  2298. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2299. continue
  2300. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2301. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2302. continue
  2303. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2304. expired.append((row.ams_id, row.tray_id))
  2305. else:
  2306. held.add(hold_key)
  2307. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2308. if not expired:
  2309. return
  2310. # A statement rather than ORM deletes, like the sync pass: the two
  2311. # can overlap, and a row the other already removed must not fail
  2312. # this commit.
  2313. for ams_id, tray_id in expired:
  2314. await db.execute(
  2315. delete(SpoolmanSlotAssignment).where(
  2316. SpoolmanSlotAssignment.printer_id == printer_id,
  2317. SpoolmanSlotAssignment.ams_id == ams_id,
  2318. SpoolmanSlotAssignment.tray_id == tray_id,
  2319. )
  2320. )
  2321. await db.commit()
  2322. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2323. for ams_id, tray_id in expired:
  2324. await ws_manager.broadcast(
  2325. {
  2326. "type": "spool_assignment_changed",
  2327. "printer_id": printer_id,
  2328. "ams_id": ams_id,
  2329. "tray_id": tray_id,
  2330. }
  2331. )
  2332. except Exception as e:
  2333. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2334. async def _recheck_held_unlinks(printer_id: int) -> None:
  2335. """Re-run just the slot cleanup against the printer's current AMS state.
  2336. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2337. passes otherwise run only when the AMS hash changes, and a slot that went
  2338. empty and stayed empty may never change it again.
  2339. """
  2340. status = printer_manager.get_status(printer_id)
  2341. # A disconnected printer's state is its last report, not a new one: acting
  2342. # on it would "confirm" a removal nobody has seen for the whole grace
  2343. # period. Leave the holds; the first push after reconnecting decides.
  2344. if status is None or not status.connected:
  2345. return
  2346. ams_raw = status.raw_data.get("ams")
  2347. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2348. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2349. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2350. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2351. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2352. async def on_ams_change(printer_id: int, ams_data: list):
  2353. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2354. logger = logging.getLogger(__name__)
  2355. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  2356. # on_print_complete may pop _active_sessions during our awaits (#880).
  2357. from backend.app.services.usage_tracker import _active_sessions
  2358. _print_active = printer_id in _active_sessions
  2359. # A slot that reports empty while a print is running is a filament runout,
  2360. # not a spool swap: the spool is still physically in the AMS, just
  2361. # consumed. Dropping either inventory backend's slot link there loses the
  2362. # only record of which spool fed the print, so the completion path can't
  2363. # charge the runout segment to anything. Both cleanup passes below consult
  2364. # this; computed once, up front, so neither depends on the other having run.
  2365. _unlink_state = printer_manager.get_status(printer_id)
  2366. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2367. # MQTT relay - publish AMS change
  2368. try:
  2369. printer_info = printer_manager.get_printer(printer_id)
  2370. if printer_info:
  2371. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2372. except Exception:
  2373. pass # Don't fail AMS callback if MQTT fails
  2374. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2375. # This ensures frontend gets immediate updates when AMS slots are configured
  2376. try:
  2377. state = printer_manager.get_status(printer_id)
  2378. if state:
  2379. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2380. await ws_manager.send_printer_status(
  2381. printer_id,
  2382. printer_state_to_dict(
  2383. state,
  2384. printer_id,
  2385. printer_manager.get_model(printer_id),
  2386. printer_manager.get_drying_targets(printer_id),
  2387. ),
  2388. )
  2389. except Exception as e:
  2390. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2391. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2392. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2393. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  2394. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2395. # "no existing assignment" for the same (printer, ams, tray) and race to
  2396. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2397. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2398. # bug stayed latent there. See _ams_assignment_locks comment for details.
  2399. try:
  2400. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2401. from sqlalchemy.orm import selectinload
  2402. from backend.app.api.routes.settings import get_setting
  2403. from backend.app.models.spool import Spool
  2404. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2405. from backend.app.services.spool_tag_matcher import (
  2406. auto_assign_spool,
  2407. create_spool_from_tray,
  2408. find_matching_untagged_spool,
  2409. get_spool_by_tag,
  2410. is_bambu_tag,
  2411. is_valid_tag,
  2412. link_tag_to_inventory_spool,
  2413. )
  2414. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2415. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2416. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2417. if not _spoolman_on or _spoolman_on.lower() != "true":
  2418. for ams_unit in ams_data:
  2419. if not isinstance(ams_unit, dict):
  2420. continue
  2421. ams_id = int(ams_unit.get("id", 0))
  2422. for tray in ams_unit.get("tray", []):
  2423. if not isinstance(tray, dict):
  2424. continue
  2425. tray_id = int(tray.get("id", 0))
  2426. tag_uid = tray.get("tag_uid", "")
  2427. tray_uuid = tray.get("tray_uuid", "")
  2428. tray_info_idx = tray.get("tray_info_idx", "")
  2429. if not tray.get("tray_type"):
  2430. # Slot reported empty — drop any cached unknown-tag
  2431. # broadcast so reinserting the same spool re-prompts.
  2432. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2433. continue # Empty slot
  2434. # Check if assignment already exists for this slot
  2435. existing = await db.execute(
  2436. select(SA)
  2437. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2438. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2439. )
  2440. existing_assignment = existing.scalar_one_or_none()
  2441. if existing_assignment:
  2442. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2443. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2444. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2445. # Skip during active prints: the usage tracker handles deduction
  2446. # precisely via 3MF data on print completion. Without this guard the
  2447. # AMS remain% SET and the usage tracker ADD both fire from the same
  2448. # MQTT message, doubling the deduction (#880).
  2449. if _print_active:
  2450. continue
  2451. remain_raw = tray.get("remain")
  2452. if (
  2453. remain_raw is not None
  2454. and existing_assignment.spool
  2455. and not existing_assignment.spool.weight_locked
  2456. ):
  2457. try:
  2458. remain_val = int(remain_raw)
  2459. except (TypeError, ValueError):
  2460. remain_val = -1
  2461. if 1 <= remain_val <= 100:
  2462. lw = existing_assignment.spool.label_weight or 1000
  2463. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2464. current_used = existing_assignment.spool.weight_used or 0
  2465. if new_used > current_used + 1:
  2466. logger.info(
  2467. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2468. existing_assignment.spool_id,
  2469. current_used,
  2470. new_used,
  2471. remain_val,
  2472. )
  2473. existing_assignment.spool.weight_used = new_used
  2474. await db.commit()
  2475. # Re-apply stored K-profile when the live tray's
  2476. # cali_idx drifted from the spool's stored profile.
  2477. # This catches "reset slot → re-read" and any other
  2478. # path where the firmware loses the user's K-profile
  2479. # selection while the SpoolAssignment row persists.
  2480. # Per the maintainer's rule: any time a spool tag is
  2481. # identified and matches inventory, the slot must be
  2482. # configured with the spool's stored settings. Without
  2483. # this block the existing-assignment branch only ran
  2484. # weight-sync and let the firmware-default cali_idx win.
  2485. try:
  2486. spool = existing_assignment.spool
  2487. if (
  2488. spool is not None
  2489. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  2490. and spool.k_profiles
  2491. ):
  2492. state = printer_manager.get_status(printer_id)
  2493. slot_nozzle = resolve_slot_nozzle(
  2494. state, ams_id, tray_id, printer_manager.get_model(printer_id)
  2495. )
  2496. nozzle_diameter = slot_nozzle.diameter
  2497. slot_extruder = slot_nozzle.extruder
  2498. # Prefer exact extruder match, fall back to
  2499. # extruder-agnostic kp for the same printer +
  2500. # nozzle. Avoids hard-skipping when the AMS is
  2501. # mapped differently than at calibration time.
  2502. matching_kp = None
  2503. fallback_kp = None
  2504. for kp in spool.k_profiles:
  2505. if (
  2506. kp.printer_id != printer_id
  2507. or kp.nozzle_diameter != nozzle_diameter
  2508. or kp.cali_idx is None
  2509. or not slot_nozzle.flow_matches(kp.nozzle_type)
  2510. ):
  2511. continue
  2512. if (
  2513. slot_extruder is not None
  2514. and kp.extruder is not None
  2515. and kp.extruder == slot_extruder
  2516. ):
  2517. matching_kp = kp
  2518. break
  2519. if fallback_kp is None:
  2520. fallback_kp = kp
  2521. chosen_kp = matching_kp or fallback_kp
  2522. if chosen_kp is not None:
  2523. live_cali_idx = tray.get("cali_idx")
  2524. # Only fire MQTT when the printer's live
  2525. # cali_idx differs from the stored value.
  2526. # Avoids spamming the broker on every
  2527. # MQTT push during steady-state operation.
  2528. if live_cali_idx != chosen_kp.cali_idx:
  2529. client = printer_manager.get_client(printer_id)
  2530. if client:
  2531. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  2532. client.extrusion_cali_sel(
  2533. ams_id=ams_id,
  2534. tray_id=tray_id,
  2535. cali_idx=chosen_kp.cali_idx,
  2536. filament_id=cali_filament_id,
  2537. nozzle_diameter=nozzle_diameter,
  2538. )
  2539. logger.info(
  2540. "Re-applied K-profile cali_idx=%d for spool %d "
  2541. "on printer %d AMS%d-T%d (live=%s drift detected)",
  2542. chosen_kp.cali_idx,
  2543. spool.id,
  2544. printer_id,
  2545. ams_id,
  2546. tray_id,
  2547. live_cali_idx,
  2548. )
  2549. except Exception:
  2550. logger.exception(
  2551. "K-profile re-apply failed for printer %d AMS%d-T%d",
  2552. printer_id,
  2553. ams_id,
  2554. tray_id,
  2555. )
  2556. continue
  2557. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2558. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2559. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2560. if not spool:
  2561. # Try matching an untagged inventory spool (same material/color)
  2562. spool = await find_matching_untagged_spool(db, tray)
  2563. if spool:
  2564. await link_tag_to_inventory_spool(db, spool, tray)
  2565. elif _auto_add_unknown:
  2566. spool = await create_spool_from_tray(db, tray)
  2567. else:
  2568. # Auto-add disabled: surface the slot so the
  2569. # user can add it manually via the UI.
  2570. await _broadcast_unknown_tag(
  2571. printer_id=printer_id,
  2572. ams_id=ams_id,
  2573. tray_id=tray_id,
  2574. tag_uid=tag_uid,
  2575. tray_uuid=tray_uuid,
  2576. tray_type=tray.get("tray_type"),
  2577. tray_color=tray.get("tray_color"),
  2578. tray_sub_brands=tray.get("tray_sub_brands"),
  2579. tray_count=len(ams_unit.get("tray", [])),
  2580. )
  2581. continue
  2582. # Slot matched (existing tag, untagged inventory
  2583. # match, or freshly auto-created spool) — drop any
  2584. # stale dedup so a future tag swap re-prompts.
  2585. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2586. await auto_assign_spool(
  2587. printer_id,
  2588. ams_id,
  2589. tray_id,
  2590. spool,
  2591. printer_manager,
  2592. db,
  2593. tray_info_idx=tray_info_idx,
  2594. )
  2595. await db.commit()
  2596. await ws_manager.broadcast(
  2597. {
  2598. "type": "spool_auto_assigned",
  2599. "printer_id": printer_id,
  2600. "ams_id": ams_id,
  2601. "tray_id": tray_id,
  2602. "spool_id": spool.id,
  2603. }
  2604. )
  2605. logger.info(
  2606. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2607. spool.id,
  2608. printer_id,
  2609. ams_id,
  2610. tray_id,
  2611. )
  2612. elif is_valid_tag(tag_uid, tray_uuid):
  2613. # Non-BL spool with some tag — let user choose
  2614. await _broadcast_unknown_tag(
  2615. printer_id=printer_id,
  2616. ams_id=ams_id,
  2617. tray_id=tray_id,
  2618. tag_uid=tag_uid,
  2619. tray_uuid=tray_uuid,
  2620. tray_type=tray.get("tray_type"),
  2621. tray_color=tray.get("tray_color"),
  2622. tray_sub_brands=tray.get("tray_sub_brands"),
  2623. tray_count=len(ams_unit.get("tray", [])),
  2624. )
  2625. # No-tag slots (generic non-RFID filament) are left alone:
  2626. # nothing to identify, prompting "+ Add" would just create
  2627. # ghost spools with empty tags on every confirm.
  2628. except Exception as e:
  2629. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2630. try:
  2631. async with async_session() as db:
  2632. from backend.app.api.routes.settings import get_setting
  2633. from backend.app.models.printer import Printer
  2634. # Check if Spoolman is enabled
  2635. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2636. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2637. return
  2638. # Check sync mode
  2639. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2640. if sync_mode and sync_mode != "auto":
  2641. return # Only sync on auto mode
  2642. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2643. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2644. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2645. # always owned by per-print tracking, never by AMS auto-sync. The
  2646. # setting is still read by the settings UI for backwards compat but
  2647. # has no effect on the sync path here.
  2648. # Get Spoolman URL
  2649. spoolman_url = await get_setting(db, "spoolman_url")
  2650. if not spoolman_url:
  2651. return
  2652. # Get or create Spoolman client
  2653. client = await get_spoolman_client()
  2654. if not client:
  2655. try:
  2656. client = await init_spoolman_client(spoolman_url)
  2657. except ValueError as exc:
  2658. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2659. return
  2660. # Check if Spoolman is reachable
  2661. if not await client.health_check():
  2662. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2663. return
  2664. # Get printer name for location
  2665. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2666. printer = result.scalar_one_or_none()
  2667. printer_name = printer.name if printer else f"Printer {printer_id}"
  2668. # OPTIMIZATION: Fetch all spools once before processing trays
  2669. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2670. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2671. try:
  2672. cached_spools = await client.get_spools()
  2673. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2674. except Exception as e:
  2675. logger.error(
  2676. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2677. printer_id,
  2678. e,
  2679. )
  2680. return
  2681. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2682. from sqlalchemy.orm import selectinload
  2683. from backend.app.models.spool_assignment import SpoolAssignment
  2684. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2685. from backend.app.services.ams_slot_presence import spool_present
  2686. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2687. # Built-in remaining weight, used by sync_ams_tray only when the
  2688. # firmware reports an unusable remain%/tray_weight for a slot.
  2689. #
  2690. # Left empty since #2812. This block runs in Spoolman mode only,
  2691. # and until then the built-in table was emptied on the switch, so
  2692. # there was never anything here to read and the fallback was inert.
  2693. # Preserving those rows makes it live again, and it is keyed by slot
  2694. # rather than by spool: after a mode switch the tray may well hold
  2695. # different filament, and ``create_spool`` writes ``remaining_weight``
  2696. # unconditionally, so a stale figure would be seeded into a brand new
  2697. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2698. # intent survives for whoever revisits the cross-mode fallback.
  2699. inventory_weights: dict[tuple[int, int], float] = {}
  2700. if not await spoolman_owns_assignments(db):
  2701. try:
  2702. assign_result = await db.execute(
  2703. select(SpoolAssignment)
  2704. .options(selectinload(SpoolAssignment.spool))
  2705. .where(SpoolAssignment.printer_id == printer_id)
  2706. )
  2707. for assignment in assign_result.scalars().all():
  2708. spool = assignment.spool
  2709. if spool and spool.label_weight > 0:
  2710. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2711. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2712. except Exception as e:
  2713. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2714. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2715. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2716. try:
  2717. slot_result = await db.execute(
  2718. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2719. )
  2720. for slot in slot_result.scalars().all():
  2721. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2722. except Exception as e:
  2723. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2724. # Sync each AMS tray and collect slot changes for DB persistence
  2725. synced = 0
  2726. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2727. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2728. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  2729. for ams_unit in ams_data:
  2730. if not isinstance(ams_unit, dict):
  2731. continue
  2732. ams_id = int(ams_unit.get("id", 0))
  2733. trays = ams_unit.get("tray", [])
  2734. for tray_data in trays:
  2735. if not isinstance(tray_data, dict):
  2736. continue
  2737. tray_id_raw = int(tray_data.get("id", 0))
  2738. tray = client.parse_ams_tray(ams_id, tray_data)
  2739. if not tray:
  2740. # Empty tray slot — record for local assignment cleanup
  2741. # and drop any cached unknown-tag broadcast so a
  2742. # reinserted spool re-prompts.
  2743. #
  2744. # Not during a running print: a slot that empties there
  2745. # is a filament runout, and the spool is still in the
  2746. # AMS. `spoolman_slot_assignments` is how a tag-less
  2747. # spool assigned through the Bambuddy UI is resolved at
  2748. # completion (#1459), so deleting the row mid-print
  2749. # loses the runout segment's usage — the same failure
  2750. # the internal inventory's auto-unlink had.
  2751. #
  2752. # Nor when firmware's presence bit says the slot is
  2753. # occupied. parse_ams_tray calls a tray with no type or
  2754. # no colour empty, and a spool the AMS cannot read has
  2755. # neither until something configures it — so a tag-less
  2756. # spool assigned through the UI had its row deleted by
  2757. # the first idle push after it was inserted. Same
  2758. # deletion as the internal inventory's in #3100, same
  2759. # answer, so the two modes stay in step.
  2760. #
  2761. # And only once the slot has stayed empty for the grace
  2762. # period -- the internal inventory's #3186 answer, for
  2763. # the same one-push blank.
  2764. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  2765. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  2766. if not printing_now and (
  2767. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  2768. ):
  2769. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2770. empty_slots.append((ams_id, tray_id_raw))
  2771. else:
  2772. spoolman_held.add(hold_key)
  2773. logger.info(
  2774. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  2775. "unlinking if it is still empty in %ds",
  2776. ams_id,
  2777. tray_id_raw,
  2778. linked_spool,
  2779. int(slot_unlink_grace.GRACE_SECONDS),
  2780. )
  2781. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2782. continue
  2783. spool_tag = (
  2784. tray.tray_uuid
  2785. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2786. else tray.tag_uid
  2787. )
  2788. # Provide the hint only when no RFID is available
  2789. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2790. try:
  2791. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2792. result = await client.sync_ams_tray(
  2793. tray,
  2794. printer_name,
  2795. db,
  2796. # Per-print tracking is the only weight writer (#1119).
  2797. # AMS auto-sync still maintains spool metadata / slot
  2798. # assignments but no longer touches remaining_weight.
  2799. disable_weight_sync=True,
  2800. cached_spools=cached_spools,
  2801. inventory_remaining=inv_remaining,
  2802. spoolman_spool_id_hint=hint,
  2803. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2804. )
  2805. if result is None and spool_tag and not auto_add_unknown_rfid:
  2806. # Spoolman skipped auto-create per user setting — surface
  2807. # the slot so the UI can offer "+ Add to inventory".
  2808. await _broadcast_unknown_tag(
  2809. printer_id=printer_id,
  2810. ams_id=ams_id,
  2811. tray_id=tray.tray_id,
  2812. tag_uid=tray.tag_uid or "",
  2813. tray_uuid=tray.tray_uuid or "",
  2814. tray_type=tray.tray_type,
  2815. tray_color=tray.tray_color,
  2816. tray_sub_brands=tray.tray_sub_brands,
  2817. tray_count=len(trays),
  2818. )
  2819. elif result:
  2820. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2821. if result:
  2822. synced += 1
  2823. if result.get("id"):
  2824. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2825. # If a new spool was created, add it to the cache
  2826. # so subsequent trays can find it if they reference the same tag
  2827. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  2828. if not spool_exists:
  2829. cached_spools.append(result)
  2830. logger.debug(
  2831. "[Printer %s] Added newly created spool %s to cache",
  2832. printer_id,
  2833. result["id"],
  2834. )
  2835. # Reconcile slot_preset_mappings (the same row internal
  2836. # mode keeps in sync via inventory + spool_tag_matcher).
  2837. # Without this the slot card surfaces the previous spool's
  2838. # preset name — same bug shape, different inventory mode.
  2839. from backend.app.services.slot_preset_writer import (
  2840. upsert_slot_preset_for_spoolman_spool,
  2841. )
  2842. await upsert_slot_preset_for_spoolman_spool(
  2843. db=db,
  2844. spoolman_spool=result,
  2845. tray_info_idx=tray.tray_info_idx or "",
  2846. tray_sub_brands=tray.tray_sub_brands or "",
  2847. tray_type=tray.tray_type or "",
  2848. printer_id=printer_id,
  2849. ams_id=ams_id,
  2850. tray_id=tray.tray_id,
  2851. )
  2852. except Exception as e:
  2853. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  2854. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  2855. if synced > 0:
  2856. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  2857. # Persist slot assignment changes to the local table
  2858. if slot_changes or empty_slots:
  2859. try:
  2860. for ams_id, tray_id, spool_id in slot_changes:
  2861. await db.execute(
  2862. text(
  2863. "INSERT INTO spoolman_slot_assignments"
  2864. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  2865. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  2866. " ON CONFLICT(printer_id, ams_id, tray_id)"
  2867. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  2868. ),
  2869. {
  2870. "printer_id": printer_id,
  2871. "ams_id": ams_id,
  2872. "tray_id": tray_id,
  2873. "spool_id": spool_id,
  2874. },
  2875. )
  2876. for ams_id, tray_id in empty_slots:
  2877. await db.execute(
  2878. delete(SpoolmanSlotAssignment).where(
  2879. SpoolmanSlotAssignment.printer_id == printer_id,
  2880. SpoolmanSlotAssignment.ams_id == ams_id,
  2881. SpoolmanSlotAssignment.tray_id == tray_id,
  2882. )
  2883. )
  2884. await db.commit()
  2885. except Exception as e:
  2886. await db.rollback()
  2887. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  2888. else:
  2889. # Tell open browsers the slot changed. This loop rewrites
  2890. # slot_preset_mappings via upsert_slot_preset_for_spoolman_spool
  2891. # above, and the AMS slot card reads that row ahead of the
  2892. # live tray_info_idx -- so with no event the card keeps
  2893. # showing the previous spool's preset name. Internal mode
  2894. # raises spool_auto_assigned for the same reason; this loop
  2895. # broadcast nothing at all, which made Spoolman mode the
  2896. # worse half of the same bug. On the else branch so a
  2897. # failed commit stays silent and a broadcast failure cannot
  2898. # roll back rows that are already committed.
  2899. for ams_id, tray_id, *_ in (*slot_changes, *empty_slots):
  2900. await ws_manager.broadcast(
  2901. {
  2902. "type": "spool_assignment_changed",
  2903. "printer_id": printer_id,
  2904. "ams_id": ams_id,
  2905. "tray_id": tray_id,
  2906. }
  2907. )
  2908. except Exception as e:
  2909. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  2910. # Largest finish photo attached to a notification; a bigger one is still linked.
  2911. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  2912. async def _finish_photo_for_notification(
  2913. db, archive, archive_id: int, filename: str
  2914. ) -> tuple[str | None, bytes | None]:
  2915. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  2916. With authentication off the link is the archive's own photo route, as it
  2917. always was: it opens without a login and doesn't expire. With
  2918. authentication on that route needs a media token, which nothing tapping a
  2919. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  2920. link only ever answered 401. The photo is then saved as a notification
  2921. photo as well (utils/notification_photos.py) and the link points there: an
  2922. unguessable name that opens this one photo and nothing else, for 3 days.
  2923. The link is relative when no External URL is set. Bytes over
  2924. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  2925. ``(None, None)`` when the photo can't be found.
  2926. """
  2927. from backend.app.api.routes.settings import get_setting
  2928. from backend.app.core.auth import is_auth_enabled
  2929. from backend.app.utils.archive_paths import find_archive_photo
  2930. from backend.app.utils.notification_photos import save_notification_photo
  2931. log = logging.getLogger(__name__)
  2932. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  2933. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  2934. photo_bytes: bytes | None = None
  2935. try:
  2936. photo_path = find_archive_photo(archive, filename)
  2937. if photo_path is not None:
  2938. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  2939. except Exception as e:
  2940. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  2941. try:
  2942. auth_on = await is_auth_enabled(db)
  2943. except Exception:
  2944. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  2945. if auth_on:
  2946. url = None
  2947. if photo_bytes:
  2948. try:
  2949. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  2950. url = f"{base}/api/v1/notifications/photos/{name}"
  2951. except Exception as e:
  2952. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  2953. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  2954. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  2955. return url, None
  2956. if photo_bytes:
  2957. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  2958. return url, photo_bytes
  2959. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  2960. """Capture a camera snapshot for notification image attachment.
  2961. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  2962. Uses: external camera > buffered frame > fresh capture.
  2963. Turns the chamber light on for the picture when the printer asks for it
  2964. (#1655). ``light=False`` is for callers that capture all through a print,
  2965. where the light would flash with every frame.
  2966. """
  2967. if not printer:
  2968. return None
  2969. async with camera_light(printer if light else None):
  2970. return await _capture_snapshot_frame(printer_id, printer, logger)
  2971. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  2972. """The capture behind ``_capture_snapshot_for_notification``."""
  2973. try:
  2974. from backend.app.api.routes.settings import get_setting
  2975. async with async_session() as db:
  2976. capture_enabled = await get_setting(db, "capture_finish_photo")
  2977. if capture_enabled is not None and capture_enabled.lower() != "true":
  2978. return None
  2979. # Try external camera first
  2980. if printer.external_camera_enabled and printer.external_camera_url:
  2981. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  2982. from backend.app.api.routes.camera import live_frame_for_capture
  2983. from backend.app.services.external_camera import capture_frame
  2984. # An external camera allows one reader, so capturing while a viewer
  2985. # is attached fails (#2707). A None here falls through to the paths
  2986. # below exactly as a failed capture did.
  2987. defer, buffered = live_frame_for_capture(printer_id)
  2988. if defer:
  2989. frame_data = buffered
  2990. else:
  2991. frame_data = await capture_frame(
  2992. printer.external_camera_url,
  2993. printer.external_camera_type or "mjpeg",
  2994. snapshot_url=printer.external_camera_snapshot_url,
  2995. )
  2996. if frame_data and len(frame_data) <= 2_500_000:
  2997. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  2998. return _apply_camera_rotation(frame_data, printer, logger)
  2999. # Try buffered frame from active stream
  3000. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3001. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3002. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3003. buffered_frame = get_buffered_frame(printer_id)
  3004. if (active_for_printer or active_chamber) and buffered_frame:
  3005. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3006. if len(buffered_frame) <= 2_500_000:
  3007. return _apply_camera_rotation(buffered_frame, printer, logger)
  3008. # Fresh capture from printer camera
  3009. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3010. from backend.app.services.camera import capture_camera_frame_bytes
  3011. frame_data = await capture_camera_frame_bytes(
  3012. printer.ip_address, printer.access_code, printer.model, timeout=15
  3013. )
  3014. if frame_data and len(frame_data) <= 2_500_000:
  3015. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3016. return _apply_camera_rotation(frame_data, printer, logger)
  3017. except Exception as e:
  3018. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3019. return None
  3020. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3021. """#1867: bank a recent in-print camera frame for the finish photo.
  3022. Called on every layer change and (#2547) on every print-progress advance.
  3023. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3024. path has a pre-End-G-code image for prints that end with a plate swap.
  3025. Both drivers are print telemetry that stops the instant printing ends: no
  3026. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3027. plate swap) executes. So the last banked frame is always the finished print,
  3028. never the swapped plate — that property is what the #1867 path relies on and
  3029. it must survive any change to the throttle below.
  3030. Layer changes alone were not enough: they stop when the *final* layer
  3031. begins, which on a three-minute last layer left the bank stale by the whole
  3032. length of that layer (#2547). Progress keeps ticking through it.
  3033. Best-effort: any failure just leaves the previous banked frame.
  3034. """
  3035. logger = logging.getLogger(__name__)
  3036. client = printer_manager.get_client(printer_id)
  3037. state = client.state if client else None
  3038. if not state or state.state != "RUNNING":
  3039. return
  3040. # Only during actual extrusion — firmware ticks layer_num during the
  3041. # pre-print calibration sequence, whose sub-stages are non-zero.
  3042. if state.mc_print_sub_stage not in (None, 0):
  3043. return
  3044. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3045. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3046. # now that progress advances also drive banking, that exemption would fire a
  3047. # camera grab on every percent tick of the last layer. Bambu printers accept
  3048. # one RTSP client at a time, so each grab contends with the live view.
  3049. now = time.monotonic()
  3050. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3051. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3052. return
  3053. total = state.total_layers or 0
  3054. try:
  3055. async with async_session() as db:
  3056. from backend.app.models.printer import Printer
  3057. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3058. printer = result.scalar_one_or_none()
  3059. if not printer:
  3060. return
  3061. # Reuses the notification snapshot path, which honours the
  3062. # `capture_finish_photo` setting (returns None when disabled) so we
  3063. # don't bank frames the user never asked for. Without the chamber light
  3064. # (#1655): this runs every 25 seconds for the whole print.
  3065. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3066. if frame:
  3067. _inprint_frame_bank[printer_id] = frame
  3068. _inprint_frame_bank_ts[printer_id] = now
  3069. logger.debug(
  3070. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3071. printer_id,
  3072. layer_num,
  3073. total,
  3074. len(frame),
  3075. )
  3076. except Exception as e:
  3077. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3078. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3079. """Apply camera rotation to snapshot image if configured."""
  3080. from backend.app.services.camera import apply_camera_rotation
  3081. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3082. async def _send_print_start_notification(
  3083. printer_id: int,
  3084. data: dict,
  3085. archive_data: dict | None = None,
  3086. logger=None,
  3087. ):
  3088. """Helper to send print start notification with optional archive data."""
  3089. if logger is None:
  3090. logger = logging.getLogger(__name__)
  3091. try:
  3092. async with async_session() as db:
  3093. from backend.app.models.printer import Printer
  3094. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3095. printer = result.scalar_one_or_none()
  3096. printer_name = printer.name if printer else f"Printer {printer_id}"
  3097. # Capture camera snapshot for notification image attachment
  3098. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3099. if image_data:
  3100. if archive_data is None:
  3101. archive_data = {}
  3102. archive_data["image_data"] = image_data
  3103. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3104. # Send user-specific email notification for print start
  3105. if archive_data and archive_data.get("created_by_id"):
  3106. await notification_service.send_user_print_email(
  3107. event_type="user_print_start",
  3108. created_by_id=archive_data["created_by_id"],
  3109. printer_name=printer_name,
  3110. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3111. db=db,
  3112. )
  3113. except Exception as e:
  3114. logger.warning("Notification on_print_start failed: %s", e)
  3115. async def _dispatch_user_print_email(
  3116. status: str,
  3117. created_by_id: int | None,
  3118. printer_name: str,
  3119. filename: str,
  3120. db,
  3121. image_data: bytes | None = None,
  3122. finish_photo_url: str | None = None,
  3123. ) -> None:
  3124. """Send a user-specific print-completion email based on print status.
  3125. Maps the normalised print status to the correct event type and delegates
  3126. to :meth:`NotificationService.send_user_print_email`. A single helper
  3127. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3128. "stopped"`` dispatch block at every call site.
  3129. Does nothing if *created_by_id* is ``None``.
  3130. """
  3131. if created_by_id is None:
  3132. return
  3133. if status == "completed":
  3134. event_type = "user_print_complete"
  3135. elif status == "failed":
  3136. event_type = "user_print_failed"
  3137. elif status in ("stopped", "aborted", "cancelled"):
  3138. event_type = "user_print_stopped"
  3139. else:
  3140. return
  3141. await notification_service.send_user_print_email(
  3142. event_type=event_type,
  3143. created_by_id=created_by_id,
  3144. printer_name=printer_name,
  3145. filename=filename,
  3146. db=db,
  3147. image_data=image_data,
  3148. finish_photo_url=finish_photo_url,
  3149. )
  3150. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3151. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3152. try:
  3153. from backend.app.services.archive import extract_printable_objects_from_archive
  3154. client = printer_manager.get_client(printer_id)
  3155. if not client:
  3156. return
  3157. # Extract with positions for UI overlay, scoped to the plate that
  3158. # is printing — resolve_plate_id is the same resolver /cover uses,
  3159. # so the object list can't disagree with the thumbnail it is drawn
  3160. # over (#2522).
  3161. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3162. app_settings.base_dir / archive.file_path,
  3163. plate_number=resolve_plate_id(client.state),
  3164. )
  3165. if printable_objects:
  3166. client.state.printable_objects = printable_objects
  3167. client.state.printable_objects_bbox_all = bbox_all
  3168. client.state.skipped_objects = []
  3169. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3170. except Exception as e:
  3171. logger.debug("Failed to extract printable objects from archive: %s", e)
  3172. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3173. """Put the skip-objects list back after a restart mid-print.
  3174. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3175. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3176. which the #1304 guard suppresses on the first RUNNING push after startup.
  3177. Everything else this hook restores (the archive, the usage-tracking session,
  3178. the timelapse baseline) was already handled; the object list was not, so a
  3179. restart mid-print took skip-objects away for the rest of that print.
  3180. Nothing recovered it either: the printer card gates its Skip button on the
  3181. object count, and the one endpoint that can rebuild the list is reachable
  3182. only from the modal that button opens.
  3183. Anchored on ``subtask_id``, which the firmware mints per print, so a
  3184. leftover ``status="printing"`` row from a completion we never saw cannot
  3185. hand this print someone else's objects. Without one, nothing is loaded
  3186. rather than guessed — the reload path on ``GET /print/objects`` covers that
  3187. case on demand.
  3188. """
  3189. client = printer_manager.get_client(printer_id)
  3190. if client is None or client.state.printable_objects:
  3191. return
  3192. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  3193. if subtask_id in ("", "0"):
  3194. return
  3195. from backend.app.models.archive import PrintArchive
  3196. archive = await db.scalar(
  3197. select(PrintArchive)
  3198. .where(
  3199. PrintArchive.printer_id == printer_id,
  3200. PrintArchive.status == "printing",
  3201. PrintArchive.subtask_id == subtask_id,
  3202. )
  3203. .order_by(PrintArchive.created_at.desc())
  3204. .limit(1)
  3205. )
  3206. if archive is not None:
  3207. _load_objects_from_archive(archive, printer_id, logger)
  3208. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3209. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3210. # past it; the second covers a handshake that failed again on the way back and
  3211. # armed a fresh one. Module-level so tests can shrink them.
  3212. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3213. # Retry ladder for the other temporary give-up: the file service answered and
  3214. # the transfer still did not finish, which at print start is usually the printer
  3215. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3216. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3217. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3218. # two cover a printer that stays busy well into the print.
  3219. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3220. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3221. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3222. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3223. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3224. # by view, so two views race), the cool-off retry task, and print completion.
  3225. # Without this they each read file_path == "" and each run a full copy, so the row
  3226. # ends up pointing at one timestamped directory while the others sit orphaned.
  3227. #
  3228. # Keyed by printer rather than archive because a printer runs one print at a time,
  3229. # which makes the two equally strong here — and it bounds the dict by printer
  3230. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3231. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3232. # resuming, so "no waiters" is not a question this API can answer.
  3233. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3234. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3235. """Fill in a no-3MF archive from a 3MF that turned up later.
  3236. Returns True when the row was upgraded. Safe to call speculatively: it
  3237. verifies the archive still exists, is still a fallback, and that the file
  3238. is a readable 3MF before touching anything.
  3239. Serialised per printer — see ``_fallback_recovery_locks``.
  3240. """
  3241. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3242. async with lock:
  3243. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id)
  3244. async def _recover_fallback_archive_locked(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3245. """The body of :func:`_recover_fallback_archive`, under its per-printer lock."""
  3246. import zipfile
  3247. from backend.app.models.archive import PrintArchive
  3248. from backend.app.services.archive import ArchiveService
  3249. logger = logging.getLogger(__name__)
  3250. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3251. return False
  3252. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3253. # A truncated or half-written download is worse than no download: it
  3254. # would replace an honest empty archive with wrong metadata.
  3255. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3256. return False
  3257. async with async_session() as db:
  3258. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3259. if archive is None or archive.deleted_at is not None:
  3260. return False
  3261. if archive.file_path:
  3262. # Already recovered, or never was a fallback. Either way there is a
  3263. # real 3MF attached and overwriting it is not this function's job.
  3264. return False
  3265. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3266. service = ArchiveService(db)
  3267. recovered = await service.archive_print(
  3268. printer_id=printer_id,
  3269. source_file=source_3mf,
  3270. print_data={**print_data, "status": archive.status or "printing"},
  3271. subtask_id=archive.subtask_id,
  3272. update_archive_id=archive.id,
  3273. )
  3274. if recovered is None:
  3275. return False
  3276. logger.info(
  3277. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3278. archive_id,
  3279. source_3mf,
  3280. recovered.file_size,
  3281. )
  3282. # `archive_updated`, not `archive_created` — the row was already on the
  3283. # Archives page as an empty card and is now filled in, not new.
  3284. await ws_manager.send_archive_updated(
  3285. {
  3286. "id": recovered.id,
  3287. "printer_id": recovered.printer_id,
  3288. "filename": recovered.filename,
  3289. "print_name": recovered.print_name,
  3290. "status": recovered.status,
  3291. }
  3292. )
  3293. return True
  3294. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path) -> bool:
  3295. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3296. Called from the paths that pull a 3MF for a print that is already under way
  3297. — chiefly the cover endpoint, which downloads the very file the archive flow
  3298. could not get and, before #2957, used it for a thumbnail and nothing else.
  3299. The bytes are already local, so this costs a parse and a row update.
  3300. No-op when the running print has a real archive, which is the common case.
  3301. """
  3302. from backend.app.models.archive import PrintArchive
  3303. logger = logging.getLogger(__name__)
  3304. # `_active_prints` is keyed on the raw names seen at print start — the
  3305. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3306. # Callers here arrive with whichever variant their own path produced, so
  3307. # match on the same normalization the download cache uses rather than on an
  3308. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3309. # endpoint find an archive registered under "Desktop_Goose".
  3310. wanted = normalize_3mf_name(name)
  3311. archive_id = None
  3312. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3313. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3314. archive_id = value
  3315. break
  3316. if archive_id is None:
  3317. return False
  3318. async with async_session() as db:
  3319. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3320. # Cheap pre-check so the common case (a normal archive) does no work.
  3321. if archive is None or archive.file_path or archive.deleted_at is not None:
  3322. return False
  3323. try:
  3324. return await _recover_fallback_archive(archive_id, path, printer_id)
  3325. except Exception as e:
  3326. # Recovery is opportunistic. A failure here must never take down the
  3327. # caller, which is usually just trying to render a thumbnail.
  3328. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3329. return False
  3330. def _schedule_fallback_3mf_retry(
  3331. printer_id: int,
  3332. archive_id: int,
  3333. filenames: list[str],
  3334. delays: tuple[float, ...] | None = None,
  3335. reason: str = REASON_FTPS_COOLOFF,
  3336. ) -> None:
  3337. """Re-attempt the 3MF download after a temporary give-up.
  3338. ``reason`` says which give-up this is, and picks the default ladder: an
  3339. FTPS cool-off has to be waited out, while a transfer that timed out under
  3340. contention is worth asking about again straight away (#3063). It is only
  3341. read for the ladder and the log line -- the retry itself is identical, since
  3342. in both cases the file is on the printer and the last attempt at it failed
  3343. for a reason that does not last.
  3344. """
  3345. logger = logging.getLogger(__name__)
  3346. if delays is None:
  3347. delays = (
  3348. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3349. if reason == REASON_FTP_TRANSFER_FAILED
  3350. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3351. )
  3352. async def _retry() -> None:
  3353. from backend.app.models.archive import PrintArchive
  3354. from backend.app.models.printer import Printer
  3355. for delay in delays:
  3356. await asyncio.sleep(delay)
  3357. async with async_session() as db:
  3358. archive = (
  3359. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3360. ).scalar_one_or_none()
  3361. if archive is None or archive.deleted_at is not None or archive.file_path:
  3362. return
  3363. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3364. if printer is None:
  3365. return
  3366. # Read the fields while the session is open rather than touching
  3367. # a detached instance minutes later, mid-download.
  3368. printer_ip = printer.ip_address
  3369. printer_code = printer.access_code
  3370. printer_model = printer.model
  3371. # Someone else may have fetched it in the meantime — the cover
  3372. # endpoint routinely does, and its copy is the same bytes.
  3373. for name in filenames:
  3374. cached = get_cached_3mf(printer_id, name)
  3375. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3376. return
  3377. if ftps_handshake_blocked(printer_ip):
  3378. logger.info(
  3379. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3380. printer_id,
  3381. archive_id,
  3382. )
  3383. continue
  3384. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3385. for candidate in filenames:
  3386. # Bare name only. These come from the print-start flow, which
  3387. # already strips the path, but the local temp write must not
  3388. # depend on that holding for every future caller — a name that
  3389. # is absolute or contains ".." would otherwise escape the data
  3390. # volume via the `/` operator.
  3391. name = Path(candidate).name
  3392. if not name or name in (".", ".."):
  3393. continue
  3394. if not name.endswith(".3mf"):
  3395. name = f"{name}.3mf"
  3396. temp_path = app_settings.archive_dir / "temp" / name
  3397. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3398. try:
  3399. hit = await download_file_try_paths_async(
  3400. printer_ip,
  3401. printer_code,
  3402. ftp_probe_paths(name),
  3403. temp_path,
  3404. socket_timeout=ftp_timeout,
  3405. printer_model=printer_model,
  3406. )
  3407. except Exception as e:
  3408. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3409. continue
  3410. if not hit:
  3411. continue
  3412. cache_3mf_download(printer_id, name, temp_path)
  3413. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3414. return
  3415. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3416. async def _guarded() -> None:
  3417. try:
  3418. await _retry()
  3419. except asyncio.CancelledError:
  3420. raise
  3421. except Exception as e:
  3422. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3423. finally:
  3424. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3425. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3426. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3427. if existing and not existing.done():
  3428. existing.cancel()
  3429. task = asyncio.create_task(_guarded())
  3430. _fallback_3mf_retry_tasks[printer_id] = task
  3431. logger.info(
  3432. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3433. archive_id,
  3434. reason,
  3435. printer_id,
  3436. ", ".join(f"{d:g}s" for d in delays),
  3437. )
  3438. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3439. """Whether an archive created here should ask for the print's outcome (#1898).
  3440. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3441. branches below: a queued job already has its archive and takes the
  3442. expected-print branch, where the queue item's own ``confirm_outcome``
  3443. decides. The queue is still consulted, because a restart mid-print empties
  3444. ``_expected_prints`` — without the check the setting could override a queue
  3445. item that deliberately has the flag off. Any failure answers "don't ask":
  3446. an unwanted prompt is worse than a missing one, and this must never be the
  3447. reason a print goes unarchived.
  3448. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3449. leaves one behind when a completion cannot be matched to it
  3450. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3451. only takes it back once the printer has sat connected and terminal for
  3452. minutes. Until then every screen-started print on that printer would
  3453. silently lose its prompt, so the row is held against ``observed_name`` by
  3454. the same comparison a completion uses: a positive disagreement means the row
  3455. is about some other run and this print is external after all.
  3456. """
  3457. logger = logging.getLogger(__name__)
  3458. try:
  3459. # A savepoint rather than a rollback of the caller's transaction on
  3460. # failure: a failed statement leaves the transaction unusable, but a
  3461. # full rollback also expires every object the caller has loaded (the
  3462. # printer, the archive it just created), and on an async session the
  3463. # next attribute read then raises instead of reloading. Everything here
  3464. # is a read, so undoing the savepoint loses nothing.
  3465. async with db.begin_nested():
  3466. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3467. except Exception as e:
  3468. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3469. return False
  3470. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3471. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3472. from backend.app.api.routes.settings import get_setting, setting_is_true
  3473. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3474. return False
  3475. from backend.app.models.print_queue import PrintQueueItem
  3476. dispatched_here = await db.scalar(
  3477. select(PrintQueueItem)
  3478. .where(
  3479. PrintQueueItem.printer_id == printer_id,
  3480. PrintQueueItem.status == "printing",
  3481. )
  3482. .limit(1)
  3483. )
  3484. if dispatched_here is None:
  3485. return True
  3486. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3487. observed = (observed_name or "").strip()
  3488. if not expected or not observed or _subtask_names_match(expected, observed):
  3489. logger.info(
  3490. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3491. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3492. printer_id,
  3493. dispatched_here.id,
  3494. )
  3495. return False
  3496. logger.info(
  3497. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3498. "%r; treating this as an externally started print.",
  3499. dispatched_here.id,
  3500. printer_id,
  3501. expected,
  3502. observed,
  3503. )
  3504. return True
  3505. async def _dispatch_outcome_confirmation_safely(
  3506. db,
  3507. printer_id: int,
  3508. printer_name: str,
  3509. data: dict,
  3510. archive_id: int,
  3511. archive_data: dict | None = None,
  3512. ) -> None:
  3513. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3514. The completion task sends the per-user print email on the same session
  3515. right after the prompt. A failed statement in the prompt leaves that
  3516. session needing a rollback, and without one the email step fails with
  3517. PendingRollbackError; the prompt is the optional part, so it must not be
  3518. the reason the email never goes out.
  3519. """
  3520. try:
  3521. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3522. except Exception as e:
  3523. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  3524. try:
  3525. await db.rollback()
  3526. except Exception:
  3527. pass
  3528. async def dispatch_outcome_confirmation(
  3529. db,
  3530. printer_id: int,
  3531. printer_name: str,
  3532. data: dict,
  3533. archive_id: int,
  3534. archive_data: dict | None = None,
  3535. ) -> bool:
  3536. """Emit the post-print outcome prompt for a completed archive (#1898).
  3537. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3538. queue item, or from ``confirm_outcome_external_prints`` for a print
  3539. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3540. question still open. Mints the per-archive capability token the one-tap
  3541. verdict links carry.
  3542. Lives here rather than inline in ``on_print_complete``'s notification task
  3543. because that task swallows every exception: extracted, the gate and the two
  3544. emissions can be driven by a test, which is the only thing standing between
  3545. a regression here and a farm that quietly stops asking.
  3546. Returns whether a prompt was sent.
  3547. """
  3548. logger = logging.getLogger(__name__)
  3549. from backend.app.models.archive import PrintArchive
  3550. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3551. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3552. return False
  3553. import secrets as _secrets
  3554. # A spent token stays on the row so the one-tap route can recognise it, so
  3555. # "has a token" no longer means "answerable". A prompt going out now needs a
  3556. # live one: mint a new token whenever the stored one is already spent, or
  3557. # every button in the new message would land on the already-answered page.
  3558. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  3559. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  3560. confirm_archive.confirm_token_used_at = None
  3561. await db.commit()
  3562. from backend.app.api.routes.settings import get_external_base_url, get_setting
  3563. base = await get_external_base_url(db)
  3564. if not await get_setting(db, "external_url"):
  3565. # Both the Telegram inline keyboard and the ntfy action buttons need an
  3566. # absolute URL, so an unconfigured install used to get a message body
  3567. # with two unusable relative paths and no buttons at all. The shared
  3568. # fallback at least produces tappable links; say which setting makes
  3569. # them resolve from a phone.
  3570. logger.warning(
  3571. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  3572. "Set Settings → External URL so they resolve away from this host.",
  3573. base,
  3574. )
  3575. token = confirm_archive.confirm_token
  3576. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  3577. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  3578. confirm_url = f"{base}/archives?confirm={archive_id}"
  3579. await ws_manager.send_print_confirm_request(
  3580. printer_id,
  3581. {
  3582. "archive_id": archive_id,
  3583. "print_name": confirm_archive.print_name or confirm_archive.filename,
  3584. },
  3585. )
  3586. await notification_service.on_print_confirm_request(
  3587. printer_id,
  3588. printer_name,
  3589. data,
  3590. db,
  3591. archive_data=archive_data,
  3592. good_url=good_url,
  3593. reject_url=reject_url,
  3594. confirm_url=confirm_url,
  3595. archive_id=archive_id,
  3596. )
  3597. return True
  3598. async def on_print_start(printer_id: int, data: dict):
  3599. """Handle print start - archive the 3MF file immediately."""
  3600. logger = logging.getLogger(__name__)
  3601. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3602. # Clear any stale user-stopped flag from previous print cycles
  3603. _user_stopped_printers.discard(printer_id)
  3604. # A new print starts its milestones from zero (#3211). The status path only
  3605. # resets on progress below 5 while not printing, which a printer that goes
  3606. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  3607. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  3608. # or on resume from pause, so it cannot repeat a milestone mid-print.
  3609. _last_progress_milestone[printer_id] = 0
  3610. _kill_switch_notification_tasks.pop(printer_id, None)
  3611. # #1721: drop any leftover pre-captured finish frame from a prior print
  3612. # so a never-consumed cache entry can't bleed into the new print's photo.
  3613. _stage22_finish_frames.pop(printer_id, None)
  3614. # #1867: same for the in-print frame bank — a queued print must not reuse
  3615. # the previous job's banked frame.
  3616. _inprint_frame_bank.pop(printer_id, None)
  3617. _inprint_frame_bank_ts.pop(printer_id, None)
  3618. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3619. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3620. # print's flag instead of inheriting it.
  3621. print_dispatch_context.adopt(printer_id)
  3622. # Cancel any active bed cooldown waiter for this printer
  3623. if _bed_cool_waiters.pop(printer_id, None):
  3624. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  3625. # Clear cached cover images so the new print's thumbnail is fetched fresh
  3626. from backend.app.api.routes.printers import clear_cover_cache
  3627. clear_cover_cache(printer_id)
  3628. await ws_manager.send_print_start(printer_id, data)
  3629. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  3630. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  3631. # MQTT relay - publish print start
  3632. try:
  3633. printer_info = printer_manager.get_printer(printer_id)
  3634. if printer_info:
  3635. await mqtt_relay.on_print_start(
  3636. printer_id,
  3637. printer_info.name,
  3638. printer_info.serial_number,
  3639. data.get("filename", ""),
  3640. data.get("subtask_name", ""),
  3641. )
  3642. except Exception:
  3643. pass # Don't fail print start callback if MQTT fails
  3644. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  3645. # and mapping, and the seeded tray-change log.
  3646. #
  3647. # Unconditional, for both inventory backends. This only *captures* — the
  3648. # writing is still split, with the internal tracker skipped at completion
  3649. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  3650. # carries its plate-scoped 3MF figures and stored mapping, but not the
  3651. # tray-change log, and that log is the only record of which spool fed
  3652. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  3653. # it on one side only would leave Spoolman users with the mid-print
  3654. # restart bug this fixes for everyone else.
  3655. try:
  3656. async with async_session() as db:
  3657. from backend.app.api.routes.settings import get_setting
  3658. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  3659. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3660. await usage_on_print_start(
  3661. printer_id,
  3662. data,
  3663. printer_manager,
  3664. db=db,
  3665. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  3666. )
  3667. except Exception as e:
  3668. logger.warning("Usage tracker on_print_start failed: %s", e)
  3669. # Track if notification was sent (to avoid sending twice)
  3670. notification_sent = False
  3671. # Smart plug automation: turn on plug when print starts
  3672. try:
  3673. async with async_session() as db:
  3674. await smart_plug_manager.on_print_start(printer_id, db)
  3675. except Exception as e:
  3676. logger.warning("Smart plug on_print_start failed: %s", e)
  3677. async with async_session() as db:
  3678. from backend.app.models.printer import Printer
  3679. from backend.app.services.bambu_ftp import list_files_async
  3680. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3681. printer = result.scalar_one_or_none()
  3682. # Plate detection check - pause if objects detected on build plate
  3683. logger.info(
  3684. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  3685. )
  3686. if printer and printer.plate_detection_enabled:
  3687. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  3688. # Release the pooled DB connection before the plate-detection camera
  3689. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  3690. # printer SELECT has run so far — nothing to persist — so this commit
  3691. # is a data-noop that ends the read transaction and returns the
  3692. # connection to the pool during the I/O (issue #2572). expire_on_commit
  3693. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  3694. # archive lookups below re-acquire a fresh connection on next execute.
  3695. await db.commit()
  3696. try:
  3697. from backend.app.services.plate_detection import check_plate_empty
  3698. # Build ROI tuple from printer settings if available
  3699. roi = None
  3700. if all(
  3701. [
  3702. printer.plate_detection_roi_x is not None,
  3703. printer.plate_detection_roi_y is not None,
  3704. printer.plate_detection_roi_w is not None,
  3705. printer.plate_detection_roi_h is not None,
  3706. ]
  3707. ):
  3708. roi = (
  3709. printer.plate_detection_roi_x,
  3710. printer.plate_detection_roi_y,
  3711. printer.plate_detection_roi_w,
  3712. printer.plate_detection_roi_h,
  3713. )
  3714. # Auto-turn on chamber light if it's off for better detection
  3715. light_was_off = False
  3716. client = printer_manager.get_client(printer_id)
  3717. if client and client.state:
  3718. light_was_off = not client.state.chamber_light
  3719. if light_was_off:
  3720. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  3721. client.set_chamber_light(True)
  3722. # Wait for light to physically turn on and camera to adjust exposure
  3723. await asyncio.sleep(2.5)
  3724. plate_photo_data = None
  3725. objects_detected = False
  3726. try:
  3727. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  3728. plate_result = await check_plate_empty(
  3729. printer_id=printer_id,
  3730. ip_address=printer.ip_address,
  3731. access_code=printer.access_code,
  3732. model=printer.model,
  3733. include_debug_image=False,
  3734. external_camera_url=printer.external_camera_url,
  3735. external_camera_type=printer.external_camera_type,
  3736. use_external=printer.external_camera_enabled,
  3737. roi=roi,
  3738. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  3739. )
  3740. objects_detected = not plate_result.needs_calibration and not plate_result.is_empty
  3741. if objects_detected:
  3742. # Objects detected - pause the print!
  3743. logger.warning(
  3744. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  3745. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  3746. )
  3747. pause_client = printer_manager.get_client(printer_id)
  3748. if pause_client:
  3749. pause_client.pause_print()
  3750. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  3751. # Snapshot while the light's still on — restoring it first
  3752. # would leave the notification with a dark photo.
  3753. try:
  3754. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3755. except Exception as snap_err:
  3756. logger.warning(
  3757. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  3758. )
  3759. finally:
  3760. # Restore chamber light to original state as soon as the
  3761. # camera is done with it, whatever happened above.
  3762. if light_was_off and client:
  3763. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  3764. try:
  3765. client.set_chamber_light(False)
  3766. except Exception as light_err:
  3767. logger.warning(
  3768. "[PLATE CHECK] Failed to restore chamber light for printer %s: %s",
  3769. printer_id,
  3770. light_err,
  3771. )
  3772. if objects_detected:
  3773. # Send notification about plate not empty
  3774. await ws_manager.broadcast(
  3775. {
  3776. "type": "plate_not_empty",
  3777. "printer_id": printer_id,
  3778. "printer_name": printer.name,
  3779. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  3780. }
  3781. )
  3782. # Also send push notification
  3783. try:
  3784. await notification_service.on_plate_not_empty(
  3785. printer_id=printer_id,
  3786. printer_name=printer.name,
  3787. db=db,
  3788. difference_percent=plate_result.difference_percent,
  3789. image_data=plate_photo_data,
  3790. )
  3791. except Exception as notif_err:
  3792. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  3793. else:
  3794. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  3795. except Exception as plate_err:
  3796. # Don't block print on plate detection errors
  3797. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  3798. if not printer:
  3799. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  3800. if not notification_sent:
  3801. await _send_print_start_notification(printer_id, data, logger=logger)
  3802. return
  3803. if not printer.auto_archive:
  3804. # auto-archive disabled — check if there's an expected print (dispatched
  3805. # by BamBuddy via queue/reprint) that already has an archive to promote.
  3806. # If so, fall through to the expected-print handling below so the archive
  3807. # is tracked in _active_prints and usage tracking works at completion.
  3808. _fn = data.get("filename", "")
  3809. _sn = data.get("subtask_name", "")
  3810. _check_keys: list[tuple[int, str]] = []
  3811. if _sn:
  3812. _check_keys += [
  3813. (printer_id, _sn),
  3814. (printer_id, f"{_sn}.3mf"),
  3815. (printer_id, f"{_sn}.gcode.3mf"),
  3816. ]
  3817. if _fn:
  3818. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  3819. _check_keys.append((printer_id, _base_fn))
  3820. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  3821. _check_keys += [
  3822. (printer_id, _no_archive_base),
  3823. (printer_id, f"{_no_archive_base}.3mf"),
  3824. ]
  3825. _has_expected = any(k in _expected_prints for k in _check_keys)
  3826. if not _has_expected:
  3827. # No expected print — truly external print (started from slicer/touchscreen)
  3828. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  3829. if not notification_sent:
  3830. _no_archive_creator: int | None = None
  3831. for _key in _check_keys:
  3832. _expected_prints.pop(_key, None)
  3833. _expected_print_registered_at.pop(_key, None)
  3834. popped_creator = _expected_print_creators.pop(_key, None)
  3835. if _no_archive_creator is None:
  3836. _no_archive_creator = popped_creator
  3837. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  3838. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  3839. return
  3840. else:
  3841. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  3842. # Get the filename and subtask_name
  3843. filename = data.get("filename", "")
  3844. subtask_name = data.get("subtask_name", "")
  3845. # MQTT subtask_id uniquely identifies a print job on the printer. When
  3846. # present, it lets us match an archive across a backend restart (#972):
  3847. # same id → same print → resume the existing row instead of cancelling
  3848. # it and recreating from scratch (which loses started_at). Treat "0"
  3849. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  3850. raw_mqtt = data.get("raw_data") or {}
  3851. subtask_id = raw_mqtt.get("subtask_id")
  3852. if subtask_id is not None:
  3853. subtask_id = str(subtask_id).strip()
  3854. if subtask_id in ("", "0"):
  3855. subtask_id = None
  3856. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  3857. # Skip the printer's own jobs — a calibration run is not a user's print.
  3858. # See is_internal_printer_job for what counts and why both fields are
  3859. # tested; the pressure-advance line reports as a subtask name with no
  3860. # /usr/ path, which the old prefix-only test here missed entirely.
  3861. #
  3862. # No notification either. The event describes the printer calibrating
  3863. # itself, so "Print started" is as wrong as the archive was, and the
  3864. # matching completion is suppressed in on_print_complete for the same
  3865. # reason.
  3866. if is_internal_printer_job(filename, subtask_name):
  3867. logger.info(
  3868. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  3869. filename,
  3870. subtask_name,
  3871. )
  3872. return
  3873. if not filename and not subtask_name:
  3874. # Send notification without archive data (no filename)
  3875. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  3876. if not notification_sent:
  3877. await _send_print_start_notification(printer_id, data, logger=logger)
  3878. return
  3879. # Check if this is an expected print from reprint/scheduled
  3880. # Build list of possible keys to check
  3881. expected_keys = []
  3882. if subtask_name:
  3883. expected_keys.append((printer_id, subtask_name))
  3884. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  3885. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3886. if filename:
  3887. fname = filename.split("/")[-1] if "/" in filename else filename
  3888. expected_keys.append((printer_id, fname))
  3889. # Strip extensions to match
  3890. base = fname.replace(".gcode", "").replace(".3mf", "")
  3891. expected_keys.append((printer_id, base))
  3892. expected_keys.append((printer_id, f"{base}.3mf"))
  3893. expected_archive_id = None
  3894. for key in expected_keys:
  3895. expected_archive_id = _expected_prints.pop(key, None)
  3896. _expected_print_registered_at.pop(key, None)
  3897. if expected_archive_id:
  3898. # Clean up other possible keys for this print
  3899. for other_key in expected_keys:
  3900. _expected_prints.pop(other_key, None)
  3901. _expected_print_registered_at.pop(other_key, None)
  3902. break
  3903. if expected_archive_id:
  3904. # This is a reprint/scheduled print - use existing archive, don't create new one
  3905. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  3906. from backend.app.models.archive import PrintArchive
  3907. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  3908. archive = result.scalar_one_or_none()
  3909. if archive:
  3910. # Update archive status to printing
  3911. archive.status = "printing"
  3912. archive.started_at = datetime.now(timezone.utc)
  3913. # The previous run's answer is still on this row and the
  3914. # completion prompt is gated on ``user_verdict is None`` (#1898),
  3915. # so without a reset the second run inherits the first run's
  3916. # verdict: no prompt at all, and a green "good" badge on a run
  3917. # nobody ever judged.
  3918. if archive.confirm_requested:
  3919. archive.user_verdict = None
  3920. archive.user_verdict_source = None
  3921. archive.user_verdict_at = None
  3922. archive.confirm_token = None
  3923. archive.confirm_token_used_at = None
  3924. # Reprint of an archive reuses the source row. Without resetting
  3925. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  3926. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  3927. # extracts the *original* print's last frame, which then ships in
  3928. # the completion notification (#1707). Clear the path so the
  3929. # scanner runs fresh; also unlink the old video file so reprints
  3930. # don't accumulate orphans in the archive directory. Photos list
  3931. # is left alone — accumulating one finish photo per run is fine.
  3932. # The print-start baseline (#2704) is stale for the same reason:
  3933. # it describes the printer before the previous run. The capture
  3934. # below overwrites it, but clear it here too so an early failure
  3935. # can't leave the scan diffing against the wrong snapshot.
  3936. archive.timelapse_baseline = None
  3937. stale_timelapse_relpath = archive.timelapse_path
  3938. if stale_timelapse_relpath:
  3939. archive.timelapse_path = None
  3940. try:
  3941. stale_path = app_settings.base_dir / stale_timelapse_relpath
  3942. if stale_path.is_file():
  3943. stale_path.unlink()
  3944. logger.info(
  3945. "Deleted stale timelapse %s on reprint of archive %s",
  3946. stale_timelapse_relpath,
  3947. expected_archive_id,
  3948. )
  3949. except OSError as e:
  3950. logger.warning(
  3951. "Failed to delete stale timelapse %s on reprint: %s",
  3952. stale_timelapse_relpath,
  3953. e,
  3954. )
  3955. # Persist a restart-stable id so a later restart resumes this
  3956. # archive by subtask_id instead of name-matching + duplicating
  3957. # it (#1485). The printer often hasn't echoed subtask_id back
  3958. # this soon after dispatch, so fall back to the id Bambuddy
  3959. # minted when it sent the print command. Scoped to this
  3960. # expected-print branch on purpose: an expected match means
  3961. # Bambuddy dispatched this exact print in this process, so the
  3962. # client's last-dispatch id genuinely belongs to it — using it
  3963. # for an externally-started print could mis-tag the archive.
  3964. effective_subtask_id = subtask_id
  3965. if not effective_subtask_id:
  3966. _client = printer_manager.get_client(printer_id)
  3967. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  3968. if _dispatched:
  3969. effective_subtask_id = str(_dispatched).strip() or None
  3970. # Update on first-set OR on reprint (the queue dispatcher mints
  3971. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  3972. # the rewrite for reprints leaves the archive holding the FIRST
  3973. # run's id; if MQTT then reconnects mid-print, the reconciler
  3974. # (#1542) compares the stale stored id against the printer's
  3975. # live id, sees a mismatch, and synthesises a bogus PRINT
  3976. # COMPLETE — exactly the false-positive "Print Stopped" reported
  3977. # in #1807. Inequality check preserves the noop-on-stable-push
  3978. # behaviour the earlier `not archive.subtask_id` guard provided.
  3979. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  3980. archive.subtask_id = effective_subtask_id
  3981. # #1403 follow-up: VP-queue archives are created with
  3982. # printer_id=None at queue-add time (we don't know which
  3983. # printer will run the job yet). When the print actually
  3984. # starts on a specific printer the expected-archive lookup
  3985. # used to skip this assignment, leaving printer_id=None
  3986. # forever — which then disables the "Scan for timelapse"
  3987. # button in ArchivesPage (gated on !archive.printer_id).
  3988. if archive.printer_id != printer_id:
  3989. archive.printer_id = printer_id
  3990. await db.commit()
  3991. # Track as active print
  3992. _active_prints[(printer_id, archive.filename)] = archive.id
  3993. if subtask_name:
  3994. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  3995. # Start timelapse session if external camera is enabled (#1353).
  3996. # Queue / VP-dispatched prints land here in the expected-archive
  3997. # branch and used to skip start_session entirely — frames were
  3998. # never captured and the post-print stitch silently returned None.
  3999. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4000. # Inject ams_mapping into usage tracker session — the session was created
  4001. # before expected-print promotion, so it may have ams_mapping=None when
  4002. # the MQTT request topic subscription failed (common on P1S/A1).
  4003. _stored_map = _print_ams_mappings.get(expected_archive_id)
  4004. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  4005. if _stored_map or _stored_plate_id is not None:
  4006. try:
  4007. from backend.app.services.usage_tracker import _active_sessions
  4008. _ut_session = _active_sessions.get(printer_id)
  4009. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4010. _ut_session.ams_mapping = _stored_map
  4011. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4012. # plate_id injection covers direct-Print of plate N of a multi-plate
  4013. # 3MF — queue prints already capture it via the on_print_start queue
  4014. # lookup, but direct-Print never goes through the queue (#1697).
  4015. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4016. _ut_session.plate_id = _stored_plate_id
  4017. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4018. except Exception:
  4019. pass
  4020. # Set up energy tracking (#941: persist start on archive row)
  4021. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4022. await ws_manager.send_archive_updated(
  4023. {
  4024. "id": archive.id,
  4025. "status": "printing",
  4026. }
  4027. )
  4028. # Send notification with archive data (reprint/scheduled)
  4029. if not notification_sent:
  4030. # Use archive's created_by_id; fall back to the creator registered via
  4031. # register_expected_print (handles library-file-based queue items where
  4032. # the freshly-created archive has no created_by_id yet).
  4033. # Pop ALL matching keys so no stale entries remain in the dict.
  4034. fallback_creator = None
  4035. for key in expected_keys:
  4036. popped = _expected_print_creators.pop(key, None)
  4037. if fallback_creator is None:
  4038. fallback_creator = popped
  4039. archive_data = {
  4040. "print_time_seconds": archive.print_time_seconds,
  4041. "created_by_id": archive.created_by_id or fallback_creator,
  4042. }
  4043. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4044. # Extract printable objects from the archived 3MF file
  4045. _load_objects_from_archive(archive, printer_id, logger)
  4046. # Store Spoolman tracking data for per-filament usage reporting
  4047. try:
  4048. await _store_spoolman_print_data(
  4049. printer_id,
  4050. archive.id,
  4051. archive.file_path,
  4052. db,
  4053. printer_manager,
  4054. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4055. plate_id=_get_start_plate_id(archive.id),
  4056. )
  4057. except Exception as e:
  4058. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4059. # Capture timelapse file baseline for snapshot-diff on completion
  4060. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4061. # hit this branch — without the baseline the completion-time scan
  4062. # falls into its "take baseline now" fallback, which snapshots
  4063. # AFTER the new MP4 already exists and never matches a diff
  4064. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4065. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4066. return # Skip creating a new archive
  4067. # Check if there's already a "printing" archive for this printer/file
  4068. # This prevents duplicates when backend restarts during an active print
  4069. from backend.app.models.archive import PrintArchive
  4070. existing_archive: PrintArchive | None = None
  4071. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4072. # across a backend restart for the same print, so this is the most
  4073. # reliable way to reattach. We also accept a previously stale-cancelled
  4074. # archive here so users upgrading mid-print get revived when the row
  4075. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  4076. if subtask_id:
  4077. by_id = await db.execute(
  4078. select(PrintArchive)
  4079. .where(PrintArchive.printer_id == printer_id)
  4080. .where(PrintArchive.subtask_id == subtask_id)
  4081. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  4082. .order_by(PrintArchive.created_at.desc())
  4083. .limit(1)
  4084. )
  4085. candidate = by_id.scalar_one_or_none()
  4086. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  4087. existing_archive = candidate
  4088. # Fallback match: name-based lookup. Kept as-is for prints whose
  4089. # subtask_id is missing ("0" / local / non-cloud prints).
  4090. if existing_archive is None:
  4091. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4092. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4093. # A print started from the printer's screen names its file in full,
  4094. # so the forms above double its extension. The file itself is the
  4095. # one exact match, and nothing looser is added (#3009).
  4096. if _subtask_is_the_file(subtask_name, filename):
  4097. archive_filenames.append(subtask_name)
  4098. existing = await db.execute(
  4099. select(PrintArchive)
  4100. .where(PrintArchive.printer_id == printer_id)
  4101. .where(PrintArchive.status == "printing")
  4102. .where(
  4103. or_(
  4104. PrintArchive.print_name == check_name,
  4105. PrintArchive.filename.in_(archive_filenames),
  4106. )
  4107. )
  4108. .order_by(PrintArchive.created_at.desc())
  4109. .limit(1)
  4110. )
  4111. existing_archive = existing.scalar_one_or_none()
  4112. if existing_archive:
  4113. # subtask_id match → always resume, regardless of age. Same print,
  4114. # just a backend restart. Revive if it was previously stale-cancelled.
  4115. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4116. if subtask_match:
  4117. if existing_archive.status == "cancelled":
  4118. logger.warning(
  4119. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  4120. existing_archive.id,
  4121. subtask_id,
  4122. )
  4123. existing_archive.status = "printing"
  4124. existing_archive.failure_reason = None
  4125. await db.commit()
  4126. else:
  4127. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4128. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4129. if existing_archive.energy_start_kwh is None:
  4130. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4131. if not notification_sent:
  4132. archive_data = {
  4133. "print_time_seconds": existing_archive.print_time_seconds,
  4134. "created_by_id": existing_archive.created_by_id,
  4135. }
  4136. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4137. _load_objects_from_archive(existing_archive, printer_id, logger)
  4138. return
  4139. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4140. # stale from the printer's *current* progress, not wall-clock age.
  4141. # A genuinely long print used to trip a blind 4h cutoff and have its
  4142. # live archive cancelled + duplicated on every backend restart
  4143. # (#1485). If the printer reports real progress, this name-matched
  4144. # 'printing' archive IS that ongoing print — resume it whatever its
  4145. # age. Only treat it as a stale leftover when the printer clearly
  4146. # shows a different, freshly-started print: near-0% progress on an
  4147. # archive far too old to still be at 0%. Unknown progress (printer
  4148. # not connected) never cancels — resuming is the safe default.
  4149. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4150. live_status = printer_manager.get_status(printer_id)
  4151. live_progress = getattr(live_status, "progress", None) if live_status else None
  4152. looks_stale = (
  4153. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4154. )
  4155. if looks_stale:
  4156. logger.warning(
  4157. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  4158. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  4159. )
  4160. existing_archive.status = "cancelled"
  4161. # Canonical key, not a sentence (issue #2974). "No status update
  4162. # received" is what both stale paths actually observed; which of
  4163. # the two it was is already carried by ``status`` -- cancelled
  4164. # here, the reconciled outcome at the reconnect site -- so one
  4165. # key loses no information and gives the Statistics breakdown a
  4166. # single bucket instead of two untranslatable prose strings.
  4167. existing_archive.failure_reason = "noStatusUpdate"
  4168. await db.commit()
  4169. # Fall through to create new archive (don't return)
  4170. else:
  4171. logger.info(
  4172. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4173. )
  4174. # Track this as the active print
  4175. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4176. # Attach subtask_id retroactively so future restarts can resume.
  4177. # Compare for inequality (not "is empty") to also pick up reprint
  4178. # dispatches that mint a fresh id — see #1807 for the bogus
  4179. # "Print Stopped" the strict-empty guard caused on reconnect.
  4180. if subtask_id and existing_archive.subtask_id != subtask_id:
  4181. existing_archive.subtask_id = subtask_id
  4182. await db.commit()
  4183. # Also set up energy tracking if not already tracked (#941: persisted column)
  4184. if existing_archive.energy_start_kwh is None:
  4185. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4186. # Send notification with archive data (existing archive)
  4187. if not notification_sent:
  4188. archive_data = {
  4189. "print_time_seconds": existing_archive.print_time_seconds,
  4190. "created_by_id": existing_archive.created_by_id,
  4191. }
  4192. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4193. # Extract printable objects from the archived 3MF file
  4194. _load_objects_from_archive(existing_archive, printer_id, logger)
  4195. return
  4196. # Build list of possible 3MF filenames to try
  4197. possible_names = []
  4198. # Bambu printers typically store files as "Name.gcode.3mf"
  4199. # The subtask_name is usually the best source for the filename
  4200. if subtask_name:
  4201. if _subtask_is_the_file(subtask_name, filename):
  4202. # A print started from the printer's own screen reports the
  4203. # file's full name, extension included. That is the file, so
  4204. # no extension is appended to it (#3009).
  4205. possible_names.append(subtask_name)
  4206. else:
  4207. # Try common Bambu naming patterns
  4208. possible_names.append(f"{subtask_name}.gcode.3mf")
  4209. possible_names.append(f"{subtask_name}.3mf")
  4210. # Try original filename with .3mf extension
  4211. if filename:
  4212. # Extract just the filename part, not the full path
  4213. fname = filename.split("/")[-1] if "/" in filename else filename
  4214. if fname.endswith(".3mf"):
  4215. possible_names.append(fname)
  4216. elif fname.endswith(".gcode"):
  4217. base = fname.rsplit(".", 1)[0]
  4218. possible_names.append(f"{base}.gcode.3mf")
  4219. possible_names.append(f"{base}.3mf")
  4220. else:
  4221. possible_names.append(f"{fname}.gcode.3mf")
  4222. possible_names.append(f"{fname}.3mf")
  4223. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4224. space_variants = []
  4225. for name in possible_names:
  4226. if " " in name:
  4227. space_variants.append(name.replace(" ", "_"))
  4228. possible_names.extend(space_variants)
  4229. # Remove duplicates while preserving order
  4230. seen = set()
  4231. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4232. logger.info("Trying filenames: %s", possible_names)
  4233. # Release the pooled DB connection before the 3MF FTP download. Reaching
  4234. # here means none of the expected-/existing-archive write branches ran
  4235. # (they all return earlier) — only SELECTs have executed on this path, so
  4236. # this commit persists nothing; it ends the read transaction so the
  4237. # connection returns to the pool during the download. That download tries
  4238. # up to five remote paths per candidate filename with retry/backoff and
  4239. # can run for minutes under FTP contention; holding the session across it
  4240. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  4241. # work runs during the download — the new-archive writes below re-acquire
  4242. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  4243. await db.commit()
  4244. # Try to find and download the 3MF file
  4245. temp_path = None
  4246. downloaded_filename = None
  4247. # Cache check: cover endpoint may have already pulled this 3MF during
  4248. # the print (frontend opens the card and shows the thumbnail) — reuse
  4249. # that file instead of re-downloading 36MB over the same FTP link that
  4250. # just served it (#972). The cache keys on a normalized filename so
  4251. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  4252. for try_filename in possible_names:
  4253. if not try_filename.endswith(".3mf"):
  4254. continue
  4255. cached = get_cached_3mf(printer_id, try_filename)
  4256. if cached:
  4257. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  4258. temp_path = cached
  4259. downloaded_filename = try_filename
  4260. break
  4261. # Does this printer keep the sliced file somewhere FTPS can reach? On
  4262. # H2-series and P2S the answer is routinely no — the file stays on
  4263. # internal eMMC and port 990 only ever serves external storage — and
  4264. # then the whole sweep below (six filenames x five directories x four
  4265. # retries, then the directory walk) is ~110 connections that cannot
  4266. # succeed. Skip it and say why (#2780).
  4267. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  4268. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  4269. # running rather than because the file is somewhere unreachable. The
  4270. # distinction is the whole of #2957: one is permanent, the other clears
  4271. # in minutes with the file still sitting on the printer.
  4272. blocked_by_ftps_cooloff = False
  4273. # Set when a probe reached the printer and still came back without the
  4274. # file -- a timeout mid-transfer, a refused connection, anything that is
  4275. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  4276. # caught by name below, so a file that genuinely is not on the card
  4277. # leaves this False and schedules nothing. Anything else means the
  4278. # transfer, not the file, is what failed, and that does not last (#3063).
  4279. ftp_transfer_failed = False
  4280. # The print's name, for a fallback archive whose `subtask_name` the
  4281. # plate guard below had to disown. Display only, and deliberately kept
  4282. # apart from `subtask_name`: that variable is what every file lookup
  4283. # here is built from, and once a name has been shown to fetch another
  4284. # plate's 3MF it must not key `_active_prints` either, or the cover
  4285. # endpoint hands the same contradicted file to
  4286. # `_recover_fallback_archive` and fills the row in with it (#3126).
  4287. display_name_after_plate_reject: str | None = None
  4288. # Get FTP retry settings
  4289. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  4290. # ...but "the printer put it on eMMC" is where it went, not whether we
  4291. # can read it. An H2D with a card in mirrors the job to /cache and
  4292. # serves it happily, and skipping on the URL alone cost that reporter
  4293. # every archive for two days (#2856). So ask the printer instead of
  4294. # guessing: the dispatch named the exact file, which is one connection
  4295. # walking five paths rather than the sweep's ~110. Only when the probe
  4296. # comes back empty does the verdict's reason stand.
  4297. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  4298. if ftps_handshake_blocked(printer.ip_address):
  4299. # Deliberately NOT recorded as a cool-off give-up. This branch
  4300. # only runs on an unreachable verdict, and that verdict is the
  4301. # honest, permanent reason the archive is empty — the probe was
  4302. # a long shot on top of it. Blaming the cool-off here would
  4303. # schedule a retry for a file sitting on internal eMMC, which is
  4304. # the sweep #2780 removed (#2957).
  4305. logger.debug(
  4306. "Not probing for %s on printer %s: its file service is not answering over TLS",
  4307. storage.probe_filename,
  4308. printer_id,
  4309. )
  4310. else:
  4311. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  4312. probe_path.parent.mkdir(parents=True, exist_ok=True)
  4313. try:
  4314. probe_hit = await download_file_try_paths_async(
  4315. printer.ip_address,
  4316. printer.access_code,
  4317. ftp_probe_paths(storage.probe_filename),
  4318. probe_path,
  4319. socket_timeout=ftp_timeout,
  4320. printer_model=printer.model,
  4321. )
  4322. except Exception as e:
  4323. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  4324. probe_hit = False
  4325. if probe_hit:
  4326. downloaded_filename = storage.probe_filename
  4327. temp_path = probe_path
  4328. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  4329. # Naming the path, not just the file: a printer that keeps
  4330. # uploads around for weeks can serve a same-named copy of an
  4331. # earlier slice, and without the directory in the log that
  4332. # mismatch is invisible rather than merely rare (#1820).
  4333. logger.info(
  4334. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  4335. downloaded_filename,
  4336. probe_hit,
  4337. printer_id,
  4338. storage.reason,
  4339. )
  4340. if not storage.reachable and not downloaded_filename:
  4341. # Same opening words whether or not a probe ran, because that is
  4342. # the phrase support asks people to grep for — only the tail says
  4343. # which of the two happened.
  4344. logger.info(
  4345. "Skipping the 3MF lookup for printer %s: %s — %s",
  4346. printer_id,
  4347. storage.reason,
  4348. "no copy of it on external storage either"
  4349. if storage.probe_filename
  4350. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  4351. )
  4352. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  4353. if not try_filename.endswith(".3mf"):
  4354. continue
  4355. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  4356. # printers, so try it first — deferring it to last cost #972's reporter
  4357. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  4358. # landing on the path that actually had the file.
  4359. remote_paths = [
  4360. f"/{try_filename}",
  4361. f"/cache/{try_filename}",
  4362. f"/model/{try_filename}",
  4363. f"/data/{try_filename}",
  4364. f"/data/Metadata/{try_filename}",
  4365. ]
  4366. temp_path = app_settings.archive_dir / "temp" / try_filename
  4367. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4368. for remote_path in remote_paths:
  4369. if ftps_handshake_blocked(printer.ip_address):
  4370. # The printer's FTPS service is not completing a TLS
  4371. # handshake, so it has no path we could reach — walking the
  4372. # remaining candidates only re-runs the same failure
  4373. # (#2780). Fall through to the no-3MF archive now.
  4374. #
  4375. # Remember *why*, though. This is the one give-up that is
  4376. # temporary: the cool-off clears in minutes and the file was
  4377. # on the printer the whole time. The fallback archive is
  4378. # stamped with it so a retry can be scheduled, and so the
  4379. # Archives banner stops blaming storage (#2957).
  4380. blocked_by_ftps_cooloff = True
  4381. logger.warning(
  4382. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  4383. printer_id,
  4384. )
  4385. break
  4386. logger.debug("Trying FTP download: %s", remote_path)
  4387. try:
  4388. if ftp_retry_enabled:
  4389. downloaded = await with_ftp_retry(
  4390. download_file_async,
  4391. printer.ip_address,
  4392. printer.access_code,
  4393. remote_path,
  4394. temp_path,
  4395. timeout=ftp_timeout,
  4396. socket_timeout=ftp_timeout,
  4397. printer_model=printer.model,
  4398. max_retries=ftp_retry_count,
  4399. retry_delay=ftp_retry_delay,
  4400. operation_name=f"Download 3MF from {remote_path}",
  4401. cooloff_ip=printer.ip_address,
  4402. non_retry_exceptions=(FileNotOnPrinterError,),
  4403. )
  4404. else:
  4405. downloaded = await download_file_async(
  4406. printer.ip_address,
  4407. printer.access_code,
  4408. remote_path,
  4409. temp_path,
  4410. timeout=ftp_timeout,
  4411. socket_timeout=ftp_timeout,
  4412. printer_model=printer.model,
  4413. )
  4414. if downloaded:
  4415. downloaded_filename = try_filename
  4416. logger.info("Downloaded: %s", remote_path)
  4417. # Populate shared cache so the cover endpoint (if it
  4418. # runs next) doesn't refetch the same 36MB over FTP.
  4419. cache_3mf_download(printer_id, try_filename, temp_path)
  4420. break
  4421. # with_ftp_retry returns None once it has spent its budget,
  4422. # and download_file_async returns False on a timeout, so an
  4423. # exhausted transfer arrives here rather than as an
  4424. # exception (#3063).
  4425. ftp_transfer_failed = True
  4426. except FileNotOnPrinterError:
  4427. # 550 — file isn't at this path. Advance to next candidate
  4428. # without burning the retry budget.
  4429. logger.debug("3MF not at %s (550), trying next path", remote_path)
  4430. except Exception as e:
  4431. ftp_transfer_failed = True
  4432. logger.debug("FTP download failed for %s: %s", remote_path, e)
  4433. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  4434. break
  4435. # If still not found, try listing directories to find matching file
  4436. # Different printer models use different directory structures. Skipped
  4437. # when the printer's FTPS handshake is failing — the directory walk is
  4438. # five more connections that cannot get further than the download did.
  4439. if (
  4440. not downloaded_filename
  4441. and storage.reachable
  4442. and (filename or subtask_name)
  4443. and not ftps_handshake_blocked(printer.ip_address)
  4444. ):
  4445. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  4446. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  4447. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  4448. for search_dir in search_dirs:
  4449. if downloaded_filename:
  4450. break
  4451. try:
  4452. dir_files = await list_files_async(
  4453. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  4454. )
  4455. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  4456. if threemf_files:
  4457. logger.info(
  4458. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  4459. )
  4460. for f in dir_files:
  4461. if f.get("is_directory"):
  4462. continue
  4463. fname = f.get("name", "")
  4464. # Normalize both for comparison (spaces and underscores are equivalent)
  4465. fname_normalized = fname.lower().replace(" ", "_")
  4466. search_normalized = search_term.replace(" ", "_")
  4467. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  4468. logger.info("Found matching file in %s: %s", search_dir, fname)
  4469. temp_path = app_settings.archive_dir / "temp" / fname
  4470. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4471. remote_full_path = posixpath.join(search_dir, fname)
  4472. if ftp_retry_enabled:
  4473. downloaded = await with_ftp_retry(
  4474. download_file_async,
  4475. printer.ip_address,
  4476. printer.access_code,
  4477. remote_full_path,
  4478. temp_path,
  4479. timeout=ftp_timeout,
  4480. socket_timeout=ftp_timeout,
  4481. printer_model=printer.model,
  4482. max_retries=ftp_retry_count,
  4483. retry_delay=ftp_retry_delay,
  4484. operation_name=f"Download 3MF from {remote_full_path}",
  4485. cooloff_ip=printer.ip_address,
  4486. )
  4487. else:
  4488. downloaded = await download_file_async(
  4489. printer.ip_address,
  4490. printer.access_code,
  4491. remote_full_path,
  4492. temp_path,
  4493. timeout=ftp_timeout,
  4494. socket_timeout=ftp_timeout,
  4495. printer_model=printer.model,
  4496. )
  4497. if downloaded:
  4498. downloaded_filename = fname
  4499. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  4500. cache_3mf_download(printer_id, fname, temp_path)
  4501. break
  4502. # The listing named the file, so it is on the card;
  4503. # only the transfer failed (#3063).
  4504. ftp_transfer_failed = True
  4505. except Exception as e:
  4506. logger.debug("Failed to list %s: %s", search_dir, e)
  4507. # Validate the downloaded 3MF actually matches the plate that's running
  4508. # (#1204): subtask_name lags across consecutive plates of the same model,
  4509. # so the first FTP candidate (built from subtask_name) can land on the
  4510. # previous plate's still-resident upload. Cross-check the slice_info
  4511. # plate index against the plate parsed from gcode_file (always fresh —
  4512. # it's the field whose change triggered this callback).
  4513. if downloaded_filename and temp_path:
  4514. expected_plate = parse_plate_id(filename)
  4515. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  4516. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  4517. logger.warning(
  4518. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  4519. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  4520. downloaded_filename,
  4521. actual_plate,
  4522. expected_plate,
  4523. subtask_name,
  4524. )
  4525. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  4526. retry_succeeded = False
  4527. if corrected_subtask and corrected_subtask != subtask_name:
  4528. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  4529. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  4530. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  4531. for remote_path in (
  4532. f"/{try_filename}",
  4533. f"/cache/{try_filename}",
  4534. f"/model/{try_filename}",
  4535. f"/data/{try_filename}",
  4536. f"/data/Metadata/{try_filename}",
  4537. ):
  4538. try:
  4539. if ftp_retry_enabled:
  4540. downloaded = await with_ftp_retry(
  4541. download_file_async,
  4542. printer.ip_address,
  4543. printer.access_code,
  4544. remote_path,
  4545. retry_temp_path,
  4546. timeout=ftp_timeout,
  4547. socket_timeout=ftp_timeout,
  4548. printer_model=printer.model,
  4549. max_retries=ftp_retry_count,
  4550. retry_delay=ftp_retry_delay,
  4551. operation_name=f"Re-download 3MF from {remote_path}",
  4552. cooloff_ip=printer.ip_address,
  4553. non_retry_exceptions=(FileNotOnPrinterError,),
  4554. )
  4555. else:
  4556. downloaded = await download_file_async(
  4557. printer.ip_address,
  4558. printer.access_code,
  4559. remote_path,
  4560. retry_temp_path,
  4561. timeout=ftp_timeout,
  4562. socket_timeout=ftp_timeout,
  4563. printer_model=printer.model,
  4564. )
  4565. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  4566. logger.info(
  4567. "[CALLBACK] Re-download succeeded with corrected name %s "
  4568. "(plate %s) — replacing wrong file",
  4569. try_filename,
  4570. expected_plate,
  4571. )
  4572. try:
  4573. temp_path.unlink(missing_ok=True)
  4574. except OSError:
  4575. pass
  4576. temp_path = retry_temp_path
  4577. downloaded_filename = try_filename
  4578. subtask_name = corrected_subtask
  4579. cache_3mf_download(printer_id, try_filename, temp_path)
  4580. retry_succeeded = True
  4581. break
  4582. elif downloaded:
  4583. # Wrong plate again — discard and keep trying
  4584. try:
  4585. retry_temp_path.unlink(missing_ok=True)
  4586. except OSError:
  4587. pass
  4588. except FileNotOnPrinterError:
  4589. continue
  4590. except Exception as e:
  4591. logger.debug("Re-download failed for %s: %s", remote_path, e)
  4592. if retry_succeeded:
  4593. break
  4594. # If the retry didn't find a matching file, drop the wrong 3MF
  4595. # so the no-3MF fallback below creates an archive whose name
  4596. # at least reflects the right plate.
  4597. if not retry_succeeded:
  4598. logger.warning(
  4599. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  4600. expected_plate,
  4601. )
  4602. try:
  4603. temp_path.unlink(missing_ok=True)
  4604. except OSError:
  4605. pass
  4606. temp_path = None
  4607. downloaded_filename = None
  4608. # Whatever the sweep's transport did earlier, it is not why
  4609. # this archive ends up empty: a 3MF downloaded fine, it was
  4610. # just the wrong plate. Retrying would re-fetch that same
  4611. # contradicted file under the same stale names and hand it
  4612. # to _recover_fallback_archive, which checks that a
  4613. # candidate is a readable 3MF but not which plate it is --
  4614. # so the row would be filled in with another plate's
  4615. # filament and cost, the exact swap #2957 removed (#3063).
  4616. ftp_transfer_failed = False
  4617. # Disown the name for *lookups*: it has just been shown to
  4618. # fetch another plate's 3MF, and it keys `_active_prints`
  4619. # below, where the cover endpoint's own download of that
  4620. # same name would find this archive and fill it in with the
  4621. # file we are discarding here.
  4622. #
  4623. # Keep it for the *title*, which is a separate question.
  4624. # ``swap_plate_suffix`` returns None both for a name that
  4625. # carries no "- Plate N" / "_plate_N" suffix and for no
  4626. # name at all, and those are not the same situation: a name
  4627. # without a suffix holds no stale plate number to be wrong
  4628. # about. Blanking both uses at once dropped the project
  4629. # name too, and the row fell through to the gcode_file path
  4630. # titled "plate_1" though the real name was in hand.
  4631. # #1204's own premise is consecutive plates *of the same
  4632. # model*, so the project part is right either way (#3126).
  4633. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  4634. subtask_name = corrected_subtask or ""
  4635. if not downloaded_filename or not temp_path:
  4636. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  4637. # Create a fallback archive without 3MF data so the print is still tracked
  4638. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  4639. try:
  4640. from backend.app.models.archive import PrintArchive
  4641. # Why the card is empty. The two temporary causes outrank the
  4642. # storage verdict because they say the sweep never got a fair
  4643. # answer: a cool-off skipped it at the transport, and a failed
  4644. # transfer reached the printer but never finished. Either way
  4645. # the file is still on the card, so reporting where the printer
  4646. # files its jobs would describe a setting that is not the
  4647. # problem (#2957, #3063).
  4648. if blocked_by_ftps_cooloff:
  4649. no_3mf_reason = REASON_FTPS_COOLOFF
  4650. elif storage.reachable and ftp_transfer_failed:
  4651. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  4652. else:
  4653. no_3mf_reason = storage.reason
  4654. # Derive print name from subtask_name or filename. The
  4655. # plate guard's disowned name comes second: it is a real name
  4656. # for a real print, and only the gcode_file path is left
  4657. # otherwise -- which titles the row "plate_1" (#3126).
  4658. print_name = subtask_name or display_name_after_plate_reject or filename
  4659. if print_name:
  4660. # Clean up the name (remove extensions, path parts)
  4661. print_name = print_name.split("/")[-1]
  4662. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  4663. else:
  4664. print_name = "Unknown Print"
  4665. # Recover estimated print time from MQTT (best-effort for notifications)
  4666. fallback_print_time = None
  4667. mqtt_remaining = data.get("remaining_time")
  4668. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  4669. fallback_print_time = int(mqtt_remaining)
  4670. if fallback_print_time is None:
  4671. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  4672. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  4673. fallback_print_time = int(mc_remaining * 60)
  4674. # Best-effort filament metadata from MQTT — see
  4675. # _extract_filament_data_from_mqtt. Without this the fallback
  4676. # archive's filament fields stayed NULL even though the AMS
  4677. # state at print start was sitting right there in `data`.
  4678. # The slicer's ams_mapping (when present) narrows the result
  4679. # to slots actually used by the print (#1533).
  4680. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  4681. # Create minimal archive entry
  4682. fallback_archive = PrintArchive(
  4683. printer_id=printer_id,
  4684. filename=filename or f"{print_name}.3mf",
  4685. file_path="", # Empty - no 3MF file available
  4686. file_size=0,
  4687. print_name=print_name,
  4688. print_time_seconds=fallback_print_time,
  4689. status="printing",
  4690. started_at=datetime.now(timezone.utc),
  4691. subtask_id=subtask_id,
  4692. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  4693. filament_type=mqtt_filament_meta.get("filament_type"),
  4694. filament_color=mqtt_filament_meta.get("filament_color"),
  4695. extra_data={
  4696. "no_3mf_available": True,
  4697. # Why the card is empty, when we know -- see above. The
  4698. # banner reads this to stop telling H2/P2 owners to
  4699. # switch on a setting that is already on and would not
  4700. # have helped (#2780).
  4701. "no_3mf_reason": no_3mf_reason,
  4702. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  4703. "_print_data": data,
  4704. },
  4705. )
  4706. db.add(fallback_archive)
  4707. await db.commit()
  4708. await db.refresh(fallback_archive)
  4709. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  4710. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  4711. # Track as active print
  4712. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  4713. if filename:
  4714. _active_prints[(printer_id, filename)] = fallback_archive.id
  4715. if subtask_name:
  4716. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  4717. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  4718. # Record starting energy if smart plug available (#941: persisted column)
  4719. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  4720. # Send WebSocket notification
  4721. await ws_manager.send_archive_created(
  4722. {
  4723. "id": fallback_archive.id,
  4724. "printer_id": fallback_archive.printer_id,
  4725. "filename": fallback_archive.filename,
  4726. "print_name": fallback_archive.print_name,
  4727. "status": fallback_archive.status,
  4728. }
  4729. )
  4730. # MQTT relay - publish archive created
  4731. try:
  4732. await mqtt_relay.on_archive_created(
  4733. archive_id=fallback_archive.id,
  4734. print_name=fallback_archive.print_name,
  4735. printer_name=printer.name,
  4736. status=fallback_archive.status,
  4737. )
  4738. except Exception:
  4739. pass # Don't fail if MQTT fails
  4740. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  4741. try:
  4742. await _store_spoolman_print_data(
  4743. printer_id,
  4744. fallback_archive.id,
  4745. fallback_archive.file_path,
  4746. db,
  4747. printer_manager,
  4748. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  4749. plate_id=_get_start_plate_id(fallback_archive.id),
  4750. )
  4751. except Exception as e:
  4752. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  4753. # Both temporary give-ups are worth coming back for, and for
  4754. # the same reason: the file is on the printer and the last look
  4755. # failed at the transport rather than finding nothing. One waits
  4756. # out the handshake block (#2957), the other waits for the
  4757. # printer to stop being busy (#3063). Deliberately not scheduled
  4758. # for a storage verdict: a file on internal eMMC will not appear
  4759. # at any FTPS path however long we wait, and retrying it is
  4760. # exactly the sweep #2780 removed.
  4761. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  4762. # `possible_names`, not the raw MQTT strings: it is the exact
  4763. # list this flow just tried, already stripped of any path
  4764. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  4765. # some firmware) and deduped.
  4766. _schedule_fallback_3mf_retry(
  4767. printer_id=printer_id,
  4768. archive_id=fallback_archive.id,
  4769. filenames=list(possible_names),
  4770. reason=no_3mf_reason,
  4771. )
  4772. # Send notification without archive data (file not found)
  4773. if not notification_sent:
  4774. await _send_print_start_notification(printer_id, data, logger=logger)
  4775. # The same baseline the other two on_print_start branches take
  4776. # (#2704), and last for the same reason they are: it lists the
  4777. # printer's timelapse directory, so a slow card must not delay
  4778. # the _active_prints registration, the energy reading, the
  4779. # archive-created event or the start notification above it.
  4780. #
  4781. # This branch never took one, so every no-3MF archive reached
  4782. # completion with no baseline in memory and none on the row, and
  4783. # the completion scan fell into its "snapshot now" fallback --
  4784. # which runs after the printer has written the video, so the new
  4785. # file landed inside the baseline and no diff ever matched
  4786. # (#2957 follow-up).
  4787. #
  4788. # Skipped when the FTPS cool-off is what produced this fallback:
  4789. # the listing needs the same connection that just failed, so it
  4790. # could only record that the card was unreadable. The scan
  4791. # handles that case by refusing to choose between candidates.
  4792. if not blocked_by_ftps_cooloff:
  4793. await _capture_timelapse_baseline_at_start(
  4794. printer, printer_id, logger, archive_id=fallback_archive.id
  4795. )
  4796. return
  4797. except Exception as e:
  4798. logger.error("Failed to create fallback archive: %s", e)
  4799. # Send notification without archive data (file not found)
  4800. if not notification_sent:
  4801. await _send_print_start_notification(printer_id, data, logger=logger)
  4802. return
  4803. try:
  4804. # Archive the file with status "printing"
  4805. service = ArchiveService(db)
  4806. archive = await service.archive_print(
  4807. printer_id=printer_id,
  4808. source_file=temp_path,
  4809. print_data={**data, "status": "printing"},
  4810. subtask_id=subtask_id,
  4811. )
  4812. if archive:
  4813. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  4814. # Set on the row rather than passed to archive_print, which also
  4815. # serves the queue dispatcher — there the queue item decides.
  4816. # Guarded because this branch has no ``except``: an unhandled
  4817. # write error would take the _active_prints registration, the
  4818. # start notification, the energy reading and the timelapse
  4819. # baseline below it with it, and a missing prompt is by far the
  4820. # cheaper failure.
  4821. archive_id = archive.id
  4822. try:
  4823. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  4824. archive.confirm_requested = True
  4825. await db.commit()
  4826. except Exception as e:
  4827. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  4828. # The rollback expires every loaded object, and on an async
  4829. # session reading one afterwards raises instead of
  4830. # reloading, so the two this branch goes on to use are
  4831. # fetched again. The archive itself was committed by
  4832. # archive_print; only the flag is lost.
  4833. try:
  4834. await db.rollback()
  4835. archive = await db.get(PrintArchive, archive_id)
  4836. printer = await db.get(Printer, printer_id)
  4837. except Exception as reload_error:
  4838. logger.warning(
  4839. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  4840. )
  4841. # Track this active print (use both original filename and downloaded filename)
  4842. _active_prints[(printer_id, downloaded_filename)] = archive.id
  4843. if filename and filename != downloaded_filename:
  4844. _active_prints[(printer_id, filename)] = archive.id
  4845. if subtask_name:
  4846. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  4847. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  4848. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4849. # Record starting energy from smart plug if available (#941: persisted column)
  4850. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  4851. await ws_manager.send_archive_created(
  4852. {
  4853. "id": archive.id,
  4854. "printer_id": archive.printer_id,
  4855. "filename": archive.filename,
  4856. "print_name": archive.print_name,
  4857. "status": archive.status,
  4858. }
  4859. )
  4860. # MQTT relay - publish archive created
  4861. try:
  4862. await mqtt_relay.on_archive_created(
  4863. archive_id=archive.id,
  4864. print_name=archive.print_name,
  4865. printer_name=printer.name,
  4866. status=archive.status,
  4867. )
  4868. except Exception:
  4869. pass # Don't fail if MQTT fails
  4870. # Send notification with archive data (new archive created)
  4871. if not notification_sent:
  4872. archive_data = {
  4873. "print_time_seconds": archive.print_time_seconds,
  4874. "created_by_id": archive.created_by_id,
  4875. }
  4876. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4877. # Extract printable objects for skip object functionality
  4878. try:
  4879. from backend.app.services.archive import extract_printable_objects_from_3mf
  4880. client = printer_manager.get_client(printer_id)
  4881. if client:
  4882. with open(temp_path, "rb") as f:
  4883. threemf_data = f.read()
  4884. # Extract with positions for UI overlay, scoped to the
  4885. # plate that is printing — an all-plates 3MF carries
  4886. # every plate's objects (#2522).
  4887. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  4888. threemf_data,
  4889. plate_number=resolve_plate_id(client.state),
  4890. include_positions=True,
  4891. )
  4892. if printable_objects:
  4893. # Store objects in printer state
  4894. client.state.printable_objects = printable_objects
  4895. client.state.printable_objects_bbox_all = bbox_all
  4896. client.state.skipped_objects = [] # Reset skipped objects for new print
  4897. logger.info(
  4898. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  4899. )
  4900. except Exception as e:
  4901. logger.debug("Failed to extract printable objects: %s", e)
  4902. # Store Spoolman tracking data for per-filament usage reporting
  4903. try:
  4904. await _store_spoolman_print_data(
  4905. printer_id,
  4906. archive.id,
  4907. archive.file_path,
  4908. db,
  4909. printer_manager,
  4910. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4911. plate_id=_get_start_plate_id(archive.id),
  4912. )
  4913. except Exception as e:
  4914. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4915. # Capture timelapse file baseline for snapshot-diff on completion
  4916. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4917. finally:
  4918. # Keep temp_path around until print completes so the cover endpoint
  4919. # can reuse it (#972). Cache eviction in on_print_complete deletes
  4920. # the file. If the cache entry was evicted early (file vanished),
  4921. # clean up any stragglers here to avoid leaking disk on retries.
  4922. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  4923. if temp_path and temp_path.exists() and cached_now != temp_path:
  4924. temp_path.unlink()
  4925. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  4926. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  4927. # tests can shrink them without waiting out real delays.
  4928. #
  4929. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  4930. # looking. Across 247 support bundles the attempt that found the video was #1
  4931. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  4932. # decaying one, which is the signature of a budget that expires while files are
  4933. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  4934. # prints make big videos and the printer writes them after the print ends, so
  4935. # the poll now runs for minutes and costs one FTP LIST per round.
  4936. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  4937. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  4938. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  4939. def _timelapse_scan_max_attempts() -> int:
  4940. """Round cap for the poll, derived from the wall-clock budget.
  4941. The deadline alone is not a sufficient bound: it assumes each round really
  4942. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  4943. and an FTP list that fails immediately would otherwise spin against the
  4944. printer at full speed for the whole window. Whichever bound is reached
  4945. first ends the poll.
  4946. """
  4947. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  4948. # A zero interval makes the wall-clock budget meaningless; fall back to
  4949. # the round count the production interval would have given.
  4950. return 32
  4951. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  4952. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  4953. """Video filenames already attached to some other archive of this printer.
  4954. Used to disambiguate when more than one file is new since the baseline —
  4955. which happens when a previous print's video landed after this print's
  4956. baseline was taken. Ordering the candidates would be the obvious fix and is
  4957. the wrong one: it can only be done on mtime or on the filename timestamp,
  4958. both of which come from the printer's own clock, and a LAN-only printer
  4959. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  4960. ``attach_timelapse`` saves the video into the archive directory under the
  4961. printer's original filename, and the later MP4 conversion keeps the stem,
  4962. so the stem of ``timelapse_path`` recovers what was claimed.
  4963. """
  4964. from backend.app.models.archive import PrintArchive
  4965. rows = await db.execute(
  4966. select(PrintArchive.timelapse_path).where(
  4967. PrintArchive.printer_id == printer_id,
  4968. PrintArchive.id != exclude_archive_id,
  4969. PrintArchive.timelapse_path.is_not(None),
  4970. )
  4971. )
  4972. return {Path(p).stem for p in rows.scalars().all() if p}
  4973. def _timelapse_listing_is_trustworthy(printer) -> bool:
  4974. """Whether an *empty* timelapse listing for *printer* can be believed.
  4975. ``list_files_async`` answers ``[]`` when its connect fails rather than
  4976. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  4977. from one holding no videos. Everywhere that only wants to know "is there a
  4978. video yet" the difference does not matter — both mean "not yet, retry".
  4979. It matters where an empty listing is recorded as a *baseline*. Recording
  4980. "the card held nothing" for a card that was never read means every video on
  4981. it counts as new once the cool-off expires, and the completion scan then
  4982. attaches a stale video to this print and deletes it from the printer
  4983. (#2957 follow-up). Those two callers ask this first.
  4984. """
  4985. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  4986. ip_address = getattr(printer, "ip_address", None)
  4987. if not ip_address:
  4988. return True
  4989. return not ftps_handshake_blocked(ip_address)
  4990. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  4991. """List video files from printer's timelapse directory.
  4992. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  4993. Returns (video_files, found_path) where video_files is a list of file dicts
  4994. and found_path is the directory where they were found, or ([], None).
  4995. An empty return does not distinguish "no videos" from "could not read the
  4996. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  4997. baseline callers consult before believing one.
  4998. """
  4999. from backend.app.services.bambu_ftp import list_files_async
  5000. logger = logging.getLogger(__name__)
  5001. # No card in the slot means no /timelapse to walk — four connections that
  5002. # can only fail, on a path whose failures are swallowed and so would go on
  5003. # costing time silently forever (#2780).
  5004. #
  5005. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5006. # inside the loop's own try/except, so a caller that passed something
  5007. # unexpected used to get an empty listing rather than an exception. Keep
  5008. # that, instead of making this gate the first thing that can raise here.
  5009. printer_id = getattr(printer, "id", None)
  5010. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5011. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5012. return [], None
  5013. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  5014. try:
  5015. found_files = await list_files_async(
  5016. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5017. )
  5018. if found_files:
  5019. video_files = [
  5020. f
  5021. for f in found_files
  5022. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5023. ]
  5024. if video_files:
  5025. return video_files, timelapse_path
  5026. except Exception as e:
  5027. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5028. continue
  5029. return [], None
  5030. async def _capture_timelapse_baseline_at_start(
  5031. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5032. ) -> None:
  5033. """Snapshot the printer's timelapse directory at print start so the
  5034. completion-time scan can pick the new file by set-difference.
  5035. Must be called from every on_print_start path that proceeds to a real
  5036. print — both the new-archive branch and the expected-archive branch (which
  5037. queue / VP-dispatched prints take). Without a baseline,
  5038. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5039. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5040. so the new file ends up in the "baseline" set and no diff ever matches.
  5041. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  5042. unreliable — the snapshot-diff approach sidesteps that entirely.
  5043. When ``archive_id`` is known the baseline is also written to the archive
  5044. row, so it survives a restart and the manual "Scan for Timelapse" button
  5045. can run the same diff instead of falling back to clock-based matching
  5046. (#2704). Only baselines taken at print start are persisted — one taken at
  5047. completion already contains the new video and would poison a later scan.
  5048. """
  5049. names: set[str] | None = None
  5050. try:
  5051. if not _timelapse_listing_is_trustworthy(printer):
  5052. # Recorded anyway, deliberately. An empty baseline taken off a card
  5053. # we could not read is not authoritative, but it is still the right
  5054. # *default*: Bambuddy deletes each video from the printer once it is
  5055. # attached, so the usual card holds exactly one video at completion
  5056. # and an empty baseline resolves it correctly. Persisting NULL
  5057. # instead would send completion to take its own snapshot, by which
  5058. # point this print's video is on the card and would be swallowed by
  5059. # it. The ambiguity is handled where it actually bites — see
  5060. # ``require_unambiguous`` in the scan (#2957 follow-up).
  5061. logger.warning(
  5062. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  5063. "handshake cool-off, so the card could not be read — treating it as empty",
  5064. printer_id,
  5065. )
  5066. baseline_files, _ = await _list_timelapse_videos(printer)
  5067. names = {f.get("name", "") for f in baseline_files}
  5068. _timelapse_baselines[printer_id] = names
  5069. logger.info(
  5070. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  5071. len(names),
  5072. printer_id,
  5073. )
  5074. except Exception as e:
  5075. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  5076. if archive_id is None:
  5077. return
  5078. try:
  5079. async with async_session() as db:
  5080. from backend.app.models.archive import PrintArchive
  5081. archive = await db.get(PrintArchive, archive_id)
  5082. if archive is not None:
  5083. # Written even when the listing failed, and then as NULL. A
  5084. # reprint reuses the archive row, so leaving the previous run's
  5085. # baseline in place would have the scan diff this print against
  5086. # the state of the printer before the *last* one — and a stale
  5087. # baseline reads as authoritative, where NULL correctly falls
  5088. # back to a fresh snapshot.
  5089. archive.timelapse_baseline = sorted(names) if names is not None else None
  5090. await db.commit()
  5091. except Exception as e:
  5092. # In-memory baseline still covers the normal completion path.
  5093. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  5094. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  5095. """Poll the printer for this print's timelapse and attach it.
  5096. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  5097. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  5098. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  5099. (#2704). Comparing the current listing against the set of filenames that
  5100. existed when the print started needs no clock at all, because the printer
  5101. writes the video only once the print has ended.
  5102. Baseline precedence: the caller's in-memory set, then the one persisted on
  5103. the archive at print start, then a snapshot taken now. The last of those is
  5104. a poor substitute — by completion the new video may already be on the card,
  5105. in which case it lands in the "baseline" and no diff can ever match — but it
  5106. is all that is available for a print that began before Bambuddy started.
  5107. On success the video is deleted from the printer, which keeps ``/timelapse``
  5108. down to the unclaimed files and makes the next diff unambiguous.
  5109. """
  5110. logger = logging.getLogger(__name__)
  5111. # Cleared when the baseline had to be taken off a card we could not read, so
  5112. # the attach step refuses to choose between several candidates (#2957).
  5113. baseline_trusted = True
  5114. # --- Phase 1: establish the baseline -------------------------------------
  5115. try:
  5116. async with async_session() as db:
  5117. from backend.app.models.printer import Printer
  5118. service = ArchiveService(db)
  5119. archive = await service.get_archive(archive_id)
  5120. if not archive:
  5121. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  5122. return
  5123. if archive.timelapse_path:
  5124. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  5125. return
  5126. if not archive.printer_id:
  5127. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  5128. return
  5129. if baseline_names is not None:
  5130. logger.info(
  5131. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  5132. len(baseline_names),
  5133. archive_id,
  5134. )
  5135. elif archive.timelapse_baseline is not None:
  5136. # Persisted at print start — survives a restart mid-print.
  5137. baseline_names = set(archive.timelapse_baseline)
  5138. logger.info(
  5139. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  5140. len(baseline_names),
  5141. archive_id,
  5142. )
  5143. else:
  5144. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5145. printer = result.scalar_one_or_none()
  5146. if not printer:
  5147. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  5148. return
  5149. if not _timelapse_listing_is_trustworthy(printer):
  5150. # The card is unreadable at the one moment a baseline has to
  5151. # be taken, so the empty listing below means "we never
  5152. # looked", not "these are all new". Carry on with it anyway
  5153. # — the usual card holds exactly one video, which resolves
  5154. # correctly — but stop the poll from *choosing* between
  5155. # several, which is how a stale video got attached to this
  5156. # print and then deleted off the printer (#2957 follow-up).
  5157. baseline_trusted = False
  5158. logger.warning(
  5159. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  5160. "handshake cool-off. A single new video still resolves; several will not be "
  5161. "guessed between — use Scan for Timelapse to pick one by hand",
  5162. archive_id,
  5163. archive.printer_id,
  5164. )
  5165. baseline_files, _ = await _list_timelapse_videos(printer)
  5166. baseline_names = {f.get("name", "") for f in baseline_files}
  5167. logger.info(
  5168. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  5169. len(baseline_names),
  5170. archive_id,
  5171. )
  5172. except Exception as e:
  5173. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  5174. return
  5175. # --- Phase 2: poll for a file that was not there when the print began -----
  5176. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  5177. max_attempts = _timelapse_scan_max_attempts()
  5178. seen_names: set[str] = set()
  5179. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  5180. attempt = 0
  5181. while True:
  5182. await asyncio.sleep(delay)
  5183. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  5184. attempt += 1
  5185. try:
  5186. from backend.app.models.printer import Printer
  5187. # Read phase: fetch archive + printer in a short session and release
  5188. # the pooled connection BEFORE the FTP list/download below. Holding it
  5189. # across the FTP round-trips left one connection idle-in-transaction per
  5190. # in-flight scan (issue #2572).
  5191. async with async_session() as db:
  5192. service = ArchiveService(db)
  5193. archive = await service.get_archive(archive_id)
  5194. if not archive:
  5195. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  5196. return
  5197. if archive.timelapse_path:
  5198. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  5199. return
  5200. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5201. printer = result.scalar_one_or_none()
  5202. if not printer:
  5203. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  5204. return
  5205. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  5206. # I/O phase (no DB connection held): FTP list + download.
  5207. video_files, found_path = await _list_timelapse_videos(printer)
  5208. # The poll can run for dozens of rounds, so only narrate a round
  5209. # that saw something change. Repeating the whole listing every 30 s
  5210. # would bury the one interesting line in the support bundle.
  5211. names_now = {f.get("name", "") for f in video_files}
  5212. changed = attempt == 1 or names_now != seen_names
  5213. seen_names = names_now
  5214. speak = logger.info if changed else logger.debug
  5215. if video_files:
  5216. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  5217. if changed:
  5218. for f in video_files[:5]:
  5219. logger.info("[TIMELAPSE] - %s", f.get("name"))
  5220. attached = await _attach_first_unclaimed_timelapse(
  5221. archive_id,
  5222. printer,
  5223. video_files,
  5224. baseline_names,
  5225. claimed,
  5226. attempt,
  5227. logger,
  5228. quiet=not changed,
  5229. require_unambiguous=not baseline_trusted,
  5230. )
  5231. if attached:
  5232. return
  5233. else:
  5234. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  5235. except Exception as e:
  5236. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  5237. if attempt >= max_attempts or time.monotonic() >= deadline:
  5238. break
  5239. # No name-match fallback: it compared the print name against the filename,
  5240. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  5241. # bundles it fired 159 times and matched zero times, so all it added was a
  5242. # misleading log line before giving up.
  5243. logger.warning(
  5244. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  5245. archive_id,
  5246. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  5247. )
  5248. async def _attach_first_unclaimed_timelapse(
  5249. archive_id: int,
  5250. printer,
  5251. video_files: list[dict],
  5252. baseline_names: set[str],
  5253. claimed: set[str],
  5254. attempt: int,
  5255. logger: logging.Logger,
  5256. *,
  5257. quiet: bool = False,
  5258. require_unambiguous: bool = False,
  5259. ) -> bool:
  5260. """Download and attach the one video that belongs to this print.
  5261. A candidate is any file absent from the print-start baseline. More than one
  5262. can qualify when a previous print's video landed late, after this print's
  5263. baseline was taken — those are filtered out by name, because they are
  5264. already attached to another archive. Sorting the candidates instead would
  5265. mean sorting on mtime or on the filename timestamp, both of which come from
  5266. the printer's unsynced clock.
  5267. Returns True once a video is attached. The printer's copy is deleted only
  5268. after the attach succeeds on bytes whose length matched the listing.
  5269. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  5270. already seen this exact listing — the poll runs for many rounds and only the
  5271. rounds where something changed are worth an INFO line.
  5272. """
  5273. from backend.app.services.bambu_ftp import (
  5274. delete_archived_timelapse,
  5275. download_file_bytes_async,
  5276. remote_file_settled,
  5277. )
  5278. speak = logger.debug if quiet else logger.info
  5279. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  5280. if not new_files:
  5281. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  5282. return False
  5283. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  5284. if not candidates:
  5285. speak(
  5286. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  5287. attempt,
  5288. len(new_files),
  5289. )
  5290. return False
  5291. if len(candidates) > 1:
  5292. if require_unambiguous:
  5293. # The baseline is not evidence -- it was taken off a card that could
  5294. # not be read -- so "new since the baseline" does not narrow these
  5295. # down at all. Taking the first would attach an arbitrary video to
  5296. # this print and then delete it from the printer.
  5297. logger.warning(
  5298. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  5299. "leaving all of them on the printer for manual selection",
  5300. attempt,
  5301. len(candidates),
  5302. ", ".join(str(f.get("name")) for f in candidates),
  5303. )
  5304. return False
  5305. logger.warning(
  5306. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  5307. "the rest stay on the printer for manual selection",
  5308. attempt,
  5309. len(candidates),
  5310. ", ".join(str(f.get("name")) for f in candidates),
  5311. )
  5312. target = candidates[0]
  5313. file_name = target.get("name")
  5314. remote_path = target.get("path") or f"/timelapse/{file_name}"
  5315. logger.info(
  5316. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  5317. attempt,
  5318. file_name,
  5319. archive_id,
  5320. )
  5321. # The listing always carries a size (`list_files` skips entries it can't
  5322. # parse), but read it explicitly: the delete below is destructive and must
  5323. # depend on a size we actually had, not on one we hoped was there.
  5324. expected_size = target.get("size")
  5325. timelapse_data = await download_file_bytes_async(
  5326. printer.ip_address,
  5327. printer.access_code,
  5328. remote_path,
  5329. printer_model=printer.model,
  5330. expected_size=expected_size,
  5331. )
  5332. if not timelapse_data:
  5333. # Short or failed transfer. The printer keeps its copy, so the next
  5334. # round can try again — which is exactly why the delete below is
  5335. # gated on a verified download.
  5336. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  5337. return False
  5338. # The length check above proves we got what the listing said, not that the
  5339. # printer had finished writing. A video still being written can be listed
  5340. # short, served short, and pass — so confirm it has stopped growing before
  5341. # committing to it and deleting the original (#2704).
  5342. if not await remote_file_settled(
  5343. printer.ip_address,
  5344. printer.access_code,
  5345. remote_path,
  5346. len(timelapse_data),
  5347. printer_model=printer.model,
  5348. ):
  5349. return False
  5350. # Write phase: attach in a fresh short-lived session.
  5351. async with async_session() as db:
  5352. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name)
  5353. if not success:
  5354. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  5355. return False
  5356. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  5357. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  5358. await delete_archived_timelapse(
  5359. printer.ip_address,
  5360. printer.access_code,
  5361. remote_path,
  5362. verified=expected_size is not None,
  5363. printer_model=printer.model,
  5364. printer_name=printer.name,
  5365. )
  5366. return True
  5367. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  5368. # module-level so tests can monkeypatch them down to ~0 without timing out.
  5369. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  5370. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  5371. # How long the *background* upgrade keeps waiting after the notification has
  5372. # already gone out (#2704 follow-up). The short bound above exists so a slow
  5373. # printer can't hold up the print-complete notification; this one exists so the
  5374. # archive still ends up with the better frame afterwards.
  5375. #
  5376. # Measured across 261 attaches in the support bundles, the video lands a median
  5377. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  5378. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  5379. # was 546s. Every other model was inside 26s. The long budget is therefore
  5380. # almost entirely for P1-series users; on everything else the short wait already
  5381. # wins and this task never runs.
  5382. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  5383. async def _capture_finish_photo_from_timelapse(
  5384. archive_id: int,
  5385. archive_dir: Path,
  5386. timeout: float | None = None,
  5387. rotation: int = 0,
  5388. ) -> tuple[str | None, bool]:
  5389. """Wait for the per-print timelapse to land on the archive and extract its
  5390. last frame as the finish photo (#1397).
  5391. Bambu firmware stops timelapse recording after the toolhead parks but
  5392. before the bed-drop end-gcode runs, so the last frame frames the finished
  5393. print correctly. A live camera grab at gcode_state=FINISH captures the
  5394. bed already lowered.
  5395. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  5396. ``archive.timelapse_path`` when the file lands. This function polls for
  5397. that field.
  5398. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  5399. the wait ran out with no video on the archive yet — i.e. the video may
  5400. still be coming and a later attempt could succeed. It is False when the
  5401. video landed (whether or not extraction worked), because in that case
  5402. waiting longer changes nothing. The caller uses that to decide between
  5403. falling back permanently and scheduling a background upgrade.
  5404. ``rotation`` is the printer's camera_rotation, applied to the extracted
  5405. still (#2708) so this source agrees with every other finish-photo source.
  5406. The archived video itself is the printer's own file and is left alone —
  5407. rotating it would mean re-encoding it.
  5408. """
  5409. import uuid
  5410. from backend.app.models.archive import PrintArchive
  5411. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  5412. logger = logging.getLogger(__name__)
  5413. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  5414. deadline = asyncio.get_event_loop().time() + budget
  5415. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  5416. while True:
  5417. async with async_session() as db:
  5418. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5419. archive = result.scalar_one_or_none()
  5420. timelapse_relpath = archive.timelapse_path if archive else None
  5421. if timelapse_relpath:
  5422. video_path = app_settings.base_dir / timelapse_relpath
  5423. if video_path.exists() and video_path.stat().st_size > 0:
  5424. photos_dir = archive_dir / "photos"
  5425. photos_dir.mkdir(parents=True, exist_ok=True)
  5426. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5427. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5428. output_path = photos_dir / filename
  5429. if await extract_video_last_frame(video_path, output_path):
  5430. await apply_camera_rotation_to_file(output_path, rotation, logger)
  5431. logger.info(
  5432. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  5433. video_path.name,
  5434. archive_id,
  5435. )
  5436. return filename, False
  5437. logger.warning(
  5438. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  5439. video_path.name,
  5440. archive_id,
  5441. )
  5442. return None, False
  5443. if asyncio.get_event_loop().time() >= deadline:
  5444. logger.info(
  5445. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  5446. archive_id,
  5447. budget,
  5448. )
  5449. return None, True
  5450. await asyncio.sleep(poll_interval)
  5451. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  5452. """Add the timelapse's last frame to an archive after the fact (#2704).
  5453. The print-complete notification waits only ~60s for the video, because
  5454. holding a notification for minutes is worse than sending it with a live
  5455. camera grab. On a P1-series printer the video often lands well after that,
  5456. so the archive used to be stuck with the live grab — which is taken at
  5457. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  5458. the worse photo of the two.
  5459. This keeps waiting in the background and, when the video arrives, extracts
  5460. the frame and puts it *first* in the archive's photo list, so opening the
  5461. gallery shows it. The live grab is deliberately kept: the notification that
  5462. already went out links to that exact file, and deleting it would leave a
  5463. broken image in Discord or Telegram.
  5464. """
  5465. logger = logging.getLogger(__name__)
  5466. filename, _ = await _capture_finish_photo_from_timelapse(
  5467. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  5468. )
  5469. if not filename:
  5470. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  5471. return
  5472. try:
  5473. async with async_session() as db:
  5474. from backend.app.models.archive import PrintArchive
  5475. archive = await db.get(PrintArchive, archive_id)
  5476. if archive is None:
  5477. return
  5478. photos = list(archive.photos or [])
  5479. if filename in photos:
  5480. return
  5481. # Front of the list: PhotoGalleryModal opens at index 0.
  5482. archive.photos = [filename, *photos]
  5483. await db.commit()
  5484. except Exception as e:
  5485. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  5486. return
  5487. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  5488. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  5489. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  5490. """Put the filament-attribution context back after a restart mid-print.
  5491. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  5492. both die with the process. The print keeps running, so at completion the
  5493. tracker would fall back to whatever the printer reports *now* — and AMS
  5494. filament backup makes "now" the substitute tray, charging the whole print
  5495. to the spool that only finished it.
  5496. The persisted row is only trusted when its print name still matches what
  5497. the printer says it is running: a row left behind by a completion we never
  5498. saw must not attach itself to the next print.
  5499. """
  5500. try:
  5501. from backend.app.api.routes.settings import get_setting
  5502. from backend.app.services.usage_tracker import (
  5503. clear_persisted_session,
  5504. get_persisted_print_name,
  5505. restore_session,
  5506. )
  5507. persisted_name = await get_persisted_print_name(db, printer_id)
  5508. current_name = (state.subtask_name or "").strip()
  5509. if persisted_name and current_name and persisted_name.strip() != current_name:
  5510. logger.info(
  5511. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  5512. printer_id,
  5513. persisted_name,
  5514. current_name,
  5515. )
  5516. await clear_persisted_session(db, printer_id)
  5517. # Fall through to seeding: the print on the printer is real, it just
  5518. # isn't the one the row described.
  5519. persisted_log = None
  5520. else:
  5521. # Spoolman users get the tray-change log back but no in-memory
  5522. # session — see ``on_print_start`` on why that dict is load-bearing
  5523. # for the remain%-sync guard.
  5524. _spoolman_on = await get_setting(db, "spoolman_enabled")
  5525. persisted_log = await restore_session(
  5526. db,
  5527. printer_id,
  5528. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  5529. )
  5530. if persisted_log:
  5531. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  5532. # Anything this process already observed goes after the persisted
  5533. # history — the log is ordered by layer, and a fresh process can
  5534. # only have seen changes from later in the print.
  5535. for entry in state.tray_change_log or []:
  5536. if tuple(entry) not in restored:
  5537. restored.append(tuple(entry))
  5538. state.tray_change_log = restored
  5539. tray_now = state.tray_now
  5540. if 0 <= tray_now <= 254:
  5541. if not state.tray_change_log:
  5542. # No persisted history — a print that started before this build,
  5543. # or before the row existed. Seed with the tray feeding right
  5544. # now so the remainder of the print is at least attributable to
  5545. # the right spool.
  5546. state.tray_change_log = [(tray_now, state.layer_num)]
  5547. logger.info(
  5548. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  5549. printer_id,
  5550. tray_now,
  5551. state.layer_num,
  5552. )
  5553. # The tray handler updates ``last_loaded_tray`` on every push
  5554. # regardless of whether it logged a change, so re-align it to avoid
  5555. # a duplicate entry on the next push. Only ever with a real tray:
  5556. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  5557. # 255" fallback, and writing 255 into it would defeat that.
  5558. state.last_loaded_tray = tray_now
  5559. except Exception:
  5560. # Never let attribution recovery cost the caller its timelapse
  5561. # baseline — that capture has to happen before the printer uploads
  5562. # the in-flight MP4 and there is no second chance at it.
  5563. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  5564. async def on_print_running_observed(printer_id: int, data: dict):
  5565. """Restart-recovery for a print that started before Bambuddy came up.
  5566. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  5567. after Bambuddy startup (#1304 guard, prevents duplicate archive
  5568. creation). This hook restores the persisted archive into ``_active_prints``
  5569. and captures the timelapse baseline that normally hangs off print start.
  5570. Fires once per session, in lieu of on_print_start when restart-recovery
  5571. kicks in. The printer doesn't upload the timelapse until after PRINT
  5572. COMPLETE, so a baseline captured any time during the print is still
  5573. pre-upload.
  5574. """
  5575. logger = logging.getLogger(__name__)
  5576. async with async_session() as db:
  5577. from backend.app.models.printer import Printer
  5578. state = printer_manager.get_status(printer_id)
  5579. if state is not None:
  5580. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  5581. if authorization is True:
  5582. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  5583. await _restore_usage_tracking_session(printer_id, state, db, logger)
  5584. await _restore_printable_objects(printer_id, state, db, logger)
  5585. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5586. printer = result.scalar_one_or_none()
  5587. if not printer:
  5588. logger.warning(
  5589. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  5590. printer_id,
  5591. )
  5592. return
  5593. # Avoid double-capture: ownership reconciliation above must still run when
  5594. # a baseline already exists, but the camera work itself is one-shot.
  5595. if printer_id in _timelapse_baselines:
  5596. logger.debug(
  5597. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  5598. printer_id,
  5599. )
  5600. return
  5601. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  5602. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  5603. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  5604. against the printer's current MQTT state.
  5605. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  5606. COMPLETE events, typically a print finishing during an MQTT disconnect
  5607. window followed by a smart-plug power cycle):
  5608. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  5609. provably not running anymore — only branch that should fire under
  5610. normal disconnect-then-reconnect timing.
  5611. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  5612. firmware mints a fresh ``subtask_id`` for each print, including the
  5613. ghost replay it runs after a power cycle from a leftover SD file —
  5614. so a mismatch unambiguously means the in-DB archive is no longer
  5615. the print on the printer.
  5616. 3. Printer is running but ``subtask_name`` is empty. The printer
  5617. doesn't know what it's running; the archive's reference to it is
  5618. already broken.
  5619. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  5620. with matching subtask_id+subtask_name is left alone. The cost of a false
  5621. positive is a duplicate archive on the next real PRINT COMPLETE — the
  5622. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  5623. clears on synthesis, so the real completion creates a fresh row instead
  5624. of overwriting the synthesised one (#1679). The cost of a false negative
  5625. is the ghost-print loop in #1542.
  5626. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  5627. MQTT has connected but the first ``push_status`` response hasn't been
  5628. applied yet — ``PrinterState`` is sitting on its construction defaults.
  5629. The reconcile caller in ``on_printer_status_change`` is already gated
  5630. on a real ``state.state``, so in normal operation this branch is
  5631. unreachable; it's kept as belt-and-braces for future callers and for
  5632. the narrow window where a partial state update could arrive
  5633. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  5634. ``not stale`` on degenerate input is strictly conservative: a real
  5635. stale archive will still be caught by the next push_status arriving
  5636. with terminal state.
  5637. """
  5638. current_state = (state.state or "").upper()
  5639. if current_state in ("", "UNKNOWN"):
  5640. # No real push_status yet — PrinterState defaults are not evidence.
  5641. return False, ""
  5642. if current_state in ("IDLE", "FINISH", "FAILED"):
  5643. return True, f"printer state {current_state}"
  5644. # Below here the printer is in a running / pre-running state (RUNNING /
  5645. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  5646. current_subtask_id = (state.subtask_id or "").strip()
  5647. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  5648. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  5649. current_subtask_name = (state.subtask_name or "").strip()
  5650. if not current_subtask_name:
  5651. return True, "printer subtask_name empty"
  5652. return False, ""
  5653. async def prime_kprofile_table(printer_id: int) -> int:
  5654. """Read the printer's calibration table once per connection.
  5655. The AMS slot card shows a K value per slot (#2854). On the printers whose
  5656. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  5657. report ``cali_idx`` and nothing else -- that number can only come from
  5658. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  5659. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  5660. backup, or the printer answering a query BambuStudio made on the report
  5661. topic we share. A Bambuddy that nobody visited showed a card with no K
  5662. values at all.
  5663. Only the diameters actually fitted are asked for, which is one request on a
  5664. single-nozzle printer and two on a dual. Probing the four sizes blind is
  5665. what the backup does, and it is both wasteful and the thing that used to
  5666. blank the table.
  5667. Returns the number of nozzles whose table was read.
  5668. """
  5669. client = printer_manager.get_client(printer_id)
  5670. state = printer_manager.get_status(printer_id)
  5671. if client is None or state is None or not state.connected:
  5672. return 0
  5673. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  5674. # ask once, and both entries are empty until the first push_status lands.
  5675. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  5676. if not diameters:
  5677. logging.getLogger(__name__).debug(
  5678. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  5679. printer_id,
  5680. )
  5681. return 0
  5682. primed = 0
  5683. for diameter in diameters:
  5684. try:
  5685. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  5686. except Exception as exc: # noqa: BLE001
  5687. # A printer that won't answer costs the card its K values, nothing
  5688. # more — never the connection this runs on the back of.
  5689. logging.getLogger(__name__).warning(
  5690. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  5691. )
  5692. continue
  5693. primed += 1
  5694. logging.getLogger(__name__).info(
  5695. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  5696. )
  5697. return primed
  5698. def _sd_files_in_use(state) -> set[str]:
  5699. """Names of the SD-card files the printer may be printing right now (#3009).
  5700. The post-print cleanup works out what to delete from the finished archive,
  5701. not from the printer. When reconciliation closes an old archive because the
  5702. printer has moved on to a new job, and that job is the same file reprinted
  5703. from the printer's screen, the cleanup would delete the file mid-print.
  5704. Empty unless the printer is busy: on an ordinary completion the state is
  5705. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  5706. name, a path or a URL depending on firmware, and some report only the
  5707. plate's G-code, so the job name is matched as well, in the same spellings
  5708. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  5709. ignores case.
  5710. """
  5711. def _text(value) -> str:
  5712. return value.strip() if isinstance(value, str) else ""
  5713. if state is None:
  5714. return set()
  5715. current_state = _text(getattr(state, "state", None)).upper()
  5716. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  5717. return set()
  5718. in_use: set[str] = set()
  5719. gcode_file = _text(getattr(state, "gcode_file", None))
  5720. if gcode_file:
  5721. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  5722. # both legal in a file name, and raises on some inputs.
  5723. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  5724. if name:
  5725. in_use.add(name.lower())
  5726. subtask_name = _text(getattr(state, "subtask_name", None))
  5727. if subtask_name:
  5728. for name in (subtask_name, subtask_name.replace(" ", "_")):
  5729. for ext in (".3mf", ".gcode"):
  5730. in_use.add(f"{name}{ext}".lower())
  5731. return in_use
  5732. async def reconcile_stale_active_prints(printer_id: int) -> int:
  5733. """Synthesise ``on_print_complete`` for archives whose print can't be
  5734. running on the printer anymore.
  5735. Called once per MQTT (re)connection (from on_printer_status_change when
  5736. the connected edge flips False → True) and at Bambuddy startup (from
  5737. the FastAPI lifespan). Without this, a print that completes during a
  5738. disconnect window — followed by a smart-plug-driven power cycle — leaves
  5739. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  5740. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  5741. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  5742. power cycle until the operator notices (#1542 follow-up). Reconciliation
  5743. closes the loop by faking the missed PRINT COMPLETE — the existing
  5744. cleanup chain handles SD-file deletion, status updates, usage tracking,
  5745. and notifications.
  5746. Synthesised ``status="aborted"`` is the conservative label: we have no
  5747. proof the print finished successfully (and no progress evidence to
  5748. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  5749. fires later, overwrites the status with the correct value.
  5750. Returns the number of archives reconciled.
  5751. """
  5752. state = printer_manager.get_status(printer_id)
  5753. if not state:
  5754. return 0
  5755. # Don't reconcile while disconnected — we'd be making a decision against
  5756. # stale cached state. The connected → reconcile edge handles this.
  5757. if not state.connected:
  5758. return 0
  5759. from backend.app.models.archive import PrintArchive
  5760. reconciled = 0
  5761. async with async_session() as db:
  5762. result = await db.execute(
  5763. select(PrintArchive).where(
  5764. PrintArchive.printer_id == printer_id,
  5765. PrintArchive.status == "printing",
  5766. )
  5767. )
  5768. active = list(result.scalars().all())
  5769. if not active:
  5770. return 0
  5771. logger = logging.getLogger(__name__)
  5772. for archive in active:
  5773. is_stale, reason = _is_active_archive_stale(archive, state)
  5774. if not is_stale:
  5775. continue
  5776. logger.info(
  5777. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  5778. printer_id,
  5779. archive.id,
  5780. archive.filename,
  5781. reason,
  5782. )
  5783. # Synthesised payload: minimal fields the on_print_complete chain
  5784. # needs. `_reconciled` marker lets downstream code distinguish this
  5785. # from a real MQTT-driven completion if it ever needs to (e.g. for
  5786. # metrics / debug logging). raw_data is the live printer state so
  5787. # the usage tracker can compare end-of-print remain% against the
  5788. # captured start values.
  5789. try:
  5790. await on_print_complete(
  5791. printer_id,
  5792. {
  5793. "status": "aborted",
  5794. "filename": archive.filename,
  5795. "subtask_name": archive.print_name or "",
  5796. "subtask_id": archive.subtask_id or "",
  5797. "raw_data": state.raw_data or {},
  5798. "_reconciled": True,
  5799. },
  5800. )
  5801. reconciled += 1
  5802. except Exception as e:
  5803. # Catch-all: a reconciliation failure must not block the
  5804. # printer's normal status flow. The archive stays in
  5805. # ``status="printing"`` and the next reconnect retries.
  5806. logger.warning(
  5807. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  5808. archive.id,
  5809. e,
  5810. )
  5811. return reconciled
  5812. # #2547: clearance left between the nozzle and the top of the print when the
  5813. # plate is commanded back into camera framing. The nozzle is parked away from
  5814. # the part by then, so this is belt-and-braces against a max_z_height that
  5815. # under-reports (e.g. a slicer that excludes a final Z hop).
  5816. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  5817. # How far below the restored position to drop the plate again afterwards, so
  5818. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  5819. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  5820. # on machines with less headroom.
  5821. _PLATE_PARK_DROP_MM = 100.0
  5822. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  5823. # this axis, so it is a proven-safe speed for the full travel.
  5824. _PLATE_RESTORE_FEEDRATE = 600
  5825. # Time allowed for the plate to reach the restored position before the camera
  5826. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  5827. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  5828. # How long `_background_finish_photo` waits for this producer. Must cover the
  5829. # settle window plus a worst-case RTSP grab (15s), and stay below the
  5830. # notification path's own photo wait so a slow producer degrades to a
  5831. # photo-less notification rather than a missed one. The chamber light's
  5832. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  5833. # camera_light.MAX_DELAY_SECONDS stays below it.
  5834. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  5835. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  5836. """The ``_active_prints`` keys a finished print may be registered under.
  5837. Matching how they were registered in on_print_start. Shared by
  5838. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  5839. to find the same binding.
  5840. """
  5841. possible_keys = []
  5842. # Try subtask_name variations first (most reliable for matching)
  5843. if subtask_name:
  5844. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  5845. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  5846. possible_keys.append((printer_id, subtask_name))
  5847. # Try filename variations
  5848. if filename:
  5849. # Extract just the filename if it's a path
  5850. fname = filename.split("/")[-1] if "/" in filename else filename
  5851. if fname.endswith(".3mf"):
  5852. possible_keys.append((printer_id, fname))
  5853. elif fname.endswith(".gcode"):
  5854. base_name = fname.rsplit(".", 1)[0]
  5855. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  5856. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5857. possible_keys.append((printer_id, fname))
  5858. else:
  5859. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  5860. possible_keys.append((printer_id, f"{fname}.3mf"))
  5861. possible_keys.append((printer_id, fname))
  5862. # Also try full path versions
  5863. if filename.endswith(".3mf"):
  5864. possible_keys.append((printer_id, filename))
  5865. elif filename.endswith(".gcode"):
  5866. base_name = filename.rsplit(".", 1)[0]
  5867. possible_keys.append((printer_id, f"{base_name}.3mf"))
  5868. possible_keys.append((printer_id, filename))
  5869. else:
  5870. possible_keys.append((printer_id, f"{filename}.3mf"))
  5871. possible_keys.append((printer_id, filename))
  5872. return possible_keys
  5873. def _archive_name_forms(archive) -> set[str]:
  5874. """The names an archive could be echoed back as, in normalised form (#3240).
  5875. Its print name, and its filename with and without the 3MF extension.
  5876. """
  5877. forms = set()
  5878. if archive.print_name:
  5879. forms.add(_normalise_subtask_name(archive.print_name))
  5880. if archive.filename:
  5881. forms.add(_normalise_subtask_name(archive.filename))
  5882. for suffix in (".gcode.3mf", ".3mf"):
  5883. if archive.filename.lower().endswith(suffix):
  5884. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  5885. forms.discard("")
  5886. return forms
  5887. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  5888. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  5889. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  5890. from the plate recorded when the job was dispatched. Neither is touched:
  5891. ``on_print_complete`` pops both, which is why the finish-photo producer
  5892. calls this before its first await, while they are still there.
  5893. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  5894. archive, or that it only knows by a name -- and on any error: the producer
  5895. calls this before the ``try`` that always releases the photo consumer, so
  5896. it must not raise.
  5897. """
  5898. try:
  5899. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  5900. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  5901. if archive_id is None:
  5902. return None, None
  5903. return archive_id, _print_plate_ids.get(archive_id)
  5904. except Exception:
  5905. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  5906. return None, None
  5907. async def _max_z_for_current_print(
  5908. printer_id: int,
  5909. data: dict,
  5910. logger,
  5911. archive_id: int | None,
  5912. plate_id: int | None = None,
  5913. ) -> float | None:
  5914. """Height of the print that just finished on ``printer_id``, or None (#2547).
  5915. This number becomes the target of a real Z move, so every step here refuses
  5916. rather than guesses. A height belonging to some *other* print is the one
  5917. failure that could drive the nozzle into the model: 20 mm carried onto a
  5918. 200 mm print would command the plate up through the part.
  5919. Three independent things therefore have to agree before a height is
  5920. returned:
  5921. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  5922. when it started (see ``_bound_print``), never one found by name. A name
  5923. is not an identity: every plate of a multi-plate file shares one, and a
  5924. reprint reuses its archive row, so the newest archive with the right
  5925. name can be another plate of the same file. Support bundles show the
  5926. old name lookup doing exactly that (archive 288 for a print bound to
  5927. 169, 313 layers against 125), stopped only by the layer check below.
  5928. No binding, no move.
  5929. 2. **Identity.** The bound archive's name still has to be the finished
  5930. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  5931. because the printer echoes spaces as underscores (#3240). Exact: not a
  5932. substring, and not the completion check's tolerance for a truncated
  5933. echo.
  5934. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  5935. match the layer count the printer itself reported over MQTT for the print
  5936. that just ended. These come from genuinely different sources, so a
  5937. mismatch means the row is not this print, whatever its name says.
  5938. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  5939. plate of a multi-plate file reuses the archive row without updating its
  5940. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  5941. ``on_print_complete`` may already have flipped the status by the time we
  5942. run.
  5943. """
  5944. subtask_name = (data.get("subtask_name") or "").strip()
  5945. if not subtask_name:
  5946. # Nothing to identify the print by — refuse rather than fall back to
  5947. # "whatever ran last on this printer".
  5948. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  5949. return None
  5950. if archive_id is None:
  5951. logger.info(
  5952. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  5953. printer_id,
  5954. subtask_name,
  5955. )
  5956. return None
  5957. try:
  5958. from backend.app.models.archive import PrintArchive
  5959. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  5960. async with async_session() as db:
  5961. result = await db.execute(
  5962. select(PrintArchive).where(
  5963. PrintArchive.id == archive_id,
  5964. PrintArchive.printer_id == printer_id,
  5965. PrintArchive.status.in_(("printing", "completed")),
  5966. PrintArchive.deleted_at.is_(None),
  5967. )
  5968. )
  5969. archive = result.scalar_one_or_none()
  5970. if archive is None or not archive.file_path:
  5971. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  5972. return None
  5973. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  5974. logger.warning(
  5975. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  5976. printer_id,
  5977. archive_id,
  5978. subtask_name,
  5979. )
  5980. return None
  5981. client = printer_manager.get_client(printer_id)
  5982. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  5983. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  5984. logger.warning(
  5985. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  5986. "— refusing to move the plate on a height that may not be this print's",
  5987. printer_id,
  5988. archive.id,
  5989. archive.total_layers,
  5990. reported_layers,
  5991. )
  5992. return None
  5993. # Stored relative to the data directory, like every other archive path
  5994. # (#3240: this read a `data_dir` setting that does not exist).
  5995. path = app_settings.base_dir / archive.file_path
  5996. plate = plate_id or archive.plate_id or 1
  5997. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  5998. except Exception as e:
  5999. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  6000. return None
  6001. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  6002. """Raise the plate back into camera framing before the finish photo (#2547).
  6003. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  6004. the time ``gcode_state`` reaches FINISH the finished print sits far below
  6005. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  6006. This commands an absolute ``G1 Z`` back to just above the last printed
  6007. layer.
  6008. Absolute, not relative, is the whole safety argument. ``max_z_height +
  6009. clearance`` is a height the toolhead was physically at seconds earlier, so
  6010. it is inside the travel limits by construction and leaves the nozzle above
  6011. the part. It is also unambiguous across model families: Z is the
  6012. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  6013. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  6014. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  6015. (#2579).
  6016. Returns True if the move was sent and waited out, False if it was skipped.
  6017. """
  6018. client = printer_manager.get_client(printer_id)
  6019. if client is None:
  6020. return False
  6021. # Re-read state immediately before commanding motion. If the queue has
  6022. # already started the next print, the printer is no longer ours to move.
  6023. state = getattr(client, "state", None)
  6024. if state is None or state.state != "FINISH":
  6025. logger.info(
  6026. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  6027. printer_id,
  6028. getattr(state, "state", "unknown"),
  6029. )
  6030. return False
  6031. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  6032. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  6033. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  6034. return False
  6035. logger.info(
  6036. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  6037. printer_id,
  6038. target_z,
  6039. max_z_height,
  6040. _PLATE_RESTORE_CLEARANCE_MM,
  6041. _PLATE_RESTORE_SETTLE_SECONDS,
  6042. )
  6043. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  6044. return True
  6045. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  6046. """Drop the plate again after the finish photo (#2547).
  6047. Without this the user walks up to a finished print sitting just under the
  6048. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  6049. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  6050. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  6051. print homes anyway.
  6052. """
  6053. client = printer_manager.get_client(printer_id)
  6054. state = getattr(client, "state", None) if client else None
  6055. if client is None or state is None or state.state != "FINISH":
  6056. return
  6057. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  6058. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  6059. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  6060. """True if a queue item is about to take this printer (#2547).
  6061. The scheduler dispatches the next job the moment a print completes, and a
  6062. plate move interleaved with a print start is not a race worth having. The
  6063. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  6064. this window; this closes the head of it.
  6065. """
  6066. try:
  6067. from backend.app.models.print_queue import PrintQueueItem
  6068. async with async_session() as db:
  6069. result = await db.execute(
  6070. select(PrintQueueItem.id)
  6071. .where(
  6072. PrintQueueItem.printer_id == printer_id,
  6073. PrintQueueItem.status.in_(("pending", "printing")),
  6074. )
  6075. .limit(1)
  6076. )
  6077. return result.scalar_one_or_none() is not None
  6078. except Exception as e:
  6079. # Fail closed: if we can't tell, don't move the plate.
  6080. logging.getLogger(__name__).debug(
  6081. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  6082. )
  6083. return True
  6084. async def on_finish_photo_moment(printer_id: int, data: dict):
  6085. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  6086. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  6087. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  6088. fallback for prints that skip stage 22 (cancel, external-spool-only,
  6089. HMS halt, firmware variants). Grabs one frame via the same
  6090. external-camera / RTSP path the post-completion fallback uses, stores
  6091. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  6092. ``_background_finish_photo`` consume the cached bytes when it runs.
  6093. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  6094. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  6095. set to Smooth (#1721). No force-on now means the user's explicit
  6096. timelapse=off in the slicer send dialog is respected.
  6097. """
  6098. logger = logging.getLogger(__name__)
  6099. trigger = data.get("trigger", "unknown")
  6100. timelapse_was_active = bool(data.get("timelapse_was_active"))
  6101. logger.info(
  6102. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  6103. printer_id,
  6104. trigger,
  6105. timelapse_was_active,
  6106. )
  6107. # If a timelapse is actively recording, skip the pre-capture — the
  6108. # post-completion path will extract the last frame from the recorded
  6109. # video, which still provides the best framing (toolhead parked,
  6110. # before bed drop) without the per-layer parking side effects.
  6111. if timelapse_was_active:
  6112. logger.info(
  6113. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  6114. printer_id,
  6115. )
  6116. return
  6117. # #1790: register the producer-done event BEFORE the first await so the
  6118. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  6119. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  6120. # The `finally` below guarantees `set()` runs on every exit, including
  6121. # early returns and exceptions, so the consumer's bounded wait can't hang.
  6122. producer_done = asyncio.Event()
  6123. _stage22_finish_in_flight[printer_id] = producer_done
  6124. # #3240: also before the first await. On the FINISH-state path
  6125. # `on_print_complete` is dispatched right behind us and pops both the
  6126. # print's archive binding and its plate; read here, they are still there.
  6127. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  6128. # #2547: set once the plate has actually been raised, and read by the
  6129. # `finally` below. Declared out here so a failure anywhere after the move —
  6130. # a camera timeout, a DB error — still lowers the plate again.
  6131. restore_max_z: float | None = None
  6132. try:
  6133. async with async_session() as db:
  6134. from backend.app.api.routes.settings import get_setting
  6135. from backend.app.models.printer import Printer
  6136. capture_setting = await get_setting(db, "capture_finish_photo")
  6137. if capture_setting is not None and capture_setting.lower() != "true":
  6138. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  6139. return
  6140. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6141. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  6142. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6143. printer = result.scalar_one_or_none()
  6144. if printer is None:
  6145. logger.warning(
  6146. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  6147. printer_id,
  6148. )
  6149. return
  6150. frame_bytes: bytes | None = None
  6151. # #2708: the banked frame arrives already rotated — it comes from
  6152. # `_capture_snapshot_for_notification`, which rotates before returning.
  6153. # Every other source below is a raw grab. Tracking which lets us store
  6154. # exactly one rotation in `_stage22_finish_frames` either way.
  6155. frame_already_rotated = False
  6156. # On the FINISH-state path the End G-code has already run, and two very
  6157. # different situations arrive here needing opposite answers.
  6158. #
  6159. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  6160. # snippet may have ejected the plate — the scene in front of the camera
  6161. # is no longer the finished print, and no amount of moving the plate
  6162. # brings it back. Use the banked in-print frame instead.
  6163. #
  6164. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  6165. # than the camera frames well, and the toolhead is parked out of the
  6166. # way. That is the *best* moment available on firmware that never emits
  6167. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  6168. # back. Preferring the bank here unconditionally, as this code used to,
  6169. # is what shipped a mid-print photo with the toolhead over the part.
  6170. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  6171. banked = _inprint_frame_bank.get(printer_id)
  6172. if banked:
  6173. frame_bytes = banked
  6174. frame_already_rotated = True
  6175. logger.info(
  6176. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  6177. "frame (%d bytes) instead of a post-swap live grab",
  6178. len(banked),
  6179. )
  6180. else:
  6181. logger.warning(
  6182. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  6183. "in-print bank is empty — falling back to a live grab, which may show a "
  6184. "swapped or empty plate",
  6185. printer_id,
  6186. )
  6187. # `restore_max_z` is set only once the plate is actually up, because the
  6188. # `finally` reads it to decide whether it owes a move back down.
  6189. #
  6190. # Never on a print whose End G-code Bambuddy injected, even when the bank
  6191. # came up empty above: that machine may have just ejected its plate, and
  6192. # driving Z into whatever a swap mechanism is doing is not a risk worth
  6193. # taking for a photo of a bed we already know may be bare.
  6194. if (
  6195. frame_bytes is None
  6196. and trigger == "finish_state"
  6197. and restore_plate_enabled
  6198. and not print_dispatch_context.end_gcode_injected(printer_id)
  6199. ):
  6200. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  6201. if wants_restore is None:
  6202. logger.info(
  6203. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  6204. printer_id,
  6205. )
  6206. elif await _plate_restore_is_blocked_by_queue(printer_id):
  6207. logger.info(
  6208. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  6209. printer_id,
  6210. )
  6211. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  6212. restore_max_z = wants_restore
  6213. # Chamber light for the live capture below (#1655). The banked frame
  6214. # above was taken without it, like every in-print bank.
  6215. async with camera_light(printer if frame_bytes is None else None):
  6216. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  6217. from backend.app.api.routes.camera import live_frame_for_capture
  6218. from backend.app.services.external_camera import capture_frame
  6219. # #2707: this used to collide with the live view and fail, which is
  6220. # how finish-photo notifications went out with no image attached.
  6221. # Leaving frame_bytes None keeps the rest of the fallback chain.
  6222. defer, buffered = live_frame_for_capture(printer_id)
  6223. if defer:
  6224. frame_bytes = buffered
  6225. else:
  6226. frame_bytes = await capture_frame(
  6227. printer.external_camera_url,
  6228. printer.external_camera_type or "mjpeg",
  6229. snapshot_url=printer.external_camera_snapshot_url,
  6230. )
  6231. if frame_bytes:
  6232. logger.info(
  6233. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  6234. len(frame_bytes),
  6235. )
  6236. elif frame_bytes is None:
  6237. from backend.app.api.routes.camera import get_buffered_frame
  6238. buffered = get_buffered_frame(printer_id)
  6239. if buffered:
  6240. frame_bytes = buffered
  6241. logger.info(
  6242. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  6243. len(frame_bytes),
  6244. )
  6245. else:
  6246. from backend.app.services.camera import capture_camera_frame_bytes
  6247. frame_bytes = await capture_camera_frame_bytes(
  6248. ip_address=printer.ip_address,
  6249. access_code=printer.access_code,
  6250. model=printer.model,
  6251. timeout=15,
  6252. )
  6253. if frame_bytes:
  6254. logger.info(
  6255. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  6256. len(frame_bytes),
  6257. )
  6258. if frame_bytes:
  6259. if not frame_already_rotated:
  6260. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  6261. _stage22_finish_frames[printer_id] = frame_bytes
  6262. else:
  6263. logger.warning(
  6264. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  6265. printer_id,
  6266. )
  6267. except Exception as e:
  6268. logger.warning(
  6269. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  6270. printer_id,
  6271. e,
  6272. )
  6273. finally:
  6274. # #2547: we raised the plate, so we own lowering it — including when the
  6275. # capture above failed or threw partway through.
  6276. if restore_max_z is not None:
  6277. try:
  6278. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  6279. except Exception as e:
  6280. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6281. # #1790: always unblock the consumer's bounded wait — whether we stored
  6282. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  6283. # dict entry by the consumer doesn't affect signalling.
  6284. producer_done.set()
  6285. def _subtask_name_from_filename(filename: str) -> str:
  6286. """Recover the subtask name a print command would have carried for *filename*.
  6287. The dispatcher derives the printer-facing subtask name from the archive's
  6288. file name, so stripping the extensions back off gives the value MQTT echoes
  6289. on completion. Only the two extensions Bambuddy actually stores are removed,
  6290. and in the order they nest (``.gcode.3mf``), so a model whose own name
  6291. contains a dot -- ``My.Model.3mf`` -- keeps it.
  6292. """
  6293. name = PurePosixPath(filename).name
  6294. for suffix in (".3mf", ".gcode"):
  6295. if name.lower().endswith(suffix):
  6296. name = name[: -len(suffix)]
  6297. return name
  6298. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  6299. """Whether the subtask name is the printed 3MF's own file name.
  6300. A print started from the printer's screen reports the same full name, with
  6301. its extension, as both subtask and file (#3009). A dispatched print reports
  6302. a bare subtask name; one that merely ends in ".3mf" can be a model named
  6303. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  6304. """
  6305. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  6306. return False
  6307. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  6308. # How the printer marks a subtask name it had to cut short. Observed on real
  6309. # hardware at ~100 characters, but the cut-off is not a fixed character count
  6310. # (a name with multibyte characters came back at 98), so match the marker
  6311. # rather than a length.
  6312. _SUBTASK_TRUNCATION_MARKER = "..."
  6313. def _normalise_subtask_name(name: str) -> str:
  6314. """Canonical form for comparing a dispatched name against MQTT's echo.
  6315. The printer does not echo the name back verbatim: it substitutes
  6316. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  6317. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  6318. The 3MF lookup in this module has always known that -- it builds
  6319. space-to-underscore variants of every candidate filename, and its
  6320. directory search normalises both sides before comparing. This exists so
  6321. the completion check reads the same rule from the same place instead of
  6322. growing its own, which is exactly how it came to disagree (#2829).
  6323. A space at either end is substituted too: ``Part .gcode.3mf`` is
  6324. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  6325. are dropped after the substitution so both sides agree (#3241).
  6326. """
  6327. return name.strip().replace(" ", "_").strip("_").casefold()
  6328. def _subtask_names_match(expected: str, observed: str) -> bool:
  6329. """Whether two subtask names describe the same print.
  6330. Beyond the space/underscore substitution, the printer truncates long names
  6331. and marks the cut with ``...``. A truncated echo has to count as a match or
  6332. every print with a long name strands its queue item the same way.
  6333. """
  6334. expected_n = _normalise_subtask_name(expected)
  6335. observed_n = _normalise_subtask_name(observed)
  6336. if expected_n == observed_n:
  6337. return True
  6338. # Either side can be the truncated one: the printer truncates what it
  6339. # echoes, and an archive whose own filename was recorded from a previous
  6340. # truncated echo carries the marker too.
  6341. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  6342. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  6343. continue
  6344. # The full side has lost its edge underscores; a cut that lands right
  6345. # after one keeps it, so drop it here too (#3241). Nothing left before
  6346. # the marker is no evidence of anything, and must not match every name.
  6347. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  6348. if kept and full.startswith(kept):
  6349. return True
  6350. return False
  6351. async def _queue_item_dispatched_name(db, item) -> str:
  6352. """The subtask name *item* was dispatched under, or "" when unknowable.
  6353. A row with no archive, or an archive with no file name, is unverifiable
  6354. rather than wrong; every caller answers that with its permissive branch.
  6355. """
  6356. if item.archive_id is None:
  6357. return ""
  6358. from backend.app.models.archive import PrintArchive
  6359. archive = await db.get(PrintArchive, item.archive_id)
  6360. if archive is None or not archive.filename:
  6361. return ""
  6362. return _subtask_name_from_filename(archive.filename)
  6363. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  6364. """Whether this completion event is plausibly about *item*'s print.
  6365. The caller finds its queue row by printer and ``status='printing'`` alone,
  6366. which is all a completion event gives it -- there is no run identifier in
  6367. the MQTT payload to match on. That makes the lookup indiscriminate: any
  6368. completion delivered for this printer closes whichever row happens to be
  6369. printing, however unrelated. Comparing the subtask name against the archive
  6370. the row was dispatched with costs one primary-key load and rules that out.
  6371. Deliberately permissive: it answers False only on a positive disagreement
  6372. between two names we actually have. A row with no archive, an archive with
  6373. no file name, or an event with no subtask name is unverifiable rather than
  6374. wrong, and refusing those would strand the item in ``printing`` and wedge
  6375. the printer's queue -- a worse failure than the one being prevented.
  6376. """
  6377. observed = (data.get("subtask_name") or "").strip()
  6378. if not observed or item.archive_id is None:
  6379. return True
  6380. from backend.app.models.archive import PrintArchive
  6381. archive = await db.get(PrintArchive, item.archive_id)
  6382. if archive is None or not archive.filename:
  6383. return True
  6384. expected = _subtask_name_from_filename(archive.filename)
  6385. if not expected or _subtask_names_match(expected, observed):
  6386. return True
  6387. logging.getLogger(__name__).warning(
  6388. "Ignoring print completion for queue item %s: it was dispatched as %r "
  6389. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  6390. "printing rather than closing a run this event is not about.",
  6391. item.id,
  6392. expected,
  6393. archive.id,
  6394. archive.filename,
  6395. observed,
  6396. )
  6397. return False
  6398. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  6399. """Spend the 3MF download cache on a still-empty fallback archive.
  6400. ``on_print_complete`` drops the cache as its first act, which deletes the
  6401. file. If the cover endpoint (or anything else) pulled the 3MF while the
  6402. print ran and the archive never got one, this is the last moment those bytes
  6403. exist (#2957).
  6404. """
  6405. logger = logging.getLogger(__name__)
  6406. names = [
  6407. n
  6408. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  6409. if n
  6410. ]
  6411. for name in names:
  6412. try:
  6413. cached = get_cached_3mf(printer_id, name)
  6414. if cached and await try_recover_fallback_archive(printer_id, name, cached):
  6415. return
  6416. except Exception as e:
  6417. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  6418. async def _cleanup_sd_card_after_print(
  6419. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  6420. ) -> None:
  6421. """Delete a finished print's file from the printer's SD card."""
  6422. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  6423. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  6424. # auto-start files found in root on power cycle, causing ghost prints.
  6425. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  6426. try:
  6427. if subtask_name:
  6428. archive_filename: str | None = None
  6429. async with async_session() as db:
  6430. from backend.app.models.archive import PrintArchive
  6431. from backend.app.models.printer import Printer
  6432. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6433. printer = result.scalar_one_or_none()
  6434. if archive_id:
  6435. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  6436. archive_filename = archive_row.scalar_one_or_none()
  6437. if printer:
  6438. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  6439. from backend.app.utils.filename import derive_remote_filename
  6440. # Primary candidate: the exact path the dispatcher uploaded to
  6441. # (derived from archive.filename via the same rule as upload).
  6442. # Without it, a library row that ended up with a doubled
  6443. # .gcode.3mf (#1542) leaves the real file behind because the
  6444. # subtask_name + ext fallbacks below don't match what's on the
  6445. # SD card. Fallbacks remain for archive-less prints (subtask
  6446. # never resolved to an archive) and for older naming variants.
  6447. candidate_paths: list[str] = []
  6448. if archive_filename:
  6449. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  6450. for ext in (".3mf", ".gcode"):
  6451. fallback = f"/{subtask_name}{ext}"
  6452. if fallback not in candidate_paths:
  6453. candidate_paths.append(fallback)
  6454. # Three outcomes track across all candidates so the final log
  6455. # line reflects what actually happened. The A1 in #1721 always
  6456. # ends here with ``any_not_found=True`` and the others False
  6457. # — its firmware auto-cleans the SD card before our cleanup
  6458. # runs, every candidate FTP-DELE returns 550, and the old
  6459. # code burned 3 retries × 2 s × 3 candidates per print
  6460. # logging a misleading "may linger" WARNING on a successful
  6461. # print.
  6462. any_deleted = False
  6463. any_real_failure = False
  6464. any_not_found = False
  6465. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  6466. for remote_path in candidate_paths:
  6467. if PurePosixPath(remote_path).name.lower() in files_in_use:
  6468. logger.info(
  6469. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  6470. remote_path,
  6471. printer.name,
  6472. )
  6473. continue
  6474. # Retry only the FAILED case — 550 NOT_FOUND will never
  6475. # recover by waiting, so a "file isn't here" answer
  6476. # advances immediately to the next candidate without
  6477. # consuming the retry budget.
  6478. for attempt in range(1, 4):
  6479. try:
  6480. delete_result = await delete_file_async(
  6481. printer.ip_address,
  6482. printer.access_code,
  6483. remote_path,
  6484. printer_model=printer.model,
  6485. )
  6486. except Exception as e:
  6487. delete_result = DeleteResult.FAILED
  6488. logger.warning(
  6489. "SD card cleanup attempt %d/3 raised for %s: %s",
  6490. attempt,
  6491. remote_path,
  6492. e,
  6493. )
  6494. if delete_result == DeleteResult.DELETED:
  6495. any_deleted = True
  6496. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  6497. break
  6498. if delete_result == DeleteResult.NOT_FOUND:
  6499. any_not_found = True
  6500. break # 550 will not recover; try next candidate
  6501. # FAILED: real error — retry with backoff, then give up
  6502. if attempt < 3:
  6503. await asyncio.sleep(2)
  6504. else:
  6505. any_real_failure = True
  6506. logger.warning(
  6507. "SD card cleanup failed after 3 attempts for %s "
  6508. "(network/auth/transient error — file may linger on SD card)",
  6509. remote_path,
  6510. )
  6511. if not any_deleted and not any_real_failure and any_not_found:
  6512. # Every candidate said "not here." Either the printer
  6513. # firmware swept the SD card itself (common on A1) or the
  6514. # dispatcher's upload path doesn't match our candidate
  6515. # rule. Either way: nothing to clean up, no warning.
  6516. logger.debug(
  6517. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  6518. "(printer likely self-cleaned)",
  6519. printer.name,
  6520. )
  6521. except Exception as e:
  6522. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  6523. async def on_print_complete(printer_id: int, data: dict):
  6524. """Handle print completion - update the archive status."""
  6525. import time
  6526. logger = logging.getLogger(__name__)
  6527. start_time = time.time()
  6528. def log_timing(section: str):
  6529. elapsed = time.time() - start_time
  6530. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  6531. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  6532. # A kill-switch stop sends its provider notification immediately. Keep the
  6533. # task so the later notification path can await it and avoid a duplicate;
  6534. # if that immediate attempt failed, the regular completion path retries.
  6535. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  6536. # Last chance before the bytes go: if this print's archive is still an empty
  6537. # fallback and something downloaded the 3MF while it ran, fill the archive in
  6538. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  6539. # below deletes the file (#2957).
  6540. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  6541. # A pending cool-off retry has nothing left to recover for — the cache is
  6542. # about to be dropped and the print is over.
  6543. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  6544. if retry_task and not retry_task.done():
  6545. retry_task.cancel()
  6546. # Drop the 3MF download cache for this printer (#972). The print is over,
  6547. # nothing else legitimately needs the bytes; keeping them would only risk
  6548. # handing a stale file to the next print if it reuses the same name.
  6549. clear_3mf_cache(printer_id)
  6550. try:
  6551. ws_data = {
  6552. "status": data.get("status"),
  6553. "filename": data.get("filename"),
  6554. "subtask_name": data.get("subtask_name"),
  6555. "timelapse_was_active": data.get("timelapse_was_active"),
  6556. }
  6557. await ws_manager.send_print_complete(printer_id, ws_data)
  6558. log_timing("WebSocket send_print_complete")
  6559. except Exception as e:
  6560. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  6561. # Capture user info before clearing (needed for print log entry)
  6562. _print_user_info = printer_manager.get_current_print_user(printer_id)
  6563. # Clear current print user tracking (Issue #206)
  6564. printer_manager.clear_current_print_user(printer_id)
  6565. # If the user explicitly stopped this print from the queue UI the printer will
  6566. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  6567. # correct "print stopped" notification/email is sent instead of a failure alert.
  6568. _raw_status = data.get("status", "completed")
  6569. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  6570. logger.info(
  6571. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  6572. _raw_status,
  6573. printer_id,
  6574. )
  6575. data = {**data, "status": "cancelled"}
  6576. _user_stopped_printers.discard(printer_id)
  6577. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  6578. # may have left material on the bed: a user can cancel ten hours into a
  6579. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  6580. # touchscreen-stop reports `aborted` rather than `cancelled` because
  6581. # `_user_stopped_printers` is only populated when the user stops via the
  6582. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  6583. # which auto-dispatched the next queued print onto a fouled bed two seconds
  6584. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  6585. # Auto Off power cycles and Bambuddy restarts.
  6586. _final_status = data.get("status", "completed")
  6587. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  6588. printer_manager.set_awaiting_plate_clear(printer_id, True)
  6589. # MQTT relay - publish print complete
  6590. try:
  6591. printer_info = printer_manager.get_printer(printer_id)
  6592. if printer_info:
  6593. await mqtt_relay.on_print_complete(
  6594. printer_id,
  6595. printer_info.name,
  6596. printer_info.serial_number,
  6597. data.get("filename", ""),
  6598. data.get("subtask_name", ""),
  6599. data.get("status", "completed"),
  6600. )
  6601. except Exception:
  6602. pass # Don't fail print complete callback if MQTT fails
  6603. filename = data.get("filename", "")
  6604. subtask_name = data.get("subtask_name", "")
  6605. if not filename and not subtask_name:
  6606. logger.warning("Print complete without filename or subtask_name")
  6607. return
  6608. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  6609. # Build list of possible keys to try (matching how they were registered in on_print_start)
  6610. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  6611. # Find the archive for this print
  6612. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  6613. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  6614. archive_id = None
  6615. for key in possible_keys:
  6616. archive_id = _active_prints.pop(key, None)
  6617. if archive_id:
  6618. logger.info("Found archive %s with key %s", archive_id, key)
  6619. # Also clean up any other keys pointing to this archive
  6620. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  6621. for k in keys_to_remove:
  6622. _active_prints.pop(k, None)
  6623. break
  6624. # The archive bound when the print started, before the name search below.
  6625. # Only this one may give the finish-photo plate restore a height (#3240):
  6626. # the search matches names by substring.
  6627. bound_archive_id = archive_id
  6628. if not archive_id:
  6629. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  6630. async with async_session() as db:
  6631. from backend.app.models.archive import PrintArchive
  6632. # Try matching by subtask_name (stored as print_name) first
  6633. if subtask_name:
  6634. result = await db.execute(
  6635. select(PrintArchive)
  6636. .where(PrintArchive.printer_id == printer_id)
  6637. .where(PrintArchive.status == "printing")
  6638. .where(
  6639. or_(
  6640. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  6641. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  6642. )
  6643. )
  6644. .order_by(PrintArchive.created_at.desc())
  6645. .limit(1)
  6646. )
  6647. archive = result.scalar_one_or_none()
  6648. if archive:
  6649. archive_id = archive.id
  6650. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  6651. # Also try by filename
  6652. if not archive_id and filename:
  6653. result = await db.execute(
  6654. select(PrintArchive)
  6655. .where(PrintArchive.printer_id == printer_id)
  6656. .where(PrintArchive.filename == filename)
  6657. .where(PrintArchive.status == "printing")
  6658. .order_by(PrintArchive.created_at.desc())
  6659. .limit(1)
  6660. )
  6661. archive = result.scalar_one_or_none()
  6662. if archive:
  6663. archive_id = archive.id
  6664. await _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger)
  6665. log_timing("SD card cleanup")
  6666. # Update queue item status early — must run before the archive_id early-return
  6667. # so queue items don't get stuck in "printing" when archive lookup fails.
  6668. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  6669. queue_item_id = None
  6670. billing_run_id: str | None = None
  6671. billing_user_id: int | None = None
  6672. billing_cost_center_id: int | None = None
  6673. billing_plate_id: int | None = None
  6674. queue_status = None
  6675. queue_auto_off = False
  6676. try:
  6677. from backend.app.core.database import run_with_retry
  6678. from backend.app.models.print_queue import PrintQueueItem
  6679. async def _update_queue_status(db):
  6680. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  6681. nonlocal queue_item_id, queue_status, queue_auto_off
  6682. result = await db.execute(
  6683. select(PrintQueueItem)
  6684. .where(PrintQueueItem.printer_id == printer_id)
  6685. .where(PrintQueueItem.status == "printing")
  6686. )
  6687. printing_items = list(result.scalars().all())
  6688. if len(printing_items) > 1:
  6689. logger.warning(
  6690. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  6691. printer_id,
  6692. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  6693. )
  6694. item = printing_items[0] if printing_items else None
  6695. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  6696. return
  6697. if item:
  6698. queue_status = data.get("status", "completed")
  6699. # MQTT sends "aborted" for cancelled prints; normalise to
  6700. # "cancelled" so it matches the queue schema Literal.
  6701. if queue_status == "aborted":
  6702. queue_status = "cancelled"
  6703. item.status = queue_status
  6704. item.completed_at = datetime.now(timezone.utc)
  6705. if queue_status == "failed" and not item.error_message:
  6706. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  6707. # Bump usage counters on the source library file so admins can
  6708. # sort by "last printed" and (eventually) auto-purge stale
  6709. # files — #1008.
  6710. await _bump_library_file_usage_if_completed(db, item, queue_status)
  6711. await db.commit()
  6712. queue_item_id = item.id
  6713. billing_run_id = item.billing_run_id
  6714. billing_user_id = item.created_by_id
  6715. billing_cost_center_id = item.cost_center_id
  6716. billing_plate_id = item.plate_id
  6717. queue_auto_off = item.auto_off_after
  6718. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  6719. await run_with_retry(_update_queue_status, label="queue status update")
  6720. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  6721. # their own sessions and have their own error handling — no retry needed.
  6722. if queue_item_id is not None:
  6723. # Batch orders (#342): this run may have been the last one an order
  6724. # owed. Re-evaluate here rather than lazily on read, so a finished
  6725. # order reports itself complete without someone opening the page.
  6726. try:
  6727. from backend.app.services.print_batch import refresh_batch_status_for_item
  6728. async with async_session() as db:
  6729. await refresh_batch_status_for_item(db, queue_item_id)
  6730. await db.commit()
  6731. except Exception as e:
  6732. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  6733. # MQTT relay - publish queue job completed
  6734. try:
  6735. printer_info = printer_manager.get_printer(printer_id)
  6736. await mqtt_relay.on_queue_job_completed(
  6737. job_id=queue_item_id,
  6738. filename=filename or subtask_name,
  6739. printer_id=printer_id,
  6740. printer_name=printer_info.name if printer_info else "Unknown",
  6741. status=queue_status,
  6742. )
  6743. except Exception:
  6744. pass # Don't fail if MQTT fails
  6745. # Check if queue is now empty and send notification
  6746. try:
  6747. from sqlalchemy import func as sa_func
  6748. async with async_session() as db:
  6749. count_result = await db.execute(
  6750. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  6751. )
  6752. pending_count = count_result.scalar() or 0
  6753. if pending_count == 0:
  6754. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  6755. completed_result = await db.execute(
  6756. select(sa_func.count(PrintQueueItem.id)).where(
  6757. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  6758. PrintQueueItem.completed_at >= today_start,
  6759. )
  6760. )
  6761. completed_count = completed_result.scalar() or 1
  6762. await notification_service.on_queue_completed(
  6763. completed_count=completed_count,
  6764. db=db,
  6765. )
  6766. except Exception:
  6767. pass # Don't fail if notification fails
  6768. # Handle auto_off_after - power off printer if the queue item opted
  6769. # in. Delegates to the smart-plug manager so the off honours each
  6770. # plug's configured strategy (time delay or temperature threshold),
  6771. # is cancelled if the printer starts printing again, and never cuts
  6772. # power on a loaded print (#1890). Previously an inline block here
  6773. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  6774. # timeout regardless of print state — cutting a touchscreen reprint.
  6775. if queue_auto_off:
  6776. try:
  6777. async with async_session() as db:
  6778. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  6779. except Exception as e:
  6780. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  6781. except Exception as e:
  6782. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  6783. log_timing("Queue item update")
  6784. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  6785. # Must run before archive_id early-return so it fires for all prints (including
  6786. # prints started from BambuStudio/touchscreen that have no archive).
  6787. if data.get("status") == "completed":
  6788. try:
  6789. from backend.app.api.routes.settings import get_setting
  6790. async with async_session() as db:
  6791. threshold_str = await get_setting(db, "bed_cooled_threshold")
  6792. threshold = float(threshold_str) if threshold_str else 35.0
  6793. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  6794. async with async_session() as db:
  6795. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  6796. if providers:
  6797. _bed_cool_waiters[printer_id] = {
  6798. "threshold": threshold,
  6799. "filename": filename or subtask_name or "",
  6800. "registered_at": time.time(),
  6801. }
  6802. logger.info(
  6803. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  6804. printer_id,
  6805. threshold,
  6806. )
  6807. else:
  6808. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  6809. except Exception as e:
  6810. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  6811. # Capture the slicer estimate before usage tracking runs. The tracker may
  6812. # update archive.cost with this run's measured cost; billing partial runs
  6813. # against that already-partial value would discount the charge twice.
  6814. billing_planned_grams: float | None = None
  6815. billing_base_cost: float | None = None
  6816. if archive_id:
  6817. try:
  6818. async with async_session() as db:
  6819. from backend.app.models.archive import PrintArchive
  6820. billing_archive = await db.get(PrintArchive, archive_id)
  6821. if billing_archive:
  6822. billing_path = (
  6823. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  6824. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  6825. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  6826. billing_archive,
  6827. billing_path,
  6828. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  6829. )
  6830. except Exception as e:
  6831. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  6832. # --- Track filament consumption (must run before archive_id early-return so usage
  6833. # is recorded even when auto-archive is disabled) ---
  6834. usage_results: list[dict] = []
  6835. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  6836. stored_ams_mapping = data.get("ams_mapping")
  6837. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  6838. if not stored_ams_mapping and archive_id:
  6839. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  6840. # Always drain the plate_id register on completion — the session already
  6841. # consumed it at print-start injection; leaving it would leak into the next
  6842. # print on the same archive_id (rare but possible with reprints) (#1697).
  6843. # Capture the popped value so the completion notification can scope the
  6844. # archive-level (summed-across-plates per #1593) filament + time totals
  6845. # down to the single plate that was actually printed (#1785).
  6846. notify_plate_id: int | None = None
  6847. if archive_id:
  6848. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  6849. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  6850. try:
  6851. async with async_session() as db:
  6852. from backend.app.api.routes.settings import get_setting
  6853. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6854. if not _spoolman_on or _spoolman_on.lower() != "true":
  6855. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  6856. async with async_session() as db:
  6857. usage_results = await usage_on_print_complete(
  6858. printer_id,
  6859. data,
  6860. printer_manager,
  6861. db,
  6862. archive_id=archive_id,
  6863. ams_mapping=stored_ams_mapping,
  6864. )
  6865. if usage_results:
  6866. await ws_manager.broadcast(
  6867. {
  6868. "type": "spool_usage_logged",
  6869. "printer_id": printer_id,
  6870. "usage": usage_results,
  6871. }
  6872. )
  6873. log_timing("Usage tracker")
  6874. except Exception as e:
  6875. logger.warning("Usage tracker on_print_complete failed: %s", e)
  6876. # Drop the print-start context unconditionally — the Spoolman branch above
  6877. # skips the internal tracker entirely, so nothing else would clear what
  6878. # print start captured, and a row surviving its print would be restored
  6879. # onto the next one after a restart.
  6880. try:
  6881. from backend.app.services.usage_tracker import discard_session
  6882. async with async_session() as db:
  6883. await discard_session(db, printer_id)
  6884. except Exception as e:
  6885. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  6886. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  6887. if archive_id:
  6888. if data.get("status") == "completed":
  6889. try:
  6890. await _report_spoolman_usage(printer_id, archive_id)
  6891. log_timing("Spoolman usage report")
  6892. except Exception as e:
  6893. logger.warning("Spoolman usage reporting failed: %s", e)
  6894. else:
  6895. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  6896. try:
  6897. async with async_session() as db:
  6898. await _cleanup_spoolman_tracking(
  6899. printer_id,
  6900. archive_id,
  6901. db,
  6902. last_layer_num=data.get("last_layer_num"),
  6903. last_progress=data.get("last_progress"),
  6904. )
  6905. except Exception as e:
  6906. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  6907. log_timing("Filament usage tracking")
  6908. if not archive_id:
  6909. # The printer's own calibration run has no archive by design, so this
  6910. # arrives here every time one finishes. Returning before the no-archive
  6911. # notification is not just noise control: that path attributes an
  6912. # unmatched completion to any queue item this printer finished in the
  6913. # last five minutes, which for a calibration that runs alongside a real
  6914. # print means emailing its owner that their print is done, twice and
  6915. # early. Everything above this point has already run — the plate-clear
  6916. # gate, the queue reconciliation, the SD-card cleanup — so only the
  6917. # notification is skipped.
  6918. if is_internal_printer_job(filename, subtask_name):
  6919. logger.info(
  6920. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  6921. filename,
  6922. subtask_name,
  6923. )
  6924. return
  6925. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  6926. # Still send print-complete/failed/stopped notifications even without an archive.
  6927. # Try to enrich with queue/library-file data so user-specific emails work too.
  6928. async def _notify_no_archive():
  6929. try:
  6930. async with async_session() as db:
  6931. from backend.app.models.library import LibraryFile
  6932. from backend.app.models.print_queue import PrintQueueItem
  6933. from backend.app.models.printer import Printer
  6934. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6935. printer_obj = result.scalar_one_or_none()
  6936. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  6937. # Try to find the most-recent queue item for this printer so we can
  6938. # recover created_by_id and estimated print time.
  6939. # NOTE: By the time this task runs the queue item status has already
  6940. # been updated to a terminal state (completed/failed/cancelled), so
  6941. # we look for recently-completed items (within the last 5 minutes).
  6942. no_archive_data: dict | None = None
  6943. try:
  6944. cutoff = datetime.now(timezone.utc) - timedelta(minutes=5)
  6945. q_result = await db.execute(
  6946. select(PrintQueueItem)
  6947. .where(PrintQueueItem.printer_id == printer_id)
  6948. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled"]))
  6949. .where(PrintQueueItem.completed_at >= cutoff)
  6950. .order_by(PrintQueueItem.completed_at.desc())
  6951. .limit(1)
  6952. )
  6953. queue_item = q_result.scalar_one_or_none()
  6954. if queue_item:
  6955. no_archive_data = {"created_by_id": queue_item.created_by_id}
  6956. # Pull estimated time from library file when available
  6957. if queue_item.library_file_id:
  6958. lib_result = await db.execute(
  6959. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  6960. )
  6961. lib_file = lib_result.scalar_one_or_none()
  6962. if lib_file and lib_file.print_time_seconds:
  6963. no_archive_data["print_time_seconds"] = lib_file.print_time_seconds
  6964. except Exception as lookup_err:
  6965. logger.debug(
  6966. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  6967. )
  6968. # Enrich with usage tracker results (captured in enclosing scope)
  6969. if usage_results:
  6970. if no_archive_data is None:
  6971. no_archive_data = {}
  6972. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  6973. if total_from_usage > 0:
  6974. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  6975. no_archive_data["usage_results"] = usage_results
  6976. # Try MQTT remaining_time for print duration when no queue/library data
  6977. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  6978. mqtt_remaining = data.get("remaining_time")
  6979. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  6980. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  6981. ps = data.get("status", "completed")
  6982. logger.info(
  6983. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  6984. )
  6985. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  6986. await notification_service.on_print_complete(
  6987. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  6988. )
  6989. else:
  6990. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  6991. # Send user-specific email if we have a created_by_id
  6992. if no_archive_data and no_archive_data.get("created_by_id"):
  6993. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  6994. await _dispatch_user_print_email(
  6995. ps,
  6996. no_archive_data["created_by_id"],
  6997. p_name,
  6998. raw_filename,
  6999. db,
  7000. )
  7001. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  7002. except Exception as e:
  7003. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  7004. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  7005. return
  7006. log_timing("Archive lookup")
  7007. # Update archive status
  7008. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  7009. try:
  7010. async with async_session() as db:
  7011. service = ArchiveService(db)
  7012. status = data.get("status", "completed")
  7013. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  7014. if hms_errors:
  7015. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  7016. failure_reason = derive_failure_reason(status, hms_errors)
  7017. if data.get("_reconciled"):
  7018. # A reconciled completion closes out a stale archive at
  7019. # reconnect — it is not a user action, so don't mislabel it
  7020. # "userCancelled". It shares the stale-cleanup path's key
  7021. # (issue #2974) and records that the real end time is unknown,
  7022. # which is also why its logged duration is 0 (#2592).
  7023. failure_reason = "noStatusUpdate"
  7024. if failure_reason:
  7025. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  7026. elif status == "failed" and hms_errors:
  7027. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  7028. await service.update_archive_status(
  7029. archive_id,
  7030. status=status,
  7031. completed_at=(
  7032. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  7033. ),
  7034. failure_reason=failure_reason,
  7035. )
  7036. logger.info(
  7037. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  7038. )
  7039. await ws_manager.send_archive_updated(
  7040. {
  7041. "id": archive_id,
  7042. "status": status,
  7043. }
  7044. )
  7045. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  7046. # MQTT relay - publish archive updated
  7047. try:
  7048. await mqtt_relay.on_archive_updated(
  7049. archive_id=archive_id,
  7050. print_name=filename or subtask_name,
  7051. status=status,
  7052. )
  7053. except Exception:
  7054. pass # Don't fail if MQTT fails
  7055. except Exception as e:
  7056. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  7057. # Continue with other operations even if archive update fails
  7058. log_timing("Archive status update")
  7059. # Apply finance wallet charge or release reservations once. For all partial
  7060. # terminal states (failed, aborted at the printer display, or cancelled via
  7061. # Bambuddy) use this run's measured spool delta, falling back to the last
  7062. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  7063. # estimate and therefore cannot represent an interrupted run.
  7064. try:
  7065. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  7066. async with async_session() as db:
  7067. from backend.app.models.archive import PrintArchive
  7068. from backend.app.services.finance_billing import apply_print_charge_for_archive
  7069. archive = await db.get(PrintArchive, archive_id)
  7070. if archive and billing_run_id is None:
  7071. billing_run_id = getattr(archive, "billing_run_id", None)
  7072. if archive and archive.created_by_id is None and _print_user_info:
  7073. archive.created_by_id = _print_user_info.get("user_id")
  7074. await db.flush()
  7075. run_status = data.get("status", "completed")
  7076. last_progress = data.get("last_progress")
  7077. if last_progress is None:
  7078. last_progress = data.get("progress")
  7079. actual_run_grams = _compute_run_filament_grams(
  7080. run_status,
  7081. billing_planned_grams,
  7082. last_progress,
  7083. usage_results,
  7084. )
  7085. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  7086. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  7087. charged = await apply_print_charge_for_archive(
  7088. db,
  7089. archive_id,
  7090. charged_user_id=billing_user_id,
  7091. cost_center_id=(
  7092. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  7093. ),
  7094. print_queue_id=queue_item_id,
  7095. print_run_id=billing_run_id,
  7096. base_cost_override=billing_base_cost,
  7097. filament_usage=filament_usage,
  7098. )
  7099. await db.commit()
  7100. if charged:
  7101. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  7102. except Exception as e:
  7103. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  7104. printer_info = printer_manager.get_printer(printer_id)
  7105. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7106. billing_filename = filename or subtask_name or "Unknown"
  7107. billing_error = str(e)
  7108. try:
  7109. await ws_manager.broadcast(
  7110. {
  7111. "type": "billing_charge_failed",
  7112. "printer_id": printer_id,
  7113. "printer_name": billing_printer_name,
  7114. "filename": billing_filename,
  7115. "archive_id": archive_id,
  7116. }
  7117. )
  7118. except Exception as notification_error:
  7119. logger.error(
  7120. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  7121. archive_id,
  7122. notification_error,
  7123. )
  7124. async def _notify_billing_charge_failed() -> None:
  7125. try:
  7126. async with async_session() as notification_db:
  7127. await notification_service.on_billing_charge_failed(
  7128. printer_id,
  7129. billing_printer_name,
  7130. billing_filename,
  7131. archive_id,
  7132. billing_error,
  7133. notification_db,
  7134. )
  7135. except Exception as provider_error:
  7136. logger.error(
  7137. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  7138. archive_id,
  7139. provider_error,
  7140. exc_info=True,
  7141. )
  7142. spawn_background_task(
  7143. _notify_billing_charge_failed(),
  7144. name=f"billing-charge-failed-{archive_id}",
  7145. )
  7146. log_timing("Finance charge update")
  7147. # Write independent print log entry (separate table, never touches archives)
  7148. try:
  7149. async with async_session() as db:
  7150. from backend.app.models.archive import PrintArchive
  7151. from backend.app.services.print_log import record_archive_wear, write_log_entry
  7152. archive = await db.get(PrintArchive, archive_id)
  7153. if archive:
  7154. # Back-fill created_by_id on reprint (#730): reprint reuses the
  7155. # source archive row rather than creating a new one, so an
  7156. # archive that was auto-created from a printer-initiated
  7157. # print (created_by_id=NULL) would otherwise stay unattributed
  7158. # forever. When we have a print-session user AND the archive
  7159. # has no attribution yet, credit the current user. Never
  7160. # overwrite an existing attribution — the original uploader
  7161. # keeps ownership.
  7162. _print_user_id = _print_user_info.get("user_id") if _print_user_info else None
  7163. if archive.created_by_id is None and _print_user_id is not None:
  7164. archive.created_by_id = _print_user_id
  7165. p_info = printer_manager.get_printer(printer_id)
  7166. # Per-run actuals — written to PrintLogEntry so stats reflect
  7167. # what THIS print actually used, not the source archive's
  7168. # first-run values (#1378). Helper handles the partial-print
  7169. # math (failed / cancelled / stopped get scaled to progress
  7170. # or to tracked spool deltas).
  7171. _run_status = data.get("status", "completed")
  7172. # #2614: scope the per-run estimate to the printed plate. For a
  7173. # multi-plate 3MF dispatched one plate at a time, the archive's
  7174. # filament/cost are the whole-file totals; the PrintLogEntry must
  7175. # reflect only this plate. No effect on single-plate archives (the
  7176. # plate estimate equals the whole-file value) or on the tracker
  7177. # path (measured spool deltas win in _compute_run_filament_grams).
  7178. _est_full_path = (
  7179. app_settings.base_dir / archive.file_path if archive.file_path else None
  7180. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7181. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path)
  7182. _run_grams = _compute_run_filament_grams(
  7183. _run_status,
  7184. _est_grams,
  7185. data.get("last_progress", data.get("progress")),
  7186. usage_results,
  7187. )
  7188. # Per-run cost — prefer usage_results sum. For partial prints
  7189. # we deliberately skip the topup-to-estimate logic in
  7190. # usage_tracker (which assumes the print completed); the raw
  7191. # tracked-spool sum is closer to what THIS run actually cost.
  7192. _run_cost: float | None = None
  7193. if usage_results:
  7194. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  7195. if _run_cost is None and _run_status == "completed":
  7196. _run_cost = _est_cost
  7197. from backend.app.models.printer import Printer as _Printer
  7198. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  7199. run_entry = await write_log_entry(
  7200. db,
  7201. archive_id=archive.id,
  7202. # Captured by _update_queue_status above; None for
  7203. # printer-initiated prints with no queue row. Batch
  7204. # cost/energy roll-up joins on it (#342).
  7205. queue_item_id=queue_item_id,
  7206. status=_run_status,
  7207. print_name=archive.print_name,
  7208. printer_name=p_info.name if p_info else None,
  7209. printer_id=printer_id,
  7210. started_at=archive.started_at,
  7211. completed_at=archive.completed_at,
  7212. filament_type=archive.filament_type,
  7213. filament_color=archive.filament_color,
  7214. filament_used_grams=_run_grams,
  7215. cost=_run_cost,
  7216. wear_cost_per_hour=_wear_rate,
  7217. failure_reason=archive.failure_reason,
  7218. thumbnail_path=archive.thumbnail_path,
  7219. created_by_id=archive.created_by_id,
  7220. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  7221. # Reconciled completions have an unknown real end time —
  7222. # log 0 duration instead of the whole disconnect gap (#2592).
  7223. reconciled=bool(data.get("_reconciled")),
  7224. )
  7225. await record_archive_wear(db, archive, run_entry)
  7226. await db.commit()
  7227. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  7228. except Exception as e:
  7229. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  7230. log_timing("Print log entry")
  7231. # Run slow operations as background tasks to avoid blocking the event loop
  7232. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  7233. async def _background_energy_calculation():
  7234. """Calculate and save energy usage in background.
  7235. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  7236. backend restart no longer loses per-print energy data).
  7237. """
  7238. try:
  7239. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  7240. async with async_session() as db:
  7241. from backend.app.models.archive import PrintArchive
  7242. archive = await db.get(PrintArchive, archive_id)
  7243. if archive is None:
  7244. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  7245. return
  7246. starting_kwh = archive.energy_start_kwh
  7247. if starting_kwh is None:
  7248. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  7249. return
  7250. candidates = await energy_plug_candidates(db, printer_id)
  7251. if not candidates:
  7252. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  7253. return
  7254. # Same ordering as the start reading, so the delta below is
  7255. # against the counter that produced `starting_kwh` (#2859).
  7256. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  7257. if selected is None:
  7258. logger.warning(
  7259. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  7260. printer_id,
  7261. ", ".join(plug.name for plug in candidates),
  7262. )
  7263. return
  7264. plug, energy = selected
  7265. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  7266. energy_used = round(energy["total"] - starting_kwh, 4)
  7267. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  7268. if energy_used < 0:
  7269. logger.warning(
  7270. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  7271. archive_id,
  7272. starting_kwh,
  7273. energy["total"],
  7274. )
  7275. return
  7276. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  7277. # Each hour of the print at the price of that hour (#1251). If
  7278. # that fails, the last price known, as before, rather than no
  7279. # energy at all. Read first: the session may be unusable after.
  7280. last_price = await stored_price(db)
  7281. try:
  7282. energy_cost_value = round(
  7283. await print_energy_cost(
  7284. db,
  7285. plug_id=archive.energy_start_plug_id,
  7286. start_at=archive.energy_start_at,
  7287. start_kwh=starting_kwh,
  7288. start_price=archive.energy_start_price,
  7289. end_kwh=energy["total"],
  7290. end_plug_id=plug.id,
  7291. price_now=await current_price(db),
  7292. ),
  7293. 3,
  7294. )
  7295. except Exception as e:
  7296. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  7297. energy_cost_value = round(energy_used * last_price, 3)
  7298. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  7299. # reprint doesn't visually clobber the source archive's energy data
  7300. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  7301. from sqlalchemy import func
  7302. from backend.app.models.print_log import PrintLogEntry
  7303. existing_runs = await db.scalar(
  7304. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  7305. )
  7306. if (existing_runs or 0) <= 1:
  7307. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  7308. # we just wrote for THIS print. Either way it's the first run.
  7309. archive.energy_kwh = energy_used
  7310. archive.energy_cost = energy_cost_value
  7311. # Backfill the latest PrintLogEntry for this archive with energy
  7312. # (write_log_entry above ran before this background task completed,
  7313. # so energy fields are still NULL on that row).
  7314. latest_run = await db.execute(
  7315. select(PrintLogEntry)
  7316. .where(PrintLogEntry.archive_id == archive_id)
  7317. .order_by(PrintLogEntry.id.desc())
  7318. .limit(1)
  7319. )
  7320. run_row = latest_run.scalar_one_or_none()
  7321. if run_row is not None:
  7322. run_row.energy_kwh = energy_used
  7323. run_row.energy_cost = energy_cost_value
  7324. await db.commit()
  7325. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  7326. except Exception as e:
  7327. logger.warning("[ENERGY-BG] Failed: %s", e)
  7328. async def _background_finish_photo() -> str | None:
  7329. """Capture finish photo in background. Returns photo filename if captured."""
  7330. # #2547: set once this function has raised the plate itself (the
  7331. # timelapse path, where the moment producer returned without doing it).
  7332. # Declared out here so the `finally` can lower it again no matter where
  7333. # the capture below fails.
  7334. plate_restored_z: float | None = None
  7335. try:
  7336. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  7337. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  7338. # Read phase: settings + printer + archive in a short session, released
  7339. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  7340. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  7341. # tens of seconds; holding this session across it pinned one pooled
  7342. # connection idle-in-transaction per finishing print (issue #2572).
  7343. async with async_session() as db:
  7344. from backend.app.api.routes.settings import get_setting
  7345. from backend.app.models.archive import PrintArchive
  7346. from backend.app.models.printer import Printer
  7347. capture_enabled = await get_setting(db, "capture_finish_photo")
  7348. if capture_enabled is not None and capture_enabled.lower() != "true":
  7349. return None
  7350. if not archive_id:
  7351. return None
  7352. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  7353. archive = (
  7354. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7355. ).scalar_one_or_none()
  7356. if not printer or not archive:
  7357. return None
  7358. import uuid
  7359. from datetime import datetime
  7360. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  7361. if not archive.file_path:
  7362. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  7363. archive_dir = resolve_archive_dir(archive)
  7364. photo_filename = None
  7365. # Prefer the timelapse last-frame source when a timelapse was
  7366. # recording — it captures the moment after the toolhead parks
  7367. # but before the bed drops, which the live-camera grab below
  7368. # would miss (#1397). Skipped for external cameras (those have
  7369. # their own framing and don't see a Bambu timelapse). Only
  7370. # runs when the USER explicitly enabled timelapse for this
  7371. # print — #1721 removed Bambuddy's force-on at dispatch
  7372. # because it caused per-layer nozzle parking on Smooth-mode
  7373. # slicer profiles.
  7374. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  7375. printer.external_camera_enabled and printer.external_camera_url
  7376. )
  7377. timelapse_still_pending = False
  7378. if prefer_timelapse_source:
  7379. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  7380. archive_id=archive_id,
  7381. archive_dir=archive_dir,
  7382. rotation=getattr(printer, "camera_rotation", 0),
  7383. )
  7384. # #1721: replacement framing path — on_finish_photo_moment
  7385. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  7386. # parked, bed not yet dropped) and cached the JPEG bytes in
  7387. # _stage22_finish_frames. Consume them now so the saved photo
  7388. # has the better framing instead of the post-bed-drop angle
  7389. # the live-camera fallback below would give.
  7390. if not photo_filename:
  7391. # #1790: on the FINISH-state fallback path the producer
  7392. # task is dispatched back-to-back with this consumer, so
  7393. # a bare pop would race past with an empty result and
  7394. # the RTSP fallback below would collide with the
  7395. # producer's still-in-flight grab (single-client RTSP
  7396. # on Bambu printers). Wait for the producer to finish
  7397. # or give up before touching the cache.
  7398. #
  7399. # #2547: 20s was enough when the producer only ever grabbed a
  7400. # frame. It now also raises the plate first, which costs the
  7401. # settle window before the grab even starts — so the budget has
  7402. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  7403. # under the notification's own photo wait below.
  7404. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  7405. if in_flight is not None:
  7406. try:
  7407. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  7408. except asyncio.TimeoutError:
  7409. logger.warning(
  7410. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  7411. printer_id,
  7412. )
  7413. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  7414. if cached_frame:
  7415. # Already rotated by the producer (#2708) — rotating again
  7416. # here would undo the fix on the banked-frame path, whose
  7417. # bytes reach the cache having been rotated once already.
  7418. photos_dir = archive_dir / "photos"
  7419. photos_dir.mkdir(parents=True, exist_ok=True)
  7420. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7421. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7422. photo_path = photos_dir / photo_filename
  7423. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  7424. logger.info(
  7425. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  7426. photo_filename,
  7427. len(cached_frame),
  7428. )
  7429. # #2547: the timelapse path reaches the live grab below whenever the
  7430. # video hasn't landed in time — the documented usual outcome on
  7431. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  7432. # returned early for those prints without raising the plate, so
  7433. # without this the photo that actually ships in the notification is
  7434. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  7435. # asked us to fix. The archive still gets the better video frame
  7436. # later; this is about the image the user is sent.
  7437. #
  7438. # Gated on `timelapse_was_active` precisely because that is the
  7439. # condition under which the producer skipped. On every other path it
  7440. # has already raised and lowered the plate, and repeating that here
  7441. # would be a second pointless round trip.
  7442. if (
  7443. not photo_filename
  7444. and data.get("timelapse_was_active")
  7445. and not print_dispatch_context.end_gcode_injected(printer_id)
  7446. ):
  7447. try:
  7448. async with async_session() as db:
  7449. from backend.app.api.routes.settings import get_setting
  7450. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7451. if restore_setting is None or restore_setting.lower() == "true":
  7452. max_z = await _max_z_for_current_print(
  7453. printer_id, data, logger, bound_archive_id, notify_plate_id
  7454. )
  7455. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  7456. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  7457. plate_restored_z = max_z
  7458. except Exception as e:
  7459. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  7460. # Fallback chain: external camera → buffered live frame →
  7461. # fresh RTSP capture. Only runs if the timelapse path above
  7462. # didn't already produce a photo.
  7463. # Chamber light for the live capture below (#1655).
  7464. async with camera_light(printer if not photo_filename else None):
  7465. if not photo_filename:
  7466. if printer.external_camera_enabled and printer.external_camera_url:
  7467. logger.info("[PHOTO-BG] Using external camera")
  7468. from backend.app.api.routes.camera import live_frame_for_capture
  7469. from backend.app.services.external_camera import capture_frame
  7470. # #2707: the second half of the finish-photo failure — the
  7471. # pre-capture and this fallback both collided with the live
  7472. # view. None here continues down the fallback chain.
  7473. defer, buffered = live_frame_for_capture(printer_id)
  7474. if defer:
  7475. frame_data = buffered
  7476. else:
  7477. frame_data = await capture_frame(
  7478. printer.external_camera_url,
  7479. printer.external_camera_type or "mjpeg",
  7480. snapshot_url=printer.external_camera_snapshot_url,
  7481. )
  7482. if frame_data:
  7483. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  7484. photos_dir = archive_dir / "photos"
  7485. photos_dir.mkdir(parents=True, exist_ok=True)
  7486. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7487. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7488. photo_path = photos_dir / photo_filename
  7489. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  7490. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  7491. else:
  7492. # Check if camera stream is active - use buffered frame to avoid freeze
  7493. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  7494. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  7495. active_chamber_for_printer = [
  7496. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  7497. ]
  7498. buffered_frame = get_buffered_frame(printer_id)
  7499. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  7500. # Use frame from active stream
  7501. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  7502. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  7503. photos_dir = archive_dir / "photos"
  7504. photos_dir.mkdir(parents=True, exist_ok=True)
  7505. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7506. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7507. photo_path = photos_dir / photo_filename
  7508. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  7509. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  7510. else:
  7511. # No active stream - capture new frame
  7512. from backend.app.services.camera import capture_finish_photo
  7513. photo_filename = await capture_finish_photo(
  7514. printer_id=printer_id,
  7515. ip_address=printer.ip_address,
  7516. access_code=printer.access_code,
  7517. model=printer.model,
  7518. archive_dir=archive_dir,
  7519. rotation=getattr(printer, "camera_rotation", 0),
  7520. )
  7521. # Write phase: attach the photo in a fresh short-lived session.
  7522. if photo_filename:
  7523. async with async_session() as db:
  7524. from backend.app.models.archive import PrintArchive
  7525. arch = await db.get(PrintArchive, archive_id)
  7526. if arch is not None:
  7527. photos = arch.photos or []
  7528. photos.append(photo_filename)
  7529. arch.photos = photos
  7530. await db.commit()
  7531. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  7532. # The short wait above is bounded so a slow printer can't hold up
  7533. # the print-complete notification, which is what the caller is
  7534. # blocking on. When it ran out with the video still on its way,
  7535. # keep waiting off to the side and add the better frame to the
  7536. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  7537. # users, whose videos routinely take minutes to transfer, never get
  7538. # the pre-bed-drop framing this path exists to provide.
  7539. #
  7540. # Spawned here rather than at the point the wait gave up: both this
  7541. # function and the upgrade do a read-modify-write on `photos`, and
  7542. # the live-camera fallback above can take tens of seconds. Starting
  7543. # the upgrade before that write means the two can interleave and one
  7544. # silently drops the other's entry, leaving a JPEG on disk that the
  7545. # gallery never lists.
  7546. if timelapse_still_pending:
  7547. spawn_background_task(
  7548. _upgrade_finish_photo_from_timelapse(
  7549. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  7550. ),
  7551. name=f"finish-photo-upgrade-{archive_id}",
  7552. )
  7553. return photo_filename
  7554. except Exception as e:
  7555. logger.warning("[PHOTO-BG] Failed: %s", e)
  7556. return None
  7557. finally:
  7558. # #2547: we raised the plate, so we owe the move back down — even if
  7559. # the capture in between threw. Otherwise the user finds the print
  7560. # pinned under the nozzle.
  7561. if plate_restored_z is not None:
  7562. try:
  7563. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  7564. except Exception as e:
  7565. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7566. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  7567. # Photo capture task - result will be used by notifications
  7568. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  7569. log_timing("Background tasks scheduled (energy, photo)")
  7570. # Also run smart plug, notifications, and maintenance as background tasks
  7571. print_status = data.get("status", "completed")
  7572. async def _background_smart_plug():
  7573. """Handle smart plug automation in background."""
  7574. try:
  7575. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  7576. async with async_session() as db:
  7577. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  7578. logger.info("[AUTO-OFF-BG] Completed")
  7579. except Exception as e:
  7580. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  7581. async def _background_notifications(finish_photo_filename: str | None = None):
  7582. """Send print complete notifications in background."""
  7583. try:
  7584. logger.info(
  7585. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  7586. )
  7587. async with async_session() as db:
  7588. from backend.app.models.archive import PrintArchive
  7589. from backend.app.models.printer import Printer
  7590. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7591. printer = result.scalar_one_or_none()
  7592. printer_name = printer.name if printer else f"Printer {printer_id}"
  7593. archive_data = None
  7594. if archive_id:
  7595. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7596. archive = archive_result.scalar_one_or_none()
  7597. if archive:
  7598. # Actual elapsed time from started_at/completed_at when both are
  7599. # populated (every terminal status sets completed_at after #1198).
  7600. # Falls back to None so the notification path can decide whether to
  7601. # render the slicer estimate as a last resort.
  7602. actual_time_seconds = None
  7603. if archive.started_at and archive.completed_at:
  7604. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  7605. if elapsed > 0:
  7606. actual_time_seconds = int(elapsed)
  7607. archive_data = {
  7608. "print_time_seconds": archive.print_time_seconds,
  7609. "actual_time_seconds": actual_time_seconds,
  7610. "actual_filament_grams": archive.filament_used_grams,
  7611. "failure_reason": archive.failure_reason,
  7612. "created_by_id": archive.created_by_id,
  7613. }
  7614. # Scale filament usage for partial prints
  7615. if print_status != "completed" and archive.filament_used_grams:
  7616. progress = data.get("progress") or 0
  7617. scale = _partial_progress_scale(progress)
  7618. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  7619. archive_data["progress"] = progress
  7620. # Pass per-slot data from archive.extra_data
  7621. if archive.extra_data and archive.extra_data.get("filament_slots"):
  7622. slots = archive.extra_data["filament_slots"]
  7623. if print_status != "completed":
  7624. scale = _partial_progress_scale(data.get("progress"))
  7625. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  7626. archive_data["filament_slots"] = slots
  7627. # Scope project-summed totals down to the plate that was
  7628. # actually printed — see _scope_notification_archive_data_to_plate
  7629. # for the why (#1785).
  7630. archive_data = _scope_notification_archive_data_to_plate(
  7631. archive_data,
  7632. archive.file_path,
  7633. notify_plate_id,
  7634. print_status,
  7635. data.get("progress"),
  7636. app_settings.base_dir,
  7637. )
  7638. # Enrich filament_grams from usage_results when archive has no 3MF data
  7639. if not archive_data.get("actual_filament_grams") and usage_results:
  7640. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7641. if total_from_usage > 0:
  7642. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7643. # Pass usage tracker results for AMS slot info in notifications
  7644. if usage_results:
  7645. archive_data["usage_results"] = usage_results
  7646. # Add finish photo URL and image bytes if available
  7647. if finish_photo_filename:
  7648. photo_url, photo_bytes = await _finish_photo_for_notification(
  7649. db, archive, archive_id, finish_photo_filename
  7650. )
  7651. if photo_url:
  7652. archive_data["finish_photo_url"] = photo_url
  7653. if photo_bytes:
  7654. archive_data["image_data"] = photo_bytes
  7655. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7656. await notification_service.on_print_complete(
  7657. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  7658. )
  7659. else:
  7660. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7661. # Post-print outcome confirmation (#1898). Runs in this
  7662. # background task so the finish photo fetched above rides
  7663. # along with the prompt.
  7664. if print_status == "completed" and archive_id:
  7665. await _dispatch_outcome_confirmation_safely(
  7666. db, printer_id, printer_name, data, archive_id, archive_data
  7667. )
  7668. # Send user-specific email notification
  7669. if archive_data:
  7670. created_by_id = archive_data.get("created_by_id")
  7671. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7672. await _dispatch_user_print_email(
  7673. print_status,
  7674. created_by_id,
  7675. printer_name,
  7676. raw_filename,
  7677. db,
  7678. image_data=archive_data.get("image_data"),
  7679. finish_photo_url=archive_data.get("finish_photo_url"),
  7680. )
  7681. logger.info("[NOTIFY-BG] Completed")
  7682. except Exception as e:
  7683. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  7684. async def _background_maintenance_check():
  7685. """Check for maintenance due in background."""
  7686. if print_status != "completed":
  7687. return
  7688. try:
  7689. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  7690. async with async_session() as db:
  7691. from backend.app.models.printer import Printer
  7692. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7693. printer = result.scalar_one_or_none()
  7694. printer_name = printer.name if printer else f"Printer {printer_id}"
  7695. await ensure_default_types(db)
  7696. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  7697. items_needing_attention = [
  7698. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  7699. for item in overview.maintenance_items
  7700. if item.enabled and (item.is_due or item.is_warning)
  7701. ]
  7702. if items_needing_attention:
  7703. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  7704. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  7705. # MQTT relay - publish maintenance alerts
  7706. for item in items_needing_attention:
  7707. try:
  7708. await mqtt_relay.on_maintenance_alert(
  7709. printer_id=printer_id,
  7710. printer_name=printer_name,
  7711. maintenance_type=item["name"],
  7712. current_value=0, # Not easily available here
  7713. threshold=0, # Not easily available here
  7714. )
  7715. except Exception:
  7716. pass # Don't fail if MQTT fails
  7717. else:
  7718. logger.info("[MAINT-BG] Completed (no items need attention)")
  7719. except Exception as e:
  7720. logger.warning("[MAINT-BG] Failed: %s", e)
  7721. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  7722. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  7723. # Notification task waits for photo capture to complete first (with timeout).
  7724. # When a timelapse was recording, photo sourcing polls the per-print
  7725. # timelapse for up to 60s (#1397) — extend the budget so the notification
  7726. # carries the correct bed-up photo instead of falling through to the
  7727. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  7728. #
  7729. # #2547: both budgets now have to cover a plate restore as well.
  7730. #
  7731. # Without timelapse, the wait is on the moment producer, which raises the
  7732. # plate before its grab — so this has to outlast that producer's own budget.
  7733. #
  7734. # With timelapse, the capture polls up to
  7735. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  7736. # falls back to a live grab, which is the case that raises the plate. At the
  7737. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  7738. # restore would have moved the plate for a photo nobody waited for.
  7739. photo_wait_timeout = (
  7740. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  7741. if data.get("timelapse_was_active")
  7742. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  7743. )
  7744. async def _photo_then_notify():
  7745. """Wait for photo capture, then send notification with photo URL."""
  7746. finish_photo = None
  7747. try:
  7748. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  7749. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  7750. except TimeoutError:
  7751. logger.warning(
  7752. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  7753. photo_wait_timeout,
  7754. )
  7755. except Exception as e:
  7756. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  7757. try:
  7758. await _background_notifications(finish_photo)
  7759. except Exception as e:
  7760. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  7761. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  7762. # Stitch external camera layer timelapse if session was active
  7763. print_status = data.get("status", "completed")
  7764. async def _background_layer_timelapse():
  7765. """Stitch layer timelapse and attach to archive."""
  7766. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  7767. try:
  7768. if print_status == "completed":
  7769. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  7770. timelapse_path = await tl_complete(printer_id)
  7771. if timelapse_path and archive_id:
  7772. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  7773. async with async_session() as db:
  7774. service = ArchiveService(db)
  7775. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  7776. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  7777. # Clean up the temp file
  7778. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  7779. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  7780. elif timelapse_path:
  7781. # Timelapse created but no archive - just clean up
  7782. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  7783. else:
  7784. # Print failed or cancelled - cancel timelapse session
  7785. cancel_session(printer_id)
  7786. logger.info(
  7787. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  7788. )
  7789. except Exception as e:
  7790. logger.warning("[LAYER-TL] Failed: %s", e)
  7791. # Try to cancel session on error
  7792. try:
  7793. cancel_session(printer_id)
  7794. except Exception:
  7795. pass # Best-effort timelapse session cancellation on error
  7796. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  7797. log_timing("All background tasks scheduled")
  7798. # Auto-scan for timelapse if recording was active during the print
  7799. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  7800. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  7801. # Schedule timelapse scan as background task with retries
  7802. # The printer needs time to encode the video after print completion
  7803. baseline = _timelapse_baselines.pop(printer_id, None)
  7804. spawn_background_task(
  7805. _scan_for_timelapse_with_retries(archive_id, baseline),
  7806. name=f"scan-timelapse-{archive_id}",
  7807. )
  7808. log_timing("Timelapse scan scheduled")
  7809. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  7810. # AMS sensor history recording
  7811. _ams_history_task: asyncio.Task | None = None
  7812. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  7813. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  7814. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  7815. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  7816. _ams_alarm_cooldown: dict[str, datetime] = {}
  7817. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  7818. # (printer_id, ams_id) already reported as sending the drop index and no
  7819. # percentage. Logged once each so a supported printer that turns out to do this
  7820. # shows up in a support bundle rather than as a user wondering where the
  7821. # humidity reading went -- see the note at the read site below (#3140).
  7822. _ams_index_only_logged: set[tuple[int, int]] = set()
  7823. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  7824. """Temperature at which the AMS alarm fires, falling back to the display band.
  7825. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  7826. when a notification was sent as well, which is why a room above it made the
  7827. alarm fire once an hour for as long as the weather lasted -- and the only way
  7828. to stop that was to raise the display band and lose the colour that says the
  7829. unit is warm (#2905).
  7830. Unset resolves to the fair threshold, so an install that never sets one is
  7831. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  7832. so that arrives here as a string and is handled by the same branch as any
  7833. other unparseable value -- there is no separate sentinel to keep in sync.
  7834. A non-positive value is refused rather than honoured: zero would alarm
  7835. permanently, and it is far more likely to be a cleared field than a
  7836. deliberate choice.
  7837. """
  7838. if raw_alarm_value is None:
  7839. return fair_threshold
  7840. try:
  7841. value = float(raw_alarm_value)
  7842. except (TypeError, ValueError):
  7843. return fair_threshold
  7844. if not math.isfinite(value) or value <= 0:
  7845. return fair_threshold
  7846. return value
  7847. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  7848. # through a cycle and the cool-down after it (#1802). Stored in the settings
  7849. # table rather than alongside _ams_alarm_cooldown above, because a restart
  7850. # partway through a cool-down would otherwise resume alarming about heat the
  7851. # user asked for — the same internal-timestamp-row pattern as
  7852. # support.py's debug_logging_enabled_at.
  7853. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  7854. # Upper bound on that suppression. The latch normally clears as soon as the unit
  7855. # reads at or below the threshold; see utils.ams_drying for why this cap only
  7856. # matters when it never does.
  7857. AMS_DRYING_GRACE_MINUTES = 120
  7858. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  7859. """Read the persisted per-AMS drying latch, dropping entries out of window.
  7860. Anything older than the grace cap would expire on its next visit anyway, so
  7861. discarding it here costs nothing and stops rows for deleted printers from
  7862. accumulating.
  7863. Stamps ahead of now get two defences, because a box whose clock jumps
  7864. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  7865. ones are discarded outright, and the rest are clamped to now. Without the
  7866. clamp the cap would measure from a moment that has not happened yet and hold
  7867. the alarm quiet for the skew on top of the cap. One unnecessary notification
  7868. after a clock jump is a far better failure than an alarm silently disabled
  7869. for hours.
  7870. """
  7871. from backend.app.models.settings import Settings
  7872. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  7873. setting = result.scalar_one_or_none()
  7874. if not setting or not setting.value:
  7875. return {}
  7876. try:
  7877. raw = json.loads(setting.value)
  7878. except (ValueError, TypeError):
  7879. return {} # Corrupted row → no latch, alarms behave as they did before
  7880. if not isinstance(raw, dict):
  7881. return {}
  7882. now = datetime.now(timezone.utc)
  7883. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  7884. latch: dict[str, datetime] = {}
  7885. for key, value in raw.items():
  7886. try:
  7887. stamp = datetime.fromisoformat(str(value))
  7888. except (ValueError, TypeError):
  7889. continue
  7890. if stamp.tzinfo is None:
  7891. stamp = stamp.replace(tzinfo=timezone.utc)
  7892. if not (now - window <= stamp <= now + window):
  7893. continue
  7894. # Nothing may sit in the future: suppression is measured as now minus
  7895. # the stamp, so a stamp ahead of now would extend it by the skew on top
  7896. # of the cap. Clamping the survivors keeps the cap an actual cap.
  7897. latch[str(key)] = min(stamp, now)
  7898. return latch
  7899. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  7900. """Persist the latch, writing only when it actually changed.
  7901. Adds the session change but does not commit — the caller's own commit
  7902. carries it, so the latch lands in the same transaction as the sensor rows
  7903. that produced it.
  7904. """
  7905. from backend.app.models.settings import Settings
  7906. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  7907. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  7908. setting = result.scalar_one_or_none()
  7909. if setting is None:
  7910. # Don't create the row on installs that never dry anything.
  7911. if payload != "{}":
  7912. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  7913. elif setting.value != payload:
  7914. setting.value = payload
  7915. def _ams_has_filament(ams_data: dict) -> bool:
  7916. """True if this AMS unit has at least one tray slot holding filament.
  7917. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  7918. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  7919. still report sensor readings, but those readings are ambient and not
  7920. actionable: no filament to dry, no humidity to push down. #1619 — gate
  7921. humidity/temperature alarms on this check so empty units don't generate
  7922. hourly noise. Sensor history still records regardless so the UI charts
  7923. stay continuous.
  7924. Fallback path inspects the `tray` array's `tray_type` fields for setups
  7925. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  7926. """
  7927. bits = ams_data.get("tray_exist_bits")
  7928. if isinstance(bits, str) and bits.strip():
  7929. try:
  7930. return int(bits, 16) > 0
  7931. except ValueError:
  7932. pass
  7933. trays = ams_data.get("tray")
  7934. if isinstance(trays, list):
  7935. return any(
  7936. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  7937. )
  7938. return False
  7939. async def record_ams_history():
  7940. """Background task to record AMS humidity and temperature data."""
  7941. logger = logging.getLogger(__name__)
  7942. # Wait a short time for MQTT connections to establish on startup
  7943. await asyncio.sleep(10)
  7944. while True:
  7945. try:
  7946. from backend.app.models.ams_history import AMSSensorHistory
  7947. from backend.app.models.printer import Printer
  7948. from backend.app.models.settings import Settings
  7949. async with async_session() as db:
  7950. # Get all active printers
  7951. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  7952. printers = result.scalars().all()
  7953. # Get alarm thresholds from settings
  7954. humidity_threshold = 60.0 # Default: fair threshold
  7955. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  7956. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  7957. setting = result.scalar_one_or_none()
  7958. if setting:
  7959. try:
  7960. humidity_threshold = float(setting.value)
  7961. except (ValueError, TypeError):
  7962. pass # Keep default threshold if stored value is invalid
  7963. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  7964. setting = result.scalar_one_or_none()
  7965. if setting:
  7966. try:
  7967. temp_fair_threshold = float(setting.value)
  7968. except (ValueError, TypeError):
  7969. pass # Keep default threshold if stored value is invalid
  7970. # The alarm gets its own threshold, seeded from the resolved fair
  7971. # value so an install that has never set one behaves exactly as
  7972. # it did before (#2905). ams_temp_fair decides when the card turns
  7973. # amber; 35 C is a reasonable place to change a colour and not a
  7974. # reasonable place to page someone. A room above it makes the
  7975. # alarm fire once an hour for as long as the weather lasts, and
  7976. # the only way to stop it was to raise the display band and lose
  7977. # the colour that says the unit is warm.
  7978. #
  7979. # An unset value is stored as the literal "None", which the except
  7980. # below swallows the same way it swallows garbage -- so the
  7981. # fallback costs nothing and needs no sentinel of its own.
  7982. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  7983. setting = result.scalar_one_or_none()
  7984. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  7985. temp_fair_threshold, setting.value if setting else None
  7986. )
  7987. # Per-filament humidity threshold overrides (#1605) — resolved
  7988. # per-AMS below from the loaded tray types. Reuses the same
  7989. # resolver as the auto-drying scheduler so behavior stays in
  7990. # lockstep across both consumers.
  7991. from backend.app.services.print_scheduler import PrintScheduler
  7992. per_type_humidity_thresholds: dict[str, int] = {}
  7993. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  7994. setting = result.scalar_one_or_none()
  7995. if setting and setting.value:
  7996. try:
  7997. raw = json.loads(setting.value)
  7998. if isinstance(raw, dict):
  7999. for k, v in raw.items():
  8000. try:
  8001. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  8002. v
  8003. )
  8004. except (TypeError, ValueError):
  8005. continue
  8006. except (ValueError, TypeError):
  8007. pass # Invalid JSON → no overrides, fall through to global threshold
  8008. # Per-AMS drying latch (#1802), loaded once per pass and written
  8009. # back below only if a unit changed it.
  8010. drying_latch = await _load_ams_drying_latch(db)
  8011. drying_latch_before = dict(drying_latch)
  8012. recorded_count = 0
  8013. for printer in printers:
  8014. # Get current state from printer manager
  8015. state = printer_manager.get_status(printer.id)
  8016. if not state or not state.connected or not state.raw_data:
  8017. continue # Skip disconnected printers - don't use stale data
  8018. raw_data = state.raw_data
  8019. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  8020. continue
  8021. # Record data for each AMS unit
  8022. for ams_data in raw_data["ams"]:
  8023. ams_id = int(ams_data.get("id", 0))
  8024. # Percentage only. The 1-5 index is inverted, so
  8025. # charting it as a percentage drew the wettest units as
  8026. # the driest (#3140); a unit that reports no percentage
  8027. # leaves a gap in the chart instead. See
  8028. # utils/ams_humidity.
  8029. humidity = ams_humidity_percent(ams_data)
  8030. # No supported printer is known to send the index
  8031. # alone -- the report came from unsupported firmware,
  8032. # and no install has been seen using the old fallback.
  8033. # "Known" is doing work there, so say so once per unit:
  8034. # the alternative is a silent blank card.
  8035. if humidity is None and ams_data.get("humidity") is not None:
  8036. unit_key = (printer.id, ams_id)
  8037. if unit_key not in _ams_index_only_logged:
  8038. _ams_index_only_logged.add(unit_key)
  8039. logger.info(
  8040. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  8041. "percentage. The index is inverted and is not shown as a percentage "
  8042. "(#3140), so this unit has no humidity reading, chart or alarm. "
  8043. "Please report this with the printer and AMS firmware versions.",
  8044. printer.name,
  8045. ams_id,
  8046. )
  8047. # Get temperature
  8048. temperature = None
  8049. temp_str = ams_data.get("temp")
  8050. if temp_str is not None:
  8051. try:
  8052. temperature = float(temp_str)
  8053. except (ValueError, TypeError):
  8054. pass # Skip unparseable temperature value
  8055. # Skip if no data
  8056. if humidity is None and temperature is None:
  8057. continue
  8058. # Record the data point
  8059. history = AMSSensorHistory(
  8060. printer_id=printer.id,
  8061. ams_id=ams_id,
  8062. humidity=humidity,
  8063. # Both columns hold the same reading now that the
  8064. # index can no longer reach ``humidity``. Writing it
  8065. # through the same value also stops a genuine 0%
  8066. # from being stored as NULL, which the old truthiness
  8067. # test did.
  8068. humidity_raw=humidity,
  8069. temperature=temperature,
  8070. )
  8071. db.add(history)
  8072. recorded_count += 1
  8073. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  8074. is_ams_ht = ams_id >= 128
  8075. if is_ams_ht:
  8076. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  8077. else:
  8078. ams_label = f"AMS-{chr(65 + ams_id)}"
  8079. # Skip alarm dispatch for empty AMS units — humidity /
  8080. # temperature readings are ambient with no filament to
  8081. # protect, and the hourly notification just becomes
  8082. # noise. Sensor history was already recorded above so
  8083. # the UI charts stay continuous (#1619). Per-AMS check
  8084. # so a multi-AMS setup with one loaded + one empty
  8085. # still alarms on the loaded unit.
  8086. if not _ams_has_filament(ams_data):
  8087. continue
  8088. # Resolve per-filament humidity threshold for this AMS
  8089. # unit (#1605). Falls back to the global ams_humidity_fair
  8090. # when no per-type overrides are configured.
  8091. trays = ams_data.get("tray", []) or []
  8092. effective_humidity_threshold = float(
  8093. PrintScheduler.resolve_humidity_threshold(
  8094. trays, per_type_humidity_thresholds, int(humidity_threshold)
  8095. )
  8096. )
  8097. # Check humidity alarm (only if above threshold)
  8098. if humidity is not None and humidity > effective_humidity_threshold:
  8099. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  8100. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8101. now = datetime.now(timezone.utc)
  8102. if (
  8103. last_alarm is None
  8104. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8105. ):
  8106. _ams_alarm_cooldown[cooldown_key] = now
  8107. logger.info(
  8108. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  8109. )
  8110. try:
  8111. # Call different notification method based on AMS type
  8112. if is_ams_ht:
  8113. await notification_service.on_ams_ht_humidity_high(
  8114. printer.id,
  8115. printer.name,
  8116. ams_label,
  8117. humidity,
  8118. effective_humidity_threshold,
  8119. db,
  8120. )
  8121. else:
  8122. await notification_service.on_ams_humidity_high(
  8123. printer.id,
  8124. printer.name,
  8125. ams_label,
  8126. humidity,
  8127. effective_humidity_threshold,
  8128. db,
  8129. )
  8130. except Exception as e:
  8131. logger.warning("Failed to send humidity alarm: %s", e)
  8132. # A drying cycle heats the unit far past ams_temp_fair on
  8133. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  8134. # AMS-HT, against a 35 C default — so the alarm fired
  8135. # once an hour for the whole cycle and kept firing while
  8136. # the unit cooled back down (#1802). Latch on the
  8137. # firmware's own drying state and hold until the reading
  8138. # returns to normal. Humidity is deliberately left alone:
  8139. # it falls during drying, which is the whole point.
  8140. latch_key = f"{printer.id}:{ams_id}"
  8141. # The latch releases at `threshold`, so it takes the alarm
  8142. # number too. Handing it the display band would strand the
  8143. # latch on any unit that settles back above it -- a room
  8144. # where the AMS rests at 37.7 C never returns under a 35 C
  8145. # band, so the latch could only expire on the grace cap
  8146. # rather than releasing when the unit had actually cooled.
  8147. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  8148. drying_active=is_drying_active(ams_data),
  8149. temperature=temperature,
  8150. threshold=temp_alarm_threshold,
  8151. latched_at=drying_latch.get(latch_key),
  8152. now=datetime.now(timezone.utc),
  8153. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  8154. )
  8155. if new_latch is None:
  8156. drying_latch.pop(latch_key, None)
  8157. else:
  8158. drying_latch[latch_key] = new_latch
  8159. # Check temperature alarm (only if above threshold)
  8160. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  8161. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  8162. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8163. now = datetime.now(timezone.utc)
  8164. if (
  8165. last_alarm is None
  8166. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8167. ):
  8168. _ams_alarm_cooldown[cooldown_key] = now
  8169. logger.info(
  8170. f"Sending temperature alarm for {printer.name} {ams_label}: "
  8171. f"{temperature}°C > {temp_alarm_threshold}°C"
  8172. )
  8173. try:
  8174. # Call different notification method based on AMS type
  8175. if is_ams_ht:
  8176. # The reported threshold has to be the one
  8177. # that fired, or the message says "> 35 °C"
  8178. # while firing at 45.
  8179. await notification_service.on_ams_ht_temperature_high(
  8180. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8181. )
  8182. else:
  8183. await notification_service.on_ams_temperature_high(
  8184. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8185. )
  8186. except Exception as e:
  8187. logger.warning("Failed to send temperature alarm: %s", e)
  8188. if drying_latch != drying_latch_before:
  8189. await _save_ams_drying_latch(db, drying_latch)
  8190. await db.commit()
  8191. if recorded_count > 0:
  8192. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  8193. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  8194. global _ams_cleanup_counter
  8195. _ams_cleanup_counter += 1
  8196. if _ams_cleanup_counter >= 288:
  8197. _ams_cleanup_counter = 0
  8198. # Get retention days from settings
  8199. from backend.app.models.settings import Settings
  8200. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  8201. setting = result.scalar_one_or_none()
  8202. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  8203. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8204. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  8205. await db.commit()
  8206. if result.rowcount > 0:
  8207. logger.info(
  8208. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  8209. )
  8210. # Wait until next recording interval
  8211. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  8212. except asyncio.CancelledError:
  8213. break
  8214. except Exception as e:
  8215. logger.warning("AMS history recording failed: %s", e)
  8216. await asyncio.sleep(60) # Wait a bit before retrying
  8217. def start_ams_history_recording():
  8218. """Start the AMS history recording background task."""
  8219. global _ams_history_task
  8220. if _ams_history_task is None:
  8221. _ams_history_task = asyncio.create_task(record_ams_history())
  8222. logging.getLogger(__name__).info("AMS history recording started")
  8223. def stop_ams_history_recording():
  8224. """Stop the AMS history recording background task."""
  8225. global _ams_history_task
  8226. if _ams_history_task:
  8227. _ams_history_task.cancel()
  8228. _ams_history_task = None
  8229. logging.getLogger(__name__).info("AMS history recording stopped")
  8230. # Printer sensor history recording (nozzle / bed / chamber)
  8231. _printer_sensor_history_task: asyncio.Task | None = None
  8232. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  8233. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  8234. _printer_sensor_cleanup_counter = 0
  8235. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  8236. # MQTT parser writes, so we don't need to handle per-model field aliases here
  8237. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  8238. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  8239. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  8240. _SENSOR_TARGET_KEYS = {
  8241. "nozzle": "nozzle_target",
  8242. "nozzle_2": "nozzle_2_target",
  8243. "bed": "bed_target",
  8244. "chamber": "chamber_target",
  8245. }
  8246. async def record_printer_sensor_history():
  8247. """Background task to record nozzle / bed / chamber readings.
  8248. Pulls from `state.temperatures` (already normalised across all printer
  8249. models by the MQTT parser) rather than re-parsing raw_data, so we get
  8250. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  8251. """
  8252. logger = logging.getLogger(__name__)
  8253. await asyncio.sleep(10)
  8254. while True:
  8255. try:
  8256. from backend.app.models.printer import Printer
  8257. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  8258. from backend.app.models.settings import Settings
  8259. async with async_session() as db:
  8260. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8261. printers = result.scalars().all()
  8262. recorded_count = 0
  8263. for printer in printers:
  8264. state = printer_manager.get_status(printer.id)
  8265. if not state or not state.connected:
  8266. continue
  8267. temps = getattr(state, "temperatures", None) or {}
  8268. if not isinstance(temps, dict):
  8269. continue
  8270. for kind in _SENSOR_KINDS:
  8271. if kind not in temps:
  8272. continue
  8273. try:
  8274. value = float(temps[kind])
  8275. except (ValueError, TypeError):
  8276. continue
  8277. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  8278. target_val: float | None = None
  8279. if target_raw is not None:
  8280. try:
  8281. target_val = float(target_raw)
  8282. except (ValueError, TypeError):
  8283. target_val = None
  8284. db.add(
  8285. PrinterSensorHistory(
  8286. printer_id=printer.id,
  8287. sensor_kind=kind,
  8288. value=value,
  8289. target=target_val,
  8290. )
  8291. )
  8292. recorded_count += 1
  8293. await db.commit()
  8294. if recorded_count > 0:
  8295. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  8296. # Periodic cleanup — once every ~24h at this interval.
  8297. global _printer_sensor_cleanup_counter
  8298. _printer_sensor_cleanup_counter += 1
  8299. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  8300. if _printer_sensor_cleanup_counter >= cleanup_every:
  8301. _printer_sensor_cleanup_counter = 0
  8302. result = await db.execute(
  8303. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  8304. )
  8305. setting = result.scalar_one_or_none()
  8306. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  8307. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8308. cleanup = await db.execute(
  8309. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  8310. )
  8311. await db.commit()
  8312. if cleanup.rowcount > 0:
  8313. logger.info(
  8314. "Cleaned up %s old printer sensor history entries (older than %s days)",
  8315. cleanup.rowcount,
  8316. retention_days,
  8317. )
  8318. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  8319. except asyncio.CancelledError:
  8320. break
  8321. except Exception as e:
  8322. logger.warning("Printer sensor history recording failed: %s", e)
  8323. await asyncio.sleep(60)
  8324. def start_printer_sensor_history_recording():
  8325. global _printer_sensor_history_task
  8326. if _printer_sensor_history_task is None:
  8327. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  8328. logging.getLogger(__name__).info("Printer sensor history recording started")
  8329. def stop_printer_sensor_history_recording():
  8330. global _printer_sensor_history_task
  8331. if _printer_sensor_history_task:
  8332. _printer_sensor_history_task.cancel()
  8333. _printer_sensor_history_task = None
  8334. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  8335. # Printer runtime tracking
  8336. _runtime_tracking_task: asyncio.Task | None = None
  8337. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  8338. async def track_printer_runtime():
  8339. """Background task to track printer active runtime (RUNNING state only).
  8340. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  8341. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  8342. which track mechanical wear. Pause time has no motion and no wear, so
  8343. counting it inflates maintenance warnings (#1521).
  8344. """
  8345. logger = logging.getLogger(__name__)
  8346. # Wait for MQTT connections to establish on startup
  8347. await asyncio.sleep(15)
  8348. while True:
  8349. try:
  8350. from backend.app.models.printer import Printer
  8351. # Fetch printer IDs in a short-lived read-only session
  8352. async with async_session() as db:
  8353. result = await db.execute(
  8354. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  8355. Printer.is_active.is_(True)
  8356. )
  8357. )
  8358. printer_rows = result.all()
  8359. now = datetime.now(timezone.utc)
  8360. updated_count = 0
  8361. # Update each printer in its own short session to minimise write-lock
  8362. # hold time and avoid blocking critical commits like queue status
  8363. # updates (#897).
  8364. for pid, pname, runtime_secs, last_update in printer_rows:
  8365. state = printer_manager.get_status(pid)
  8366. if not state:
  8367. logger.debug("[%s] Runtime tracking: no state available", pname)
  8368. continue
  8369. if not state.connected:
  8370. logger.debug("[%s] Runtime tracking: not connected", pname)
  8371. continue
  8372. needs_commit = False
  8373. new_runtime = runtime_secs
  8374. new_last_update = last_update
  8375. if state.state == "RUNNING":
  8376. if last_update:
  8377. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  8378. elapsed = (now - lu).total_seconds()
  8379. if elapsed > 0:
  8380. new_runtime = runtime_secs + int(elapsed)
  8381. updated_count += 1
  8382. needs_commit = True
  8383. logger.debug(
  8384. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  8385. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  8386. )
  8387. else:
  8388. needs_commit = True
  8389. logger.debug("[%s] Runtime tracking: first active detection", pname)
  8390. new_last_update = now
  8391. else:
  8392. if last_update is not None:
  8393. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  8394. new_last_update = None
  8395. needs_commit = True
  8396. if needs_commit:
  8397. try:
  8398. async with async_session() as db:
  8399. result = await db.execute(select(Printer).where(Printer.id == pid))
  8400. printer = result.scalar_one_or_none()
  8401. if printer:
  8402. printer.runtime_seconds = new_runtime
  8403. printer.last_runtime_update = new_last_update
  8404. await db.commit()
  8405. except Exception as e:
  8406. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  8407. if updated_count > 0:
  8408. logger.debug("Updated runtime for %s printer(s)", updated_count)
  8409. except asyncio.CancelledError:
  8410. logger.info("Runtime tracking cancelled")
  8411. break
  8412. except Exception as e:
  8413. logger.warning("Runtime tracking failed: %s", e)
  8414. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  8415. def start_runtime_tracking():
  8416. """Start the printer runtime tracking background task."""
  8417. global _runtime_tracking_task
  8418. if _runtime_tracking_task is None:
  8419. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  8420. logging.getLogger(__name__).info("Printer runtime tracking started")
  8421. def stop_runtime_tracking():
  8422. """Stop the printer runtime tracking background task."""
  8423. global _runtime_tracking_task
  8424. if _runtime_tracking_task:
  8425. _runtime_tracking_task.cancel()
  8426. _runtime_tracking_task = None
  8427. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  8428. # SpoolBuddy device watchdog
  8429. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  8430. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  8431. async def _spoolbuddy_watchdog_loop():
  8432. """Periodic check for SpoolBuddy devices that have gone offline."""
  8433. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  8434. while True:
  8435. try:
  8436. await spoolbuddy_watchdog()
  8437. except asyncio.CancelledError:
  8438. break
  8439. except Exception as e:
  8440. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  8441. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  8442. def start_spoolbuddy_watchdog():
  8443. global _spoolbuddy_watchdog_task
  8444. if _spoolbuddy_watchdog_task is None:
  8445. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  8446. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  8447. def stop_spoolbuddy_watchdog():
  8448. global _spoolbuddy_watchdog_task
  8449. if _spoolbuddy_watchdog_task:
  8450. _spoolbuddy_watchdog_task.cancel()
  8451. _spoolbuddy_watchdog_task = None
  8452. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  8453. # Dead-MQTT-session recovery
  8454. #
  8455. # check_staleness() covers the "connected but silent" half-broken session. It
  8456. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  8457. # is the only thing left watching at that point. When paho stops making
  8458. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  8459. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  8460. # offline with the UI open the whole time, recovered only when something
  8461. # happened to nudge it.
  8462. #
  8463. # This loop is that backstop. It only touches printers that had a working
  8464. # session and lost it, and only when the MQTT port still answers — a printer
  8465. # that is simply switched off is left to paho, since rebuilding a client
  8466. # against an unreachable host achieves nothing and would fill the log every
  8467. # night.
  8468. _connection_watchdog_task: asyncio.Task | None = None
  8469. CONNECTION_WATCHDOG_INTERVAL = 60
  8470. # How long a printer must have been silent before we stop trusting paho.
  8471. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  8472. # so a session that is recovering on its own is never interrupted.
  8473. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  8474. # Per-printer floor between rebuild attempts.
  8475. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  8476. _connection_watchdog_last_attempt: dict[int, float] = {}
  8477. async def _recover_dead_printer_sessions() -> int:
  8478. """Rebuild MQTT clients that have been offline too long to still be trying.
  8479. Returns the number of printers a rebuild was attempted for (for tests and
  8480. for the caller's logging). Never raises: one unreachable printer must not
  8481. stop the sweep for the rest of the farm.
  8482. """
  8483. logger = logging.getLogger(__name__)
  8484. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  8485. now = time.monotonic()
  8486. recovered = 0
  8487. for printer_id, client in list(printer_manager._clients.items()):
  8488. try:
  8489. if client.state.connected:
  8490. _connection_watchdog_last_attempt.pop(printer_id, None)
  8491. continue
  8492. # Time since the last inbound message is the age of the last known
  8493. # good session — no extra bookkeeping needed, and it is the same
  8494. # clock is_stale() reads. 0 means this client has never had one:
  8495. # that is the initial-connect path, where paho retrying is the
  8496. # correct and only behaviour, so leave it be.
  8497. last_msg = client._last_message_time
  8498. if not last_msg:
  8499. continue
  8500. offline_for = time.time() - last_msg
  8501. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  8502. continue
  8503. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  8504. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  8505. continue
  8506. if not await check_port(client.ip_address, PORT_MQTT):
  8507. # Switched off, unplugged, or off the network. Paho's retry is
  8508. # the right handler; say so at debug level and move on.
  8509. logger.debug(
  8510. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  8511. "— leaving the reconnect to paho",
  8512. printer_id,
  8513. offline_for,
  8514. )
  8515. _connection_watchdog_last_attempt[printer_id] = now
  8516. continue
  8517. _connection_watchdog_last_attempt[printer_id] = now
  8518. recovered += 1
  8519. logger.warning(
  8520. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  8521. "rebuilding the client with a fresh session (last connect error: %s)",
  8522. printer_id,
  8523. offline_for,
  8524. PORT_MQTT,
  8525. client.last_connect_error or "none recorded",
  8526. )
  8527. # Async context, so this takes the hard-reset path: fresh client_id,
  8528. # paho's QoS 1 queue dropped. That matters — a project_file left
  8529. # unacked on the dead session would otherwise replay into the new
  8530. # one and trip 0500_4003 on the printer (#1136).
  8531. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  8532. except Exception as e:
  8533. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  8534. return recovered
  8535. async def _connection_watchdog_loop():
  8536. logger = logging.getLogger(__name__)
  8537. # Let the initial connects settle before judging anyone offline.
  8538. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  8539. while True:
  8540. try:
  8541. await _recover_dead_printer_sessions()
  8542. except asyncio.CancelledError:
  8543. break
  8544. except Exception as e:
  8545. logger.warning("Connection watchdog sweep failed: %s", e)
  8546. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  8547. def start_connection_watchdog():
  8548. global _connection_watchdog_task
  8549. if _connection_watchdog_task is None:
  8550. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  8551. logging.getLogger(__name__).info("Printer connection watchdog started")
  8552. def stop_connection_watchdog():
  8553. global _connection_watchdog_task
  8554. if _connection_watchdog_task:
  8555. _connection_watchdog_task.cancel()
  8556. _connection_watchdog_task = None
  8557. _connection_watchdog_last_attempt.clear()
  8558. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  8559. # Camera stream orphan cleanup
  8560. _camera_cleanup_task: asyncio.Task | None = None
  8561. CAMERA_CLEANUP_INTERVAL = 60
  8562. async def _camera_cleanup_loop():
  8563. """Periodically clean up orphaned ffmpeg processes."""
  8564. from backend.app.api.routes.camera import cleanup_orphaned_streams
  8565. while True:
  8566. try:
  8567. await cleanup_orphaned_streams()
  8568. except asyncio.CancelledError:
  8569. break
  8570. except Exception as e:
  8571. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  8572. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  8573. def start_camera_cleanup():
  8574. global _camera_cleanup_task
  8575. if _camera_cleanup_task is None:
  8576. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  8577. logging.getLogger(__name__).info("Camera stream cleanup started")
  8578. def stop_camera_cleanup():
  8579. global _camera_cleanup_task
  8580. if _camera_cleanup_task:
  8581. _camera_cleanup_task.cancel()
  8582. _camera_cleanup_task = None
  8583. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  8584. # ---------------------------------------------------------------------------
  8585. # Expected-print TTL eviction
  8586. # ---------------------------------------------------------------------------
  8587. def _evict_stale_expected_prints() -> None:
  8588. """Remove entries from _expected_prints / _expected_print_creators that are
  8589. older than _EXPECTED_PRINT_TTL_SECONDS.
  8590. This prevents unbounded growth when a print is registered (via
  8591. register_expected_print) but on_print_start never fires — e.g. because the
  8592. printer disconnects, the app restarts, or the print is started directly from
  8593. the printer panel without going through the queue.
  8594. """
  8595. # Use monotonic time so the TTL is unaffected by system clock adjustments
  8596. # (e.g. NTP sync, DST changes).
  8597. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  8598. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  8599. if not stale_keys:
  8600. return
  8601. evicted_archive_ids: set[int] = set()
  8602. for key in stale_keys:
  8603. archive_id = _expected_prints.pop(key, None)
  8604. if archive_id is not None:
  8605. evicted_archive_ids.add(archive_id)
  8606. _expected_print_creators.pop(key, None)
  8607. _expected_print_registered_at.pop(key, None)
  8608. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  8609. # that have no remaining live keys in _expected_prints (all variants
  8610. # were just evicted).
  8611. live_archive_ids = set(_expected_prints.values())
  8612. for archive_id in evicted_archive_ids:
  8613. if archive_id not in live_archive_ids:
  8614. _print_ams_mappings.pop(archive_id, None)
  8615. _print_cost_center_ids.pop(archive_id, None)
  8616. _print_plate_ids.pop(archive_id, None)
  8617. logging.getLogger(__name__).info(
  8618. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  8619. )
  8620. async def _expected_prints_cleanup_loop() -> None:
  8621. """Background task: periodically evict stale expected-print entries."""
  8622. while True:
  8623. try:
  8624. _evict_stale_expected_prints()
  8625. except asyncio.CancelledError:
  8626. raise
  8627. except Exception as e:
  8628. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  8629. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  8630. def start_expected_prints_cleanup() -> None:
  8631. global _expected_prints_cleanup_task
  8632. if _expected_prints_cleanup_task is None:
  8633. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  8634. logging.getLogger(__name__).info("Expected prints cleanup started")
  8635. def stop_expected_prints_cleanup() -> None:
  8636. global _expected_prints_cleanup_task
  8637. if _expected_prints_cleanup_task:
  8638. _expected_prints_cleanup_task.cancel()
  8639. _expected_prints_cleanup_task = None
  8640. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  8641. # ---------------------------------------------------------------------------
  8642. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  8643. # ---------------------------------------------------------------------------
  8644. _auth_cleanup_task: asyncio.Task | None = None
  8645. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  8646. async def _run_auth_cleanup() -> None:
  8647. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  8648. from backend.app.core.database import async_session
  8649. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  8650. from backend.app.models.user_totp import UserTOTP
  8651. now = datetime.now(timezone.utc)
  8652. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  8653. try:
  8654. async with async_session() as db:
  8655. stale_cutoff = now - timedelta(hours=1)
  8656. result = await db.execute(
  8657. select(UserTOTP).where(
  8658. UserTOTP.is_enabled.is_(False),
  8659. UserTOTP.created_at < stale_cutoff,
  8660. )
  8661. )
  8662. stale_records = result.scalars().all()
  8663. if stale_records:
  8664. for rec in stale_records:
  8665. await db.delete(rec)
  8666. await db.commit()
  8667. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  8668. except Exception as e:
  8669. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  8670. # Remove expired revoked-JTI entries (they are no longer needed once the
  8671. # original token's exp has passed — the token would be rejected by JWT
  8672. # signature verification regardless).
  8673. try:
  8674. async with async_session() as db:
  8675. await db.execute(
  8676. delete(AuthEphemeralToken).where(
  8677. AuthEphemeralToken.token_type == "revoked_jti",
  8678. AuthEphemeralToken.expires_at < now,
  8679. )
  8680. )
  8681. await db.commit()
  8682. except Exception as e:
  8683. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  8684. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  8685. # Events outside this window can never affect rate-limit decisions — they only
  8686. # consume DB space. Use the same window constant as the rate limiter so the
  8687. # two are always in sync.
  8688. try:
  8689. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  8690. async with async_session() as db:
  8691. await db.execute(
  8692. delete(AuthRateLimitEvent).where(
  8693. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  8694. )
  8695. )
  8696. await db.commit()
  8697. except Exception as e:
  8698. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  8699. async def _auth_cleanup_loop() -> None:
  8700. """Periodic background task: run auth cleanup every hour."""
  8701. while True:
  8702. try:
  8703. await _run_auth_cleanup()
  8704. except asyncio.CancelledError:
  8705. break
  8706. except Exception as e:
  8707. logging.warning("Auth cleanup loop error: %s", e)
  8708. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  8709. def start_auth_cleanup() -> None:
  8710. global _auth_cleanup_task
  8711. if _auth_cleanup_task is None:
  8712. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  8713. logging.getLogger(__name__).info("Auth periodic cleanup started")
  8714. def stop_auth_cleanup() -> None:
  8715. global _auth_cleanup_task
  8716. if _auth_cleanup_task:
  8717. _auth_cleanup_task.cancel()
  8718. _auth_cleanup_task = None
  8719. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  8720. @asynccontextmanager
  8721. async def lifespan(app: FastAPI):
  8722. # Startup
  8723. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  8724. # anything else can spawn tasks that might trip it.
  8725. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  8726. install_proactor_reset_filter()
  8727. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  8728. # what turned descriptor exhaustion into a corrupted database (#2883).
  8729. from backend.app.core.fd_limit import raise_open_file_limit
  8730. raise_open_file_limit()
  8731. # Before init_db, so the warning is near the top of the log rather than
  8732. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  8733. warn_if_running_on_uvloop()
  8734. await init_db()
  8735. # Browser download tokens expire after five minutes. Remove abandoned
  8736. # prepared ZIPs at startup as well as before each new preparation so a
  8737. # quiet appliance cannot retain an unusable bundle indefinitely.
  8738. try:
  8739. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  8740. await prune_stale_printer_file_bundles()
  8741. except Exception as exc:
  8742. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  8743. # After migrations, so the is_env_managed column exists. Never raises --
  8744. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  8745. # startup (see apply_env_oidc_provider).
  8746. from backend.app.core.oidc_env import apply_env_oidc_provider
  8747. async with async_session() as oidc_db:
  8748. await apply_env_oidc_provider(oidc_db)
  8749. # Close out batches that finished before `completed` was a reachable status
  8750. # (#342). Without this the Batches tab opens on every batch created since
  8751. # the feature shipped, all still marked active. Never blocks startup.
  8752. try:
  8753. from backend.app.services.print_batch import backfill_batch_statuses
  8754. async with async_session() as batch_db:
  8755. await backfill_batch_statuses(batch_db)
  8756. except Exception as exc:
  8757. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  8758. # Register an app-scoped httpx client for Bambu Cloud services so
  8759. # per-request BambuCloudService instances reuse the same connection pool
  8760. # (important for routes like /cloud/filament-info that chain many
  8761. # get_setting_detail calls). The shared client stores no region/token
  8762. # state, so the per-request ownership pattern that fixed the region-bleed
  8763. # bug is preserved.
  8764. import httpx as _httpx
  8765. from backend.app.services.bambu_cloud import set_shared_http_client
  8766. from backend.app.services.model_providers.makerworld.service import (
  8767. set_shared_http_client as set_shared_makerworld_http_client,
  8768. )
  8769. from backend.app.services.orca_cloud import (
  8770. set_shared_http_client as set_shared_orca_http_client,
  8771. )
  8772. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  8773. set_shared_http_client(_shared_cloud_http_client)
  8774. # Reuse the same connection pool for MakerWorld — different host, same
  8775. # keep-alive pool saves a TLS handshake per request.
  8776. set_shared_makerworld_http_client(_shared_cloud_http_client)
  8777. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  8778. # each spun up (and never closed) its own client, leaking sockets.
  8779. set_shared_orca_http_client(_shared_cloud_http_client)
  8780. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  8781. # This can happen when a print was cancelled mid-print on versions before this fix.
  8782. try:
  8783. async with async_session() as db:
  8784. from backend.app.models.print_queue import PrintQueueItem
  8785. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  8786. aborted_items = result.scalars().all()
  8787. if aborted_items:
  8788. for item in aborted_items:
  8789. item.status = "cancelled"
  8790. await db.commit()
  8791. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  8792. except Exception as e:
  8793. logging.warning("Failed to fix aborted queue items: %s", e)
  8794. # Restore debug logging state from previous session
  8795. await init_debug_logging()
  8796. # Set up printer manager callbacks
  8797. loop = asyncio.get_event_loop()
  8798. printer_manager.set_event_loop(loop)
  8799. printer_manager.set_status_change_callback(on_printer_status_change)
  8800. printer_manager.set_print_start_callback(on_print_start)
  8801. printer_manager.set_print_complete_callback(on_print_complete)
  8802. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  8803. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  8804. printer_manager.set_ams_change_callback(on_ams_change)
  8805. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  8806. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  8807. await printer_manager.load_awaiting_plate_clear_from_db()
  8808. # Layer change callback for external camera timelapse
  8809. async def on_layer_change(printer_id: int, layer_num: int):
  8810. """Capture timelapse frame on layer change + first layer notification."""
  8811. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  8812. await tl_layer_change(printer_id, layer_num)
  8813. # #1867: bank a recent in-print frame so the finish-photo path has a
  8814. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  8815. # #2547 added `on_print_progress` as a second driver — this one alone
  8816. # stops firing once the final layer begins.
  8817. await _maybe_bank_inprint_frame(printer_id, layer_num)
  8818. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  8819. # Gate on actual printing state — Bambu firmware ticks layer_num during
  8820. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  8821. # nozzle clean), so a bare layer_num check can fire minutes before the
  8822. # first real extrusion. We require gcode_state == RUNNING and
  8823. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  8824. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  8825. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  8826. # edge fires later; _first_layer_notified stays clear until we actually send
  8827. # so a deferred re-evaluation can win. See issue #1837.
  8828. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  8829. client = printer_manager.get_client(printer_id)
  8830. state = client.state if client else None
  8831. if not state or state.state != "RUNNING":
  8832. return
  8833. if state.mc_print_sub_stage not in (None, 0):
  8834. return
  8835. _first_layer_notified[printer_id] = True
  8836. try:
  8837. async with async_session() as db:
  8838. from backend.app.models.printer import Printer
  8839. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8840. printer = result.scalar_one_or_none()
  8841. if not printer:
  8842. return
  8843. printer_name = printer.name
  8844. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  8845. total_layers = state.total_layers if state else 0
  8846. image_data = await _capture_snapshot_for_notification(
  8847. printer_id, printer, logging.getLogger(__name__)
  8848. )
  8849. await notification_service.on_first_layer_complete(
  8850. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  8851. )
  8852. except Exception as e:
  8853. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  8854. printer_manager.set_layer_change_callback(on_layer_change)
  8855. async def on_print_progress(printer_id: int, percent: int):
  8856. """#2547: keep the in-print frame bank fresh through the final layer.
  8857. `on_layer_change` stops the moment the last layer starts, which on the
  8858. H2C capture that closed #2547 left the bank stale for the three minutes
  8859. that layer took. Progress is the only field that keeps advancing there,
  8860. and it freezes before the End G-code runs — so banking on it stays
  8861. inside the print and never sees a swapped plate.
  8862. """
  8863. client = printer_manager.get_client(printer_id)
  8864. state = client.state if client else None
  8865. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  8866. printer_manager.set_print_progress_callback(on_print_progress)
  8867. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  8868. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  8869. waiter = _bed_cool_waiters.get(printer_id)
  8870. if not waiter:
  8871. return
  8872. threshold = waiter["threshold"]
  8873. if bed_temp > threshold:
  8874. return
  8875. # Bed is at or below threshold — fire notification and remove waiter
  8876. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  8877. if not waiter_info:
  8878. return # Another callback already handled it
  8879. bed_cool_logger = logging.getLogger(__name__)
  8880. bed_cool_logger.info(
  8881. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  8882. bed_temp,
  8883. printer_id,
  8884. threshold,
  8885. )
  8886. try:
  8887. printer_info = printer_manager.get_printer(printer_id)
  8888. p_name = printer_info.name if printer_info else "Unknown"
  8889. async with async_session() as db:
  8890. await notification_service.on_bed_cooled(
  8891. printer_id=printer_id,
  8892. printer_name=p_name,
  8893. bed_temp=bed_temp,
  8894. threshold=threshold,
  8895. filename=waiter_info["filename"],
  8896. db=db,
  8897. )
  8898. except Exception as e:
  8899. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  8900. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  8901. async def on_drying_complete(printer_id: int, ams_id: int):
  8902. """Smart-plug auto-off-after-drying trigger (#1349).
  8903. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  8904. manager walks all plugs linked to this printer and turns off only
  8905. the ones with ``auto_off_after_drying`` enabled, after their
  8906. per-plug delay. Multiple AMS units finishing close together (e.g. a
  8907. dual-AMS dry that ends within the same MQTT push) call this once
  8908. per unit — the manager's ``_cancel_pending_off`` collapses
  8909. repeated scheduling on the same plug to one timer, so duplicate
  8910. fires are safe.
  8911. """
  8912. try:
  8913. async with async_session() as db:
  8914. await smart_plug_manager.on_drying_complete(printer_id, db)
  8915. except Exception as e:
  8916. logging.getLogger(__name__).warning(
  8917. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  8918. printer_id,
  8919. ams_id,
  8920. e,
  8921. )
  8922. printer_manager.set_drying_complete_callback(on_drying_complete)
  8923. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  8924. """Surface the read-back result of a spool assignment to the UI (#2582).
  8925. The MQTT client confirms (or fails to confirm) that the tray telemetry
  8926. echoed back the filament id we pushed. We relay that as a websocket
  8927. event so the frontend can toast "loaded" / "assignment didn't take"
  8928. instead of the historic silent fire-and-forget, which made the
  8929. AMS→Studio hand-off feel random to users.
  8930. """
  8931. try:
  8932. from backend.app.services.spool_assignment_notifications import (
  8933. _slot_label_from_global_tray,
  8934. )
  8935. if ams_id == 255:
  8936. global_id = 254 + tray_id
  8937. elif ams_id >= 128:
  8938. global_id = ams_id
  8939. else:
  8940. global_id = ams_id * 4 + tray_id
  8941. slot_label = _slot_label_from_global_tray(global_id)
  8942. printer_info = printer_manager.get_printer(printer_id)
  8943. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8944. await ws_manager.broadcast(
  8945. {
  8946. "type": "spool_assignment_verified",
  8947. "printer_id": printer_id,
  8948. "printer_name": printer_name,
  8949. "ams_id": ams_id,
  8950. "tray_id": tray_id,
  8951. "slot": slot_label,
  8952. "verified": verified,
  8953. # Present on success: False means the filament setting landed
  8954. # but the K-profile (cali_idx) did not — the reporter's exact
  8955. # "loaded but no flow profile" symptom.
  8956. "kprofile_applied": detail.get("kprofile_applied", True),
  8957. # Present on failure: whether any tray telemetry was seen in
  8958. # the window (distinguishes "printer silent" from "printer
  8959. # stored something else").
  8960. "saw_tray": detail.get("saw_tray", False),
  8961. }
  8962. )
  8963. except Exception as e:
  8964. logging.getLogger(__name__).warning(
  8965. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  8966. printer_id,
  8967. ams_id,
  8968. tray_id,
  8969. e,
  8970. )
  8971. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  8972. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  8973. """Persist a mid-print tray change for completion-time attribution.
  8974. AMS filament backup switches trays without telling the slicer, so the
  8975. tray-change log is the only record of which spool fed which layers.
  8976. Keeping it only in memory meant a restart mid-print charged everything
  8977. to the tray that finished the job.
  8978. """
  8979. try:
  8980. from backend.app.services.usage_tracker import record_tray_change
  8981. async with async_session() as db:
  8982. await record_tray_change(db, printer_id, tray_global, layer_num)
  8983. except Exception as e:
  8984. logging.getLogger(__name__).warning(
  8985. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  8986. printer_id,
  8987. tray_global,
  8988. layer_num,
  8989. e,
  8990. )
  8991. printer_manager.set_tray_change_callback(on_tray_change)
  8992. # Initialize MQTT relay from settings
  8993. async with async_session() as db:
  8994. from backend.app.api.routes.settings import get_setting
  8995. mqtt_settings = {
  8996. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  8997. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  8998. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  8999. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  9000. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  9001. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  9002. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  9003. }
  9004. await mqtt_relay.configure(mqtt_settings)
  9005. # Restore MQTT smart plug subscriptions
  9006. if mqtt_settings.get("mqtt_enabled"):
  9007. from backend.app.models.smart_plug import SmartPlug
  9008. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  9009. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  9010. mqtt_plugs = result.scalars().all()
  9011. restored = 0
  9012. for plug in mqtt_plugs:
  9013. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  9014. restored += 1
  9015. if restored:
  9016. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  9017. # Connect to all active printers
  9018. async with async_session() as db:
  9019. await init_printer_connections(db)
  9020. # Auto-connect to Spoolman if enabled
  9021. async with async_session() as db:
  9022. from backend.app.api.routes.settings import get_setting
  9023. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  9024. spoolman_url = await get_setting(db, "spoolman_url")
  9025. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  9026. try:
  9027. client = await init_spoolman_client(spoolman_url)
  9028. if await client.health_check():
  9029. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  9030. # Ensure the 'tag' extra field exists for RFID/UUID storage
  9031. field_ok = await client.ensure_tag_extra_field()
  9032. if not field_ok:
  9033. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  9034. # Register the BambuStudio slicer-preset fields used by the
  9035. # spool-edit / assign flow. Spoolman rejects PATCHes with
  9036. # unknown extra keys, so these must exist before any update
  9037. # that touches them.
  9038. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  9039. if not await client.ensure_extra_field(field_name):
  9040. logging.warning(
  9041. "Spoolman extra field %r registration failed — "
  9042. "spool slicer-preset edits will return 502",
  9043. field_name,
  9044. )
  9045. else:
  9046. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  9047. except Exception as e:
  9048. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  9049. # Start the print scheduler
  9050. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  9051. # Start the smart plug scheduler for time-based on/off
  9052. smart_plug_manager.start_scheduler()
  9053. # Start the Home Assistant sensor poller (#1148)
  9054. ha_sensor_manager.start()
  9055. location_ha_sensor_manager.start()
  9056. # Resume any pending auto-offs that were interrupted by restart
  9057. await smart_plug_manager.resume_pending_auto_offs()
  9058. # Start the notification digest scheduler
  9059. notification_service.start_digest_scheduler()
  9060. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  9061. # provider in reactions/both mode; the notification routes resync them.
  9062. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  9063. # until the next provider save, not the whole startup.
  9064. try:
  9065. await telegram_reaction_poller.start()
  9066. except Exception as e:
  9067. logging.warning("Telegram reaction poller did not start: %s", e)
  9068. # Start the GitHub backup scheduler
  9069. await github_backup_service.start_scheduler()
  9070. # Start the local backup scheduler
  9071. await local_backup_service.start_scheduler()
  9072. await obico_detection_service.start()
  9073. # Start the library trash sweeper (#1008)
  9074. await library_trash_service.start_scheduler()
  9075. # Start the archive auto-purge sweeper (#1008 follow-up)
  9076. await archive_purge_service.start_scheduler()
  9077. # Start AMS history recording
  9078. start_ams_history_recording()
  9079. # Start printer sensor (nozzle / bed / chamber) history recording
  9080. start_printer_sensor_history_recording()
  9081. # Start printer runtime tracking
  9082. start_runtime_tracking()
  9083. # Start SpoolBuddy device watchdog
  9084. start_spoolbuddy_watchdog()
  9085. # Start camera stream orphan cleanup
  9086. start_camera_cleanup()
  9087. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  9088. start_connection_watchdog()
  9089. # One-shot sweep for timelapse session directories orphaned by a crash
  9090. # or restart that happened mid-print (in-memory session tracking can't
  9091. # survive that, and nothing else reaps the leftover frames/output file)
  9092. try:
  9093. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9094. removed = cleanup_orphaned_timelapse_sessions()
  9095. if removed:
  9096. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  9097. except Exception as e:
  9098. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  9099. # Start expected-print TTL eviction (prevents memory leak when prints are
  9100. # registered but on_print_start never fires)
  9101. start_expected_prints_cleanup()
  9102. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  9103. start_auth_cleanup()
  9104. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  9105. from backend.app.services import announcements as announcements_service
  9106. announcements_service.start()
  9107. from backend.app.services.printer_media import start_printer_download_cleanup
  9108. start_printer_download_cleanup()
  9109. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  9110. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  9111. from backend.app.services.loop_watchdog import start_loop_watchdog
  9112. start_loop_watchdog()
  9113. # Initialize virtual printer manager and sync from DB
  9114. from backend.app.services.virtual_printer import virtual_printer_manager
  9115. virtual_printer_manager.set_session_factory(async_session)
  9116. virtual_printer_manager.set_printer_manager(printer_manager)
  9117. try:
  9118. await virtual_printer_manager.sync_from_db()
  9119. logging.info("Virtual printer manager synced from database")
  9120. except Exception as e:
  9121. logging.warning("Failed to sync virtual printers: %s", e)
  9122. yield
  9123. # Shutdown
  9124. print_scheduler.stop()
  9125. smart_plug_manager.stop_scheduler()
  9126. ha_sensor_manager.stop()
  9127. location_ha_sensor_manager.stop()
  9128. notification_service.stop_digest_scheduler()
  9129. await telegram_reaction_poller.aclose()
  9130. github_backup_service.stop_scheduler()
  9131. local_backup_service.stop_scheduler()
  9132. library_trash_service.stop_scheduler()
  9133. archive_purge_service.stop_scheduler()
  9134. obico_detection_service.stop()
  9135. stop_ams_history_recording()
  9136. stop_printer_sensor_history_recording()
  9137. stop_runtime_tracking()
  9138. stop_spoolbuddy_watchdog()
  9139. stop_camera_cleanup()
  9140. stop_connection_watchdog()
  9141. from backend.app.services.loop_watchdog import stop_loop_watchdog
  9142. stop_loop_watchdog()
  9143. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  9144. # cleanly rather than waiting on a queue that nothing will ever fill.
  9145. try:
  9146. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  9147. await shutdown_all_broadcasters()
  9148. except Exception as e:
  9149. logging.warning("Failed to shut down camera broadcasters: %s", e)
  9150. stop_expected_prints_cleanup()
  9151. stop_auth_cleanup()
  9152. from backend.app.services import announcements as announcements_service
  9153. announcements_service.stop()
  9154. from backend.app.services.printer_media import stop_printer_download_cleanup
  9155. await stop_printer_download_cleanup()
  9156. printer_manager.disconnect_all()
  9157. slot_unlink_grace.reset()
  9158. await close_spoolman_client()
  9159. # Stop all virtual printer services
  9160. await virtual_printer_manager.stop_all()
  9161. await mqtt_smart_plug_service.disconnect(timeout=2)
  9162. await mqtt_relay.disconnect(timeout=2)
  9163. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  9164. set_shared_http_client(None)
  9165. set_shared_makerworld_http_client(None)
  9166. set_shared_orca_http_client(None)
  9167. await _shared_cloud_http_client.aclose()
  9168. # Checkpoint WAL (SQLite only) and close all database connections
  9169. from backend.app.core.db_dialect import is_sqlite
  9170. if is_sqlite():
  9171. try:
  9172. async with engine.begin() as conn:
  9173. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  9174. logging.info("WAL checkpoint completed")
  9175. except Exception as e:
  9176. logging.warning("WAL checkpoint failed: %s", e)
  9177. await engine.dispose()
  9178. app = FastAPI(
  9179. title=app_settings.app_name,
  9180. description="Archive and manage Bambu Lab 3MF files",
  9181. version=APP_VERSION,
  9182. lifespan=lifespan,
  9183. )
  9184. # =============================================================================
  9185. # Authentication Middleware - Secures ALL API routes by default
  9186. # =============================================================================
  9187. # Public routes that don't require authentication even when auth is enabled
  9188. PUBLIC_API_ROUTES = {
  9189. # Auth routes needed before/during login
  9190. "/api/v1/auth/status",
  9191. "/api/v1/auth/login",
  9192. "/api/v1/auth/setup", # Needed for initial setup and recovery
  9193. # Advanced auth status needed for login page
  9194. "/api/v1/auth/advanced-auth/status",
  9195. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  9196. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  9197. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  9198. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  9199. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  9200. # OIDC routes that must be reachable without a JWT
  9201. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  9202. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  9203. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  9204. # Connected apps: the app's server swaps a code for the user's identity,
  9205. # authenticated by its client secret rather than a login token.
  9206. "/api/v1/connect/token",
  9207. # Version check for updates (no sensitive data)
  9208. "/api/v1/updates/version",
  9209. # Metrics endpoint handles its own prometheus_token authentication
  9210. "/api/v1/metrics",
  9211. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  9212. # this BEFORE a JWT is available to pick up the firstboot wizard's
  9213. # hostname / timezone / locale and the chrony NTP-gate state. The
  9214. # response contains user-set defaults and a public sync flag — no
  9215. # secrets. Without this entry the global auth middleware returns 401
  9216. # before the route handler runs, regardless of the route's own
  9217. # "no auth required" intent.
  9218. "/api/v1/system/appliance",
  9219. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  9220. # authenticates with a long-lived ``camwall``-scoped token in the query
  9221. # string — exactly like the camera streams two lists below, and for the same
  9222. # reason (no header to put a JWT in). "Public" here only means the middleware
  9223. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  9224. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  9225. # plain ``camera_stream`` token does NOT open this door.
  9226. "/api/v1/camwall/printers",
  9227. # Overlay branding: the route enforces overlay-scoped token authentication.
  9228. "/api/v1/overlay-branding/logo",
  9229. }
  9230. # Route prefixes that are public (for routes with dynamic segments)
  9231. PUBLIC_API_PREFIXES = [
  9232. # WebSocket connections handle their own auth
  9233. "/api/v1/ws",
  9234. # OIDC authorize redirects — include provider_id in path
  9235. "/api/v1/auth/oidc/authorize/",
  9236. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  9237. # a phone with no session, so no header can carry a JWT — the single-use
  9238. # capability token in the path IS the credential (same reasoning as the
  9239. # /dl/ slicer downloads below). The route grants nothing beyond writing
  9240. # good/reject on the one archive the token was minted for.
  9241. "/api/v1/archives/confirm/",
  9242. ]
  9243. # Route patterns that are public (read-only display data)
  9244. # These are checked with "in path" - needed because browsers load images/videos
  9245. # via <img src> and <video src> which don't include Authorization headers
  9246. PUBLIC_API_PATTERNS = [
  9247. # Thumbnails
  9248. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  9249. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  9250. # Images and media
  9251. "/photos/", # /archives/{id}/photos/{filename}
  9252. "/project-image/", # /archives/{id}/project-image/{path}
  9253. "/qrcode", # /archives/{id}/qrcode
  9254. "/timelapse", # /archives/{id}/timelapse (video)
  9255. "/cover", # /printers/{id}/cover
  9256. "/icon", # /external-links/{id}/icon
  9257. # Camera (streams loaded via <img> tag)
  9258. "/camera/stream", # /printers/{id}/camera/stream
  9259. "/camera/snapshot", # /printers/{id}/camera/snapshot
  9260. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  9261. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  9262. # string (same reasoning as the camera streams above — no header to carry a
  9263. # JWT). "Public" only means the middleware steps aside; the route still runs
  9264. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  9265. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  9266. "/overlay-status", # /printers/{id}/overlay-status
  9267. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  9268. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  9269. # download token in the URL path instead.
  9270. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  9271. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  9272. # and these patterns match by substring. Without its own entry the middleware
  9273. # 401s the slicer's header-less request before the route's token check runs,
  9274. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  9275. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  9276. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  9277. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  9278. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  9279. ]
  9280. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  9281. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  9282. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  9283. Format: comma-separated list of ``scheme://host[:port]`` origins.
  9284. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  9285. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  9286. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  9287. Invalid entries are dropped with a warning rather than failing startup, so
  9288. a typo in one origin doesn't take the whole deployment down.
  9289. """
  9290. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  9291. if not raw:
  9292. return ()
  9293. valid: list[str] = []
  9294. for item in raw.split(","):
  9295. candidate = item.strip()
  9296. if not candidate:
  9297. continue
  9298. try:
  9299. parsed = urlparse(candidate)
  9300. except ValueError as e:
  9301. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  9302. continue
  9303. if parsed.scheme not in ("http", "https"):
  9304. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  9305. continue
  9306. if not parsed.netloc:
  9307. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  9308. continue
  9309. if parsed.path and parsed.path != "/":
  9310. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  9311. continue
  9312. if parsed.query or parsed.fragment:
  9313. _security_headers_logger.warning(
  9314. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  9315. )
  9316. continue
  9317. if "*" in parsed.netloc:
  9318. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  9319. continue
  9320. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  9321. if valid:
  9322. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  9323. return tuple(valid)
  9324. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  9325. def _frame_ancestors(default_value: str) -> str:
  9326. """Compose the ``frame-ancestors`` CSP directive (#1191).
  9327. ``default_value`` is the strict directive used when the operator has not
  9328. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  9329. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  9330. Settings URL builder's preview). When trusted origins
  9331. are configured, ``'self'`` is always included so same-origin embedding never
  9332. breaks even if an operator forgets to add their own origin to the list.
  9333. """
  9334. if _TRUSTED_FRAME_ORIGINS:
  9335. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  9336. return f"frame-ancestors {default_value};"
  9337. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  9338. # patterns are anchored on the exact emitted name so the relaxed policies
  9339. # below can never apply to any other asset.
  9340. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  9341. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  9342. # -> /assets/pdf.worker.min-<hash>.js
  9343. # Vite also emits a one-line chunk under the second name that only exports the
  9344. # worker's URL. The page imports it as a module, and a module script is run
  9345. # under the importing document's policy, never its own response's, so it
  9346. # matching as well changes nothing.
  9347. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  9348. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  9349. @app.middleware("http")
  9350. async def security_headers_middleware(request, call_next):
  9351. """Add standard HTTP security headers to every response."""
  9352. # Per-request nonce stamped into `script-src` (#1460). On its own this
  9353. # changes nothing for Bambuddy's own pages — index.html has no inline
  9354. # scripts since the SW registration moved to /sw-register.js. The reason
  9355. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  9356. # script injected into the HTML on the edge, with a fresh hash on every
  9357. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  9358. # it clones the same nonce onto its injected <script>, and the inline
  9359. # script passes the policy without us needing 'unsafe-inline'. See
  9360. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  9361. csp_nonce = secrets.token_urlsafe(16)
  9362. # Routes that render their own HTML need it too, or their inline script is
  9363. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  9364. # one that does: it submits its own form so a verdict still costs one tap.
  9365. request.state.csp_nonce = csp_nonce
  9366. response = await call_next(request)
  9367. response.headers["X-Content-Type-Options"] = "nosniff"
  9368. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  9369. # browsers honour CSP frame-ancestors instead, and the legacy
  9370. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  9371. # When operators have explicitly allowlisted trusted frame origins (#1191
  9372. # — typically Home Assistant on a different port), drop X-Frame-Options
  9373. # and let the CSP-side frame-ancestors directive govern embedding.
  9374. if not _TRUSTED_FRAME_ORIGINS:
  9375. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  9376. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  9377. # Content-Security-Policy for the React SPA.
  9378. # Notes:
  9379. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  9380. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  9381. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  9382. # - media-src blob:: timelapse video player uses Blob URLs.
  9383. # - font-src data:: some icon fonts are embedded as data URIs.
  9384. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  9385. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  9386. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  9387. # default CSP would render a blank page.
  9388. response.headers["Content-Security-Policy"] = (
  9389. "default-src 'self'; "
  9390. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  9391. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  9392. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  9393. "connect-src 'self'; "
  9394. "font-src 'self' data: https://fonts.gstatic.com; "
  9395. "worker-src 'self' blob:; "
  9396. "object-src 'none'; "
  9397. "base-uri 'self'; " + _frame_ancestors("'none'")
  9398. )
  9399. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  9400. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  9401. # its emscripten/embind glue generates invoker functions with `new
  9402. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  9403. # worker is governed by the policy delivered with the WORKER SCRIPT's
  9404. # own response — not the document's — so relaxing it here confines
  9405. # eval to that DOM-less worker context. The document policy below
  9406. # stays nonce-strict, and this response header has no effect when the
  9407. # file is merely fetched (a fetch's CSP is enforced against the
  9408. # requesting document, not the resource's own headers).
  9409. response.headers["Content-Security-Policy"] = (
  9410. "default-src 'self'; "
  9411. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  9412. "connect-src 'self'; "
  9413. "object-src 'none'; "
  9414. "base-uri 'self'; " + _frame_ancestors("'none'")
  9415. )
  9416. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  9417. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  9418. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  9419. # rule as the STEP worker above: the policy that governs a dedicated
  9420. # worker is the one delivered with its own script, so the wasm compile
  9421. # has to be permitted here rather than on the document. Unlike the STEP
  9422. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  9423. response.headers["Content-Security-Policy"] = (
  9424. "default-src 'self'; "
  9425. "script-src 'self' 'wasm-unsafe-eval'; "
  9426. "connect-src 'self'; "
  9427. "object-src 'none'; "
  9428. "base-uri 'self'; " + _frame_ancestors("'none'")
  9429. )
  9430. else:
  9431. # The streaming overlay is embedded same-origin by the URL builder's
  9432. # preview in Settings (#1422), so this branch allows 'self'.
  9433. # Embedding from anywhere else is still refused: 'self'
  9434. # only permits a framer on this origin, which is Bambuddy's own UI, so
  9435. # a clickjacking page on another host is blocked exactly as before.
  9436. # (The overlay draws status over a camera feed and its only interactive
  9437. # element is the logo link, so there is nothing to bait a click into
  9438. # even from a same-origin framer.) Cross-origin embedding of the
  9439. # overlay — Home Assistant on another port — remains what
  9440. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  9441. # allowlist in.
  9442. #
  9443. # The connected-app consent page (/connect/authorize) gets the same
  9444. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  9445. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  9446. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  9447. # requires every ancestor to be this origin, so a foreign page -- a
  9448. # sidebar link's site included -- still cannot frame the consent
  9449. # screen to bait a click.
  9450. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  9451. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  9452. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  9453. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  9454. # the policy served with their own script, so each gets it in its own
  9455. # branch above and the document policy stays as strict as it was.
  9456. response.headers["Content-Security-Policy"] = (
  9457. "default-src 'self'; "
  9458. f"script-src 'self' 'nonce-{csp_nonce}'; "
  9459. "style-src 'self' 'unsafe-inline'; "
  9460. "img-src 'self' data: blob:; "
  9461. "media-src 'self' blob:; "
  9462. "connect-src 'self' ws: wss:; "
  9463. "font-src 'self' data:; "
  9464. "object-src 'none'; "
  9465. "base-uri 'self'; "
  9466. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  9467. )
  9468. if request.url.scheme == "https":
  9469. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  9470. return response
  9471. @app.middleware("http")
  9472. async def auth_middleware(request, call_next):
  9473. """Enforce authentication on all API routes when auth is enabled.
  9474. This middleware provides defense-in-depth by checking auth at the API gateway level,
  9475. regardless of whether individual routes have auth dependencies.
  9476. """
  9477. from starlette.responses import JSONResponse
  9478. path = request.url.path
  9479. # Only apply to API routes
  9480. if not path.startswith("/api/"):
  9481. return await call_next(request)
  9482. # Allow public routes
  9483. if path in PUBLIC_API_ROUTES:
  9484. return await call_next(request)
  9485. # Allow public prefixes
  9486. for prefix in PUBLIC_API_PREFIXES:
  9487. if path.startswith(prefix):
  9488. return await call_next(request)
  9489. # Allow public patterns (read-only display data like thumbnails)
  9490. for pattern in PUBLIC_API_PATTERNS:
  9491. if pattern in path:
  9492. return await call_next(request)
  9493. # Check if auth is enabled. Fail CLOSED on any exception during the
  9494. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  9495. # an attacker who could force a DB exception (e.g. file-descriptor
  9496. # exhaustion via login flood) bypass auth on every protected endpoint.
  9497. try:
  9498. async with async_session() as db:
  9499. from backend.app.core.auth import is_auth_enabled
  9500. auth_enabled = await is_auth_enabled(db)
  9501. if not auth_enabled:
  9502. # Auth disabled, allow all requests
  9503. return await call_next(request)
  9504. except Exception:
  9505. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  9506. return JSONResponse(
  9507. status_code=503,
  9508. content={"detail": "Authentication service temporarily unavailable"},
  9509. )
  9510. # Auth is enabled - require valid token
  9511. auth_header = request.headers.get("Authorization")
  9512. x_api_key = request.headers.get("X-API-Key")
  9513. # Check for API key auth first
  9514. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  9515. # API key authentication - let the request through to be validated by route handler
  9516. # API keys are validated per-route since they have different permission levels
  9517. return await call_next(request)
  9518. # Check for JWT auth
  9519. if not auth_header or not auth_header.startswith("Bearer "):
  9520. return JSONResponse(
  9521. status_code=401,
  9522. content={"detail": "Authentication required"},
  9523. headers={"WWW-Authenticate": "Bearer"},
  9524. )
  9525. # Validate JWT token
  9526. import jwt
  9527. try:
  9528. from backend.app.core.auth import (
  9529. ALGORITHM,
  9530. SECRET_KEY,
  9531. _is_token_fresh,
  9532. get_user_by_username,
  9533. is_jti_revoked,
  9534. )
  9535. token = auth_header.replace("Bearer ", "")
  9536. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  9537. username = payload.get("sub")
  9538. if not username:
  9539. raise ValueError("No username in token")
  9540. jti = payload.get("jti")
  9541. if not jti:
  9542. raise ValueError("No jti in token")
  9543. iat = payload.get("iat")
  9544. # Verify user exists, is active, and token is still fresh (L-R8-A).
  9545. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  9546. # this session so the gateway adds a single pooled checkout, not two (#2572).
  9547. async with async_session() as db:
  9548. if await is_jti_revoked(jti, db):
  9549. return JSONResponse(
  9550. status_code=401,
  9551. content={"detail": "Token has been revoked"},
  9552. headers={"WWW-Authenticate": "Bearer"},
  9553. )
  9554. user = await get_user_by_username(db, username)
  9555. if not user or not user.is_active:
  9556. return JSONResponse(
  9557. status_code=401,
  9558. content={"detail": "User not found or inactive"},
  9559. headers={"WWW-Authenticate": "Bearer"},
  9560. )
  9561. if not _is_token_fresh(iat, user):
  9562. return JSONResponse(
  9563. status_code=401,
  9564. content={"detail": "Token no longer valid"},
  9565. headers={"WWW-Authenticate": "Bearer"},
  9566. )
  9567. except jwt.ExpiredSignatureError:
  9568. return JSONResponse(
  9569. status_code=401,
  9570. content={"detail": "Token has expired"},
  9571. headers={"WWW-Authenticate": "Bearer"},
  9572. )
  9573. except (jwt.InvalidTokenError, ValueError, Exception):
  9574. return JSONResponse(
  9575. status_code=401,
  9576. content={"detail": "Invalid token"},
  9577. headers={"WWW-Authenticate": "Bearer"},
  9578. )
  9579. return await call_next(request)
  9580. @app.middleware("http")
  9581. async def trace_id_middleware(request, call_next):
  9582. """Stamp every HTTP request with a trace ID and echo it back.
  9583. Decorated AFTER auth_middleware on purpose: Starlette stacks
  9584. @app.middleware decorators LIFO, so the last-decorated runs first
  9585. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  9586. which means auth-middleware log lines (and every line emitted on the
  9587. way down to and back from the route handler) all carry the same
  9588. trace ID. If we put it before auth, auth's logs would be stamped
  9589. with the *previous* request's ID — useless for correlation.
  9590. Honours an inbound ``X-Trace-Id`` header so callers running their
  9591. own tracing can correlate their span IDs with our log lines, but
  9592. only if the value passes the whitelist gate in
  9593. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  9594. rejected (too long, contains control chars, etc.) silently triggers
  9595. a freshly minted server-side ID rather than failing the request.
  9596. The minted (or echoed) ID is set on a ContextVar so that every log
  9597. record emitted during the request — application logs *and* uvicorn's
  9598. access log — carries it via TraceIDFilter, and is also written to
  9599. the ``X-Trace-Id`` response header so clients can pin a server-side
  9600. log search to the exact request they made.
  9601. """
  9602. from backend.app.core.trace import (
  9603. generate_trace_id,
  9604. normalise_inbound_trace_id,
  9605. trace_id_var,
  9606. )
  9607. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  9608. trace_id = inbound if inbound is not None else generate_trace_id()
  9609. token = trace_id_var.set(trace_id)
  9610. try:
  9611. response = await call_next(request)
  9612. finally:
  9613. # Reset the ContextVar so a record emitted in a totally
  9614. # unrelated background task that just happens to inherit this
  9615. # context doesn't keep referencing this request's ID forever.
  9616. # In practice ContextVar.reset is best-effort under asyncio
  9617. # task-spawn semantics, but the cost is one attribute write so
  9618. # we may as well do it.
  9619. trace_id_var.reset(token)
  9620. response.headers["X-Trace-Id"] = trace_id
  9621. return response
  9622. # API routes
  9623. app.include_router(auth.router, prefix=app_settings.api_prefix)
  9624. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  9625. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  9626. app.include_router(users.router, prefix=app_settings.api_prefix)
  9627. app.include_router(groups.router, prefix=app_settings.api_prefix)
  9628. app.include_router(printers.router, prefix=app_settings.api_prefix)
  9629. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  9630. app.include_router(archives.router, prefix=app_settings.api_prefix)
  9631. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  9632. app.include_router(finance.router, prefix=app_settings.api_prefix)
  9633. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  9634. app.include_router(labels.router, prefix=app_settings.api_prefix)
  9635. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  9636. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  9637. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  9638. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  9639. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  9640. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  9641. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  9642. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  9643. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  9644. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  9645. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  9646. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  9647. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  9648. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  9649. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  9650. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  9651. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  9652. app.include_router(updates.router, prefix=app_settings.api_prefix)
  9653. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  9654. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  9655. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  9656. app.include_router(camera.router, prefix=app_settings.api_prefix)
  9657. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  9658. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  9659. app.include_router(projects.router, prefix=app_settings.api_prefix)
  9660. app.include_router(library.router, prefix=app_settings.api_prefix)
  9661. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  9662. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  9663. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  9664. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  9665. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  9666. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  9667. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  9668. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  9669. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  9670. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  9671. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  9672. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  9673. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  9674. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  9675. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  9676. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  9677. app.include_router(system.router, prefix=app_settings.api_prefix)
  9678. app.include_router(support.router, prefix=app_settings.api_prefix)
  9679. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  9680. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  9681. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  9682. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  9683. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  9684. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  9685. app.include_router(obico.router, prefix=app_settings.api_prefix)
  9686. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  9687. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  9688. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  9689. # Serve static files (React build)
  9690. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  9691. # Compressed, and cached for good where Vite hashed the name (#3175).
  9692. app.mount(
  9693. "/assets",
  9694. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  9695. name="assets",
  9696. )
  9697. if (app_settings.static_dir / "img").exists():
  9698. app.mount(
  9699. "/img",
  9700. StaticFiles(directory=app_settings.static_dir / "img"),
  9701. name="img",
  9702. )
  9703. if (app_settings.static_dir / "icons").exists():
  9704. app.mount(
  9705. "/icons",
  9706. StaticFiles(directory=app_settings.static_dir / "icons"),
  9707. name="icons",
  9708. )
  9709. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  9710. # falls through to the SPA catch-all and returns index.html, which the
  9711. # browser's font sanitizer rejects ("downloadable font: rejected by
  9712. # sanitizer").
  9713. if (app_settings.static_dir / "fonts").exists():
  9714. app.mount(
  9715. "/fonts",
  9716. StaticFiles(directory=app_settings.static_dir / "fonts"),
  9717. name="fonts",
  9718. )
  9719. @app.get("/")
  9720. async def serve_frontend():
  9721. """Serve the React frontend."""
  9722. index_file = app_settings.static_dir / "index.html"
  9723. if index_file.exists():
  9724. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  9725. return {
  9726. "message": "Bambuddy API",
  9727. "docs": "/docs",
  9728. "frontend": "Build and place React app in /static directory",
  9729. }
  9730. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  9731. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  9732. # forever, but the HTML wrapping it is the only file that knows which hash
  9733. # is current. Without explicit cache-control headers Chromium decides
  9734. # heuristically (typically 10% of the time since Last-Modified) and on
  9735. # long-running kiosks happily serves stale HTML across browser restarts.
  9736. # That stale HTML references an old bundle hash, the old bundle is also
  9737. # in the disk cache, and the user ends up running pre-update JS forever
  9738. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  9739. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  9740. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  9741. @app.get("/health")
  9742. async def health_check():
  9743. """Health check endpoint."""
  9744. return {"status": "healthy"}
  9745. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  9746. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  9747. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  9748. # in deployment debugging.
  9749. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  9750. async def serve_manifest():
  9751. """Serve PWA manifest."""
  9752. manifest_file = app_settings.static_dir / "manifest.json"
  9753. if manifest_file.exists():
  9754. return FileResponse(manifest_file, media_type="application/manifest+json")
  9755. return {"error": "Manifest not found"}
  9756. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  9757. async def serve_service_worker():
  9758. """Serve service worker."""
  9759. sw_file = app_settings.static_dir / "sw.js"
  9760. if sw_file.exists():
  9761. return FileResponse(
  9762. sw_file,
  9763. media_type="application/javascript",
  9764. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  9765. )
  9766. return {"error": "Service worker not found"}
  9767. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  9768. async def serve_sw_register():
  9769. """Serve the service-worker registration bootstrap script.
  9770. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  9771. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  9772. """
  9773. reg_file = app_settings.static_dir / "sw-register.js"
  9774. if reg_file.exists():
  9775. return FileResponse(reg_file, media_type="application/javascript")
  9776. return {"error": "sw-register.js not found"}
  9777. # ── GCode viewer static files ────────────────────────────────────────────────
  9778. # Catch-all route for React Router (must be last)
  9779. @app.get("/{full_path:path}")
  9780. async def serve_spa(full_path: str):
  9781. """Serve React app for client-side routing."""
  9782. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  9783. if full_path.startswith("api/"):
  9784. from fastapi import HTTPException
  9785. raise HTTPException(status_code=404, detail="Not found")
  9786. index_file = app_settings.static_dir / "index.html"
  9787. if index_file.exists():
  9788. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  9789. return {"error": "Frontend not built"}