main.py 346 KB

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