main.py 331 KB

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