main.py 321 KB

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