main.py 346 KB

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