main.py 331 KB

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