main.py 358 KB

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