main.py 417 KB

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