main.py 330 KB

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