main.py 298 KB

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