main.py 571 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import re
  8. import secrets
  9. import time
  10. from contextlib import asynccontextmanager
  11. from datetime import datetime, timedelta, timezone
  12. from logging.handlers import RotatingFileHandler
  13. from pathlib import Path, PurePosixPath
  14. from urllib.parse import urlparse
  15. from fastapi import FastAPI
  16. from fastapi.encoders import jsonable_encoder
  17. from fastapi.exceptions import RequestValidationError
  18. from fastapi.responses import FileResponse, JSONResponse
  19. from fastapi.staticfiles import StaticFiles
  20. from sqlalchemy import delete, inspect as sa_inspect, or_, select, text, update
  21. from sqlalchemy.exc import IntegrityError
  22. from sqlalchemy.orm.exc import StaleDataError
  23. from backend.app.api.routes import (
  24. ams_history,
  25. announcements,
  26. api_keys,
  27. archive_purge,
  28. archives,
  29. auth,
  30. bug_report,
  31. camera,
  32. camwall,
  33. cloud,
  34. connected_apps,
  35. discovery,
  36. external_links,
  37. filaments,
  38. finance,
  39. firmware,
  40. github_backup,
  41. groups,
  42. ha_sensors,
  43. inventory,
  44. kprofiles,
  45. labels,
  46. library,
  47. library_tags,
  48. library_trash,
  49. library_variants,
  50. local_backup,
  51. local_presets,
  52. location_ha_sensors,
  53. maintenance,
  54. makerworld,
  55. manyfold,
  56. metrics,
  57. mfa,
  58. notification_templates,
  59. notifications,
  60. obico,
  61. orca_cloud,
  62. overlay_branding,
  63. pending_uploads,
  64. pipeline_runs,
  65. print_log,
  66. print_queue,
  67. printer_locations,
  68. printer_sensor_history,
  69. printers,
  70. projects,
  71. scheduled_dryings,
  72. settings as settings_routes,
  73. slice_jobs,
  74. slicer_pipelines,
  75. slicer_presets,
  76. smart_plugs,
  77. sponsor_prompt,
  78. spoolbuddy,
  79. spoolman,
  80. spoolman_inventory,
  81. support,
  82. system,
  83. updates,
  84. user_notifications,
  85. users,
  86. virtual_printers,
  87. webhook,
  88. websocket,
  89. )
  90. from backend.app.api.routes.maintenance import (
  91. _get_printer_maintenance_internal,
  92. ensure_default_types,
  93. maintenance_alert_values,
  94. )
  95. from backend.app.api.routes.support import init_debug_logging
  96. from backend.app.core.config import APP_VERSION, settings as app_settings
  97. from backend.app.core.database import async_session, engine, init_db
  98. from backend.app.core.static_assets import AssetStaticFiles
  99. from backend.app.core.tasks import spawn_background_task
  100. from backend.app.core.websocket import ws_manager
  101. from backend.app.services import kprofile_drift, print_dispatch_context, slot_unlink_grace
  102. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  103. from backend.app.services.archive_cost_estimate import (
  104. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  105. )
  106. from backend.app.services.archive_purge import archive_purge_service
  107. from backend.app.services.bambu_ftp import (
  108. RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  109. FileNotOnPrinterError,
  110. cache_3mf_download,
  111. clear_3mf_cache,
  112. download_file_async,
  113. download_file_try_paths_async,
  114. ftps_handshake_blocked,
  115. get_cached_3mf,
  116. get_ftp_retry_settings,
  117. normalize_3mf_name,
  118. with_ftp_retry,
  119. )
  120. from backend.app.services.bambu_mqtt import PrinterState
  121. from backend.app.services.camera_light import camera_light
  122. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  123. from backend.app.services.github_backup import github_backup_service
  124. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  125. from backend.app.services.library_trash import library_trash_service
  126. from backend.app.services.local_backup import local_backup_service
  127. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  128. from backend.app.services.mqtt_relay import mqtt_relay
  129. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  130. from backend.app.services.notification_service import notification_service
  131. from backend.app.services.notify_live_activities import notify_live_activities
  132. from backend.app.services.notify_widgets import notify_widgets
  133. from backend.app.services.obico_detection import obico_detection_service
  134. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  135. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  136. from backend.app.services.print_scheduler import scheduler as print_scheduler
  137. from backend.app.services.print_storage import (
  138. REASON_FTP_TRANSFER_FAILED,
  139. REASON_FTPS_COOLOFF,
  140. external_storage_present,
  141. ftp_probe_paths,
  142. print_file_reachable_over_ftp,
  143. )
  144. from backend.app.services.printer_manager import (
  145. init_printer_connections,
  146. parse_plate_id,
  147. printer_manager,
  148. printer_state_to_dict,
  149. resolve_plate_id,
  150. )
  151. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  152. from backend.app.services.slot_nozzle import (
  153. nozzle_diameter_for_extruder,
  154. nozzle_flow_for_extruder,
  155. )
  156. from backend.app.services.smart_plug_manager import smart_plug_manager
  157. from backend.app.services.spool_assignment_notifications import (
  158. notify_missing_spool_assignments_on_print_start,
  159. )
  160. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  161. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  162. from backend.app.services.spoolman_tracking import (
  163. cleanup_tracking as _cleanup_spoolman_tracking,
  164. release_archived_slot_rows as _release_archived_spoolman_slots,
  165. report_usage as _report_spoolman_usage,
  166. store_print_data as _store_spoolman_print_data,
  167. )
  168. from backend.app.services.telegram_reactions import telegram_reaction_poller
  169. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  170. from backend.app.utils.ams_humidity import ams_humidity_percent
  171. from backend.app.utils.filament_types import printer_filament_type
  172. from backend.app.utils.fts_routing import extruder_for_inlet
  173. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  174. from backend.app.utils.print_jobs import is_internal_printer_job
  175. # =============================================================================
  176. # Dependency Check - runs before other imports to give helpful error messages
  177. # =============================================================================
  178. def _start_error_server(missing_packages: list):
  179. """Start a minimal HTTP server to display dependency errors in browser."""
  180. import os
  181. import signal
  182. from http.server import BaseHTTPRequestHandler, HTTPServer
  183. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  184. html = f"""<!DOCTYPE html>
  185. <html>
  186. <head>
  187. <title>Bambuddy - Setup Required</title>
  188. <style>
  189. body {{
  190. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  191. background: #0f172a; color: #e2e8f0;
  192. display: flex; justify-content: center; align-items: center;
  193. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  194. }}
  195. .container {{
  196. background: #1e293b; border-radius: 12px; padding: 40px;
  197. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  198. }}
  199. h1 {{ color: #f87171; margin-bottom: 10px; }}
  200. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  201. .packages {{
  202. background: #0f172a; border-radius: 8px; padding: 20px;
  203. margin: 20px 0; text-align: left;
  204. }}
  205. .packages ul {{ margin: 0; padding-left: 20px; }}
  206. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  207. .command {{
  208. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  209. margin: 15px 0; font-family: monospace; color: #4ade80;
  210. text-align: left; overflow-x: auto;
  211. }}
  212. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  213. </style>
  214. </head>
  215. <body>
  216. <div class="container">
  217. <h1>Setup Required</h1>
  218. <h2>Missing Python packages</h2>
  219. <div class="packages"><ul>{packages_html}</ul></div>
  220. <p>To fix, run this command on your server:</p>
  221. <div class="command">pip install -r requirements.lock</div>
  222. <p>Or if using a virtual environment:</p>
  223. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  224. <p class="note">After installing, restart Bambuddy:<br>
  225. <code>sudo systemctl restart bambuddy</code></p>
  226. </div>
  227. </body>
  228. </html>"""
  229. class ErrorHandler(BaseHTTPRequestHandler):
  230. def do_GET(self):
  231. self.send_response(503)
  232. self.send_header("Content-type", "text/html")
  233. self.end_headers()
  234. self.wfile.write(html.encode())
  235. def log_message(self, format, *args):
  236. print(f"[Error Server] {args[0]}")
  237. port = int(os.environ.get("PORT", 8000))
  238. print(f"\nStarting error server on http://0.0.0.0:{port}")
  239. print("Visit this URL in your browser to see the error details.\n")
  240. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  241. def shutdown(signum, frame):
  242. print("\nShutting down error server...")
  243. raise SystemExit(0)
  244. signal.signal(signal.SIGTERM, shutdown)
  245. signal.signal(signal.SIGINT, shutdown)
  246. server.serve_forever()
  247. def check_dependencies():
  248. """Check that all required packages are installed."""
  249. missing = []
  250. # Map of import name -> package name (for pip install)
  251. required = {
  252. "jwt": "PyJWT",
  253. "fastapi": "fastapi",
  254. "uvicorn": "uvicorn",
  255. "sqlalchemy": "sqlalchemy",
  256. "aiosqlite": "aiosqlite",
  257. "pydantic": "pydantic",
  258. "paho.mqtt": "paho-mqtt",
  259. }
  260. for module, package in required.items():
  261. try:
  262. __import__(module)
  263. except ImportError:
  264. missing.append(package)
  265. if missing:
  266. print("\n" + "=" * 60)
  267. print("ERROR: Missing required Python packages!")
  268. print("=" * 60)
  269. print(f"\nMissing packages: {', '.join(missing)}")
  270. print("\nTo fix, run:")
  271. print(" pip install -r requirements.lock")
  272. print("\nOr if using a virtual environment:")
  273. print(" ./venv/bin/pip install -r requirements.lock")
  274. print("=" * 60 + "\n")
  275. _start_error_server(missing)
  276. check_dependencies()
  277. # =============================================================================
  278. # Import settings first for logging configuration
  279. # Configure logging based on settings
  280. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  281. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  282. log_level = getattr(logging, log_level_str, logging.INFO)
  283. # Trace ID column ([-] when no request scope is active — startup, MQTT
  284. # callbacks, scheduled tasks not chained from a request — so the column
  285. # stays visually aligned and missing values are obvious in grep). See
  286. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  287. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  288. # Create root logger
  289. root_logger = logging.getLogger()
  290. root_logger.setLevel(log_level)
  291. # Trace-ID injection: this filter populates record.trace_id from the
  292. # per-request ContextVar so the format string above can reference it.
  293. # Attached to each HANDLER (not the root logger) because Python's
  294. # logging semantics only invoke a logger's filters on records that
  295. # *originated* at that logger — records propagated up from child
  296. # loggers (every named logger in the app) never trigger root's filter.
  297. # Putting it on the handlers means every record any handler emits gets
  298. # trace_id injected just before the formatter runs, regardless of which
  299. # logger created the record. Without this, the formatter raises
  300. # KeyError on every child-logger record and the record is silently
  301. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  302. # partially" bug we hit. See backend/app/core/trace.py for the
  303. # ContextVar the filter reads.
  304. from backend.app.core.logging_filters import RefusedHeaderRedactFilter
  305. from backend.app.core.response_redaction import RefusedHeaderResponseMask
  306. from backend.app.core.trace import TraceIDFilter
  307. _trace_id_filter = TraceIDFilter()
  308. # Console handler - always enabled
  309. console_handler = logging.StreamHandler()
  310. console_handler.setLevel(log_level)
  311. console_handler.setFormatter(logging.Formatter(log_format))
  312. console_handler.addFilter(_trace_id_filter)
  313. # A refused header's value (often a token) masked before the line is written.
  314. _refused_header_filter = RefusedHeaderRedactFilter()
  315. console_handler.addFilter(_refused_header_filter)
  316. root_logger.addHandler(console_handler)
  317. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  318. """Send uvicorn's own loggers to bambuddy.log as well.
  319. Neither reaches the root handler: uvicorn.access has propagate=False, and
  320. uvicorn.error propagates only to "uvicorn", which has propagate=False.
  321. uvicorn.access is the record of which endpoint changed server state;
  322. uvicorn.error is where an unhandled route error is logged with its
  323. traceback ("Exception in ASGI application").
  324. """
  325. for name in ("uvicorn.access", "uvicorn.error"):
  326. logging.getLogger(name).addHandler(handler)
  327. # File handler - only in production or if explicitly enabled
  328. if app_settings.log_to_file:
  329. log_file = app_settings.log_dir / "bambuddy.log"
  330. file_handler = RotatingFileHandler(
  331. log_file,
  332. maxBytes=app_settings.log_max_bytes,
  333. backupCount=app_settings.log_backup_count,
  334. encoding="utf-8",
  335. )
  336. file_handler.setLevel(log_level)
  337. file_handler.setFormatter(logging.Formatter(log_format))
  338. file_handler.addFilter(_trace_id_filter)
  339. file_handler.addFilter(_refused_header_filter)
  340. root_logger.addHandler(file_handler)
  341. logging.info("Logging to file: %s", log_file)
  342. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  343. # access logger with propagate=False by default, so without this attach
  344. # there is no on-disk record of which endpoint triggered a server-state
  345. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  346. # for exactly this reason. Filtered to write methods only
  347. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  348. # frontend don't churn the rotation window faster than it's useful.
  349. from backend.app.core.logging_filters import (
  350. CancelledPoolNoiseFilter,
  351. WriteRequestsOnlyFilter,
  352. )
  353. _attach_file_handler_to_uvicorn(file_handler)
  354. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  355. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  356. # Uvicorn's access logger has propagate=False (its own default), so the
  357. # root-attached TraceIDFilter never sees these records. Attach a
  358. # second instance directly so HTTP access lines carry the same trace
  359. # ID column as the application logs they correlate with.
  360. uvicorn_access_logger.addFilter(TraceIDFilter())
  361. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  362. # BaseHTTPMiddleware cancelling the inner task scope on client
  363. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  364. # underlying transaction leak; this filter only suppresses the residual
  365. # log records that pre-existing pools still emit during their cleanup.
  366. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  367. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  368. # handler (console included), whether or not file logging is on.
  369. from backend.app.core.logging_filters import ( # noqa: E402
  370. QueryTokenRedactFilter,
  371. ShutdownCancelledRequestFilter,
  372. )
  373. # First, so the traceback of a stream cancelled at shutdown is dropped before
  374. # the filters below render it.
  375. logging.getLogger("uvicorn.error").addFilter(ShutdownCancelledRequestFilter())
  376. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  377. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  378. logging.getLogger(_uvicorn_logger).addFilter(_refused_header_filter)
  379. # These stay at WARNING even in debug mode: at INFO/DEBUG httpx/httpcore log
  380. # full request URLs, and some carry credentials (bot tokens, webhook URLs, API
  381. # keys in the query). Same as the runtime log-level toggle in support.py.
  382. logging.getLogger("httpcore").setLevel(logging.WARNING)
  383. logging.getLogger("httpx").setLevel(logging.WARNING)
  384. # aiosqlite logs every statement with its parameters at DEBUG.
  385. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  386. # Reduce noise from third-party libraries in production
  387. if not app_settings.debug:
  388. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  389. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  390. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  391. # Track active prints: {(printer_id, filename): archive_id}
  392. _active_prints: dict[tuple[int, str], int] = {}
  393. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  394. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  395. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  396. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  397. # instead of running its own grab-now chain when present, so the finish photo
  398. # captures the better-framed pre-bed-drop moment without us having to force
  399. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  400. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  401. #
  402. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  403. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  404. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  405. # bank and the others are not — so the consumer can't tell them apart and
  406. # must not rotate again.
  407. _stage22_finish_frames: dict[int, bytes] = {}
  408. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  409. # `finally` block (whether it captured a frame or not). The consumer in
  410. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  411. # so the FINISH-state fallback path — where moment and completion are dispatched
  412. # back-to-back — doesn't race past the producer with an empty pop, and the
  413. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  414. # grab (Bambu printers allow only one RTSP client at a time).
  415. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  416. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  417. # layer-change and on print-progress advances (#2547) while the model is still
  418. # printing, then consumed by the FINISH-state finish-photo path when the
  419. # dispatcher recorded that it injected End G-code into this print. Bambu
  420. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  421. # plate-swap) has run, so a live grab there would capture the swapped/empty
  422. # plate.
  423. #
  424. # The load-bearing property: both drivers are print telemetry that stops before
  425. # the End G-code executes — no further layer_num increases, and mc_percent
  426. # freezes — so the last banked frame is always the finished print before the
  427. # swap. Anything added as a third driver must hold that same property.
  428. _inprint_frame_bank: dict[int, bytes] = {}
  429. # Monotonic timestamp of the last banked frame per printer — throttles banking
  430. # so tall prints don't add a camera grab on every layer.
  431. _inprint_frame_bank_ts: dict[int, float] = {}
  432. # Minimum seconds between banked frames, except the final object layer which
  433. # always refreshes for the best framing.
  434. _INPRINT_BANK_MIN_INTERVAL = 25.0
  435. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  436. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  437. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  438. # the first connected status update for that connection; transitions back
  439. # to False whenever we observe `state.connected = False` so the next
  440. # reconnect re-arms reconciliation. Keyed by printer_id.
  441. _printer_reconciled_since_connect: dict[int, bool] = {}
  442. # Same edge, same keying, for priming the printer's calibration table exactly
  443. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  444. # is otherwise filled only when someone opens the Profiles page or Configure
  445. # Slot, when a GitHub backup runs, or when the printer happens to answer
  446. # somebody else's query on the report topic. Until then the AMS slot card has
  447. # no K value to show on the printers whose trays carry none of their own
  448. # (#2854 — H2-series report cali_idx and nothing more).
  449. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  450. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  451. # {(printer_id, filename): archive_id}
  452. _expected_prints: dict[tuple[int, str], int] = {}
  453. # Archives of the running prints Bambuddy dispatched itself: adopted from an
  454. # expected print, or found with Bambuddy's dispatch marker. _active_prints holds
  455. # every print on_print_start archived, those started from Bambu Studio, Handy or
  456. # the printer's screen included, so it is no proof of ownership on its own.
  457. _owned_print_archive_ids: set[int] = set()
  458. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  459. # Used by usage tracker to map 3MF slots to physical AMS trays
  460. _print_ams_mappings: dict[int, list[int]] = {}
  461. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  462. _print_cost_center_ids: dict[int, int] = {}
  463. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  464. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  465. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  466. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  467. # for the queue path. Cleared on print completion or TTL eviction.
  468. _print_plate_ids: dict[int, int] = {}
  469. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  470. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  471. _last_progress_milestone: dict[int, int] = {}
  472. # Track whether first layer complete notification has been sent for current print
  473. _first_layer_notified: dict[int, bool] = {}
  474. # Track whether we already sent a kill-switch stop for the current unauthorized print
  475. _unauthorized_print_kill_sent: set[int] = set()
  476. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  477. # lookup briefly so an unknown active print does not query the database on
  478. # every status frame. A short TTL keeps settings changes responsive.
  479. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  480. _kill_switch_setting_cache: tuple[bool, float] | None = None
  481. # Provider notification started when the kill switch stops a print. The later
  482. # MQTT print-complete callback awaits this task and only sends its regular
  483. # provider notification when the immediate attempt failed.
  484. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  485. # HMS faults already notified, with when each was last seen:
  486. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  487. # fault that flickers beside a held notice was forgotten on every gap and
  488. # notified on every return (#3226). The window is long because the measured
  489. # gaps reach 64 s.
  490. _notified_hms_errors: dict[int, dict[str, float]] = {}
  491. _HMS_CLEAR_GRACE_SECONDS = 600.0
  492. # The print state each printer was last seen in, and the faults recorded before
  493. # it last changed, which are forgotten as soon as they are gone (see
  494. # _take_new_hms_faults).
  495. _hms_print_state: dict[int, str] = {}
  496. _hms_forget_when_gone: dict[int, set[str]] = {}
  497. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  498. # Used for snapshot-diff detection at print completion
  499. _timelapse_baselines: dict[int, set[str]] = {}
  500. # Track printers waiting for bed to cool after print completion.
  501. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  502. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  503. _bed_cool_waiters: dict[int, dict] = {}
  504. # Track printers where the user explicitly stopped the print from the queue UI.
  505. # When on_print_complete fires with status "failed" for these printers we treat it
  506. # as "cancelled" (stopped by user) so the correct notification email is sent.
  507. _user_stopped_printers: set[int] = set()
  508. # Printers whose running print the kill switch stopped. Their completion is a
  509. # cancel with the reason "killSwitch", not the "failed" the printer reports.
  510. _kill_switch_stopped: set[int] = set()
  511. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  512. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  513. # holds the previous observation so we only fire on the True → False edge (a
  514. # False → False repeat doesn't notify; an initial False at startup doesn't
  515. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  516. # holds the per-printer pending asyncio task that fires the notification
  517. # after a debounce window — cancelled if the printer reconnects before the
  518. # window elapses, so transient MQTT blips don't flood the user.
  519. _printer_last_connected: dict[int, bool] = {}
  520. # Printers whose relay offline event went out, so the reconnect publishes the
  521. # matching online event and a blip shorter than the debounce publishes neither.
  522. _printer_offline_published: set[int] = set()
  523. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  524. # Debounce: a printer must stay offline this long before we notify. Sized
  525. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  526. # so a single stale-trigger cooldown isn't enough to fire — only a real
  527. # offline that survives one reconnect attempt notifies.
  528. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  529. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  530. # when status="failed" to label the print's failure_reason in archives.
  531. #
  532. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  533. # which is wrong on two counts:
  534. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  535. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  536. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  537. # the public wiki) as part of its user-cancel sequence. Matching on the module
  538. # alone caused user-cancellations to be archived as "Layer shift" failures.
  539. # We now match by full short code only — anything not in this map leaves
  540. # failure_reason=None rather than guessing.
  541. # Values are the canonical camelCase failure-reason keys, NOT display labels
  542. # (issue #2974). The vocabulary is enforced on writes by
  543. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  544. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  545. # Statistics breakdown. Storing a label here instead put a second spelling of
  546. # the same cause into one column: the Failure Analysis widget groups on the raw
  547. # value, so a print the backend classified and an identical one a user
  548. # classified counted as two different reasons, and the label form could never
  549. # be translated because there was no key for ``t()`` to resolve.
  550. _HMS_FAILURE_REASONS: dict[str, str] = {
  551. # Layer shift / step loss
  552. "0300_4057": "layerShift",
  553. "0300_4068": "layerShift",
  554. "0300_800C": "layerShift",
  555. # Filament runout (printer-side & per-AMS-slot)
  556. "0300_8004": "filamentRunout",
  557. "0700_8011": "filamentRunout",
  558. "0701_8011": "filamentRunout",
  559. "0702_8011": "filamentRunout",
  560. "0703_8011": "filamentRunout",
  561. "0704_8011": "filamentRunout",
  562. "0705_8011": "filamentRunout",
  563. "0706_8011": "filamentRunout",
  564. "0707_8011": "filamentRunout",
  565. "07FF_8011": "filamentRunout",
  566. # Clogged nozzle / extruder
  567. "0300_4006": "cloggedNozzle",
  568. "0300_8016": "cloggedNozzle",
  569. "0300_801C": "cloggedNozzle",
  570. "0700_8003": "cloggedNozzle",
  571. "0700_8007": "cloggedNozzle",
  572. "0700_8013": "cloggedNozzle",
  573. "0701_8003": "cloggedNozzle",
  574. "0701_8007": "cloggedNozzle",
  575. "0701_8013": "cloggedNozzle",
  576. "0702_8003": "cloggedNozzle",
  577. # AI print monitoring — spaghetti / the model coming off the plate.
  578. # `spaghettiDetached` is a key the archive editor already offers for this
  579. # failure mode, not a new one, so a derived reason opens the dropdown on
  580. # that option rather than blank — and survives the next save, which clears
  581. # any value the editor does not recognise.
  582. #
  583. # A module-0x0C row is safe here despite the warning above: that warning is
  584. # about matching on the module alone, and 0C00_8042 is a full short code
  585. # with a documented meaning ("The AI print monitor has detected a spaghetti
  586. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  587. # cannot collide.
  588. #
  589. # 0300_8003's own text ends "before continuing your print", but on an X2D
  590. # it arrives with the print already paused, offering only
  591. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  592. #
  593. # Two neighbours are left out on purpose, so this does not get re-derived:
  594. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  595. # reads as a warning about a print that is still running, not a halt.
  596. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  597. # the waste chute. That is not the print failing.
  598. #
  599. # That line is drawn from the text, not from `severity`, because severity
  600. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  601. # module/error word with no level in it, and bambu_mqtt.py gives every
  602. # print_error entry a flat severity=3. Matching on the short code alone is
  603. # the right shape for derive_failure_reason, not an omission.
  604. "0300_8003": "spaghettiDetached",
  605. "0C00_8042": "spaghettiDetached",
  606. }
  607. def _hms_short_code(attr: int, code: int | str) -> str:
  608. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  609. if isinstance(code, str):
  610. code_int = int(code.replace("0x", ""), 16) if code else 0
  611. else:
  612. code_int = int(code or 0)
  613. attr_int = int(attr or 0)
  614. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  615. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  616. """Derive the failure_reason key for an archived print.
  617. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  618. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  619. no HMS code matches (don't guess — null is honest). The keys are the
  620. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  621. translated at render time.
  622. """
  623. if status in ("aborted", "cancelled"):
  624. return "userCancelled"
  625. if status != "failed":
  626. return None
  627. for err in hms_errors or []:
  628. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  629. if short_code in _HMS_FAILURE_REASONS:
  630. return _HMS_FAILURE_REASONS[short_code]
  631. return None
  632. # Track created_by_id for expected prints so the user email can be sent even when
  633. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  634. # {(printer_id, filename): created_by_id}
  635. _expected_print_creators: dict[tuple[int, str], int] = {}
  636. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  637. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  638. # updates for the same printer in quick succession (~30 ms apart, observed in
  639. # the wild on H2D + dual AMS).
  640. #
  641. # Without this serialisation, two concurrent on_ams_change callbacks each read
  642. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  643. # the second commit hits
  644. # IntegrityError: duplicate key value violates unique constraint
  645. # "spool_assignment_printer_id_ams_id_tray_id_key"
  646. # SQLite's WAL serial-write semantics had been silently swallowing the race
  647. # until optional Postgres support landed (asyncpg allows true concurrent
  648. # transactions and surfaces the constraint violation).
  649. #
  650. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  651. # assign) are inside the lock. The Spoolman sync block further down stays
  652. # concurrent because it's network-bound and idempotent.
  653. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  654. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  655. """Return the per-printer assignment lock, creating it on first use."""
  656. lock = _ams_assignment_locks.get(printer_id)
  657. if lock is None:
  658. lock = asyncio.Lock()
  659. _ams_assignment_locks[printer_id] = lock
  660. return lock
  661. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  662. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  663. # tag tuple changes for the slot. Cleared when the slot is reported empty
  664. # so remove + reinsert reliably re-prompts the UI.
  665. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  666. async def _broadcast_unknown_tag(
  667. *,
  668. printer_id: int,
  669. ams_id: int,
  670. tray_id: int,
  671. tag_uid: str,
  672. tray_uuid: str,
  673. tray_type: str | None = None,
  674. tray_color: str | None = None,
  675. tray_sub_brands: str | None = None,
  676. tray_count: int | None = None,
  677. ) -> None:
  678. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  679. _logger = logging.getLogger(__name__)
  680. slot_key = (ams_id, tray_id)
  681. tag_key = (tag_uid or "", tray_uuid or "")
  682. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  683. if per_printer.get(slot_key) == tag_key:
  684. _logger.debug(
  685. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  686. printer_id,
  687. ams_id,
  688. tray_id,
  689. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  690. )
  691. return
  692. _logger.info(
  693. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  694. printer_id,
  695. ams_id,
  696. tray_id,
  697. tray_type,
  698. tray_color,
  699. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  700. )
  701. # Broadcast first; only commit the dedup if the WS write succeeds.
  702. # If broadcast raises, the next MQTT push retries instead of being
  703. # permanently silenced by a poisoned dedup entry.
  704. await ws_manager.broadcast(
  705. {
  706. "type": "unknown_tag",
  707. "printer_id": printer_id,
  708. "ams_id": ams_id,
  709. "tray_id": tray_id,
  710. "tag_uid": tag_uid,
  711. "tray_uuid": tray_uuid,
  712. "tray_type": tray_type,
  713. "tray_color": tray_color,
  714. "tray_sub_brands": tray_sub_brands,
  715. "tray_count": tray_count,
  716. }
  717. )
  718. per_printer[slot_key] = tag_key
  719. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  720. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  721. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  722. if per_printer is None:
  723. return
  724. per_printer.pop((ams_id, tray_id), None)
  725. # TTL for expected-print entries: evict registrations older than this to prevent
  726. # unbounded growth when a print is registered but never starts (e.g. printer
  727. # disconnect, app restart, print started from the printer panel).
  728. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  729. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  730. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  731. # Cleanup loop interval
  732. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  733. _expected_prints_cleanup_task: asyncio.Task | None = None
  734. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  735. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  736. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  737. possible_keys: list[tuple[int, str]] = []
  738. filename = (state.gcode_file or state.current_print or "").strip()
  739. subtask_name = (state.subtask_name or "").strip()
  740. if subtask_name:
  741. possible_keys.append((printer_id, subtask_name))
  742. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  743. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  744. if filename:
  745. base_name = filename.rsplit("/", 1)[-1]
  746. if base_name.endswith(".gcode.3mf"):
  747. root_name = base_name[: -len(".gcode.3mf")]
  748. possible_keys.append((printer_id, root_name))
  749. possible_keys.append((printer_id, base_name))
  750. possible_keys.append((printer_id, f"{root_name}.gcode"))
  751. possible_keys.append((printer_id, f"{root_name}.3mf"))
  752. elif base_name.endswith(".3mf"):
  753. root_name = base_name[: -len(".3mf")]
  754. possible_keys.append((printer_id, root_name))
  755. possible_keys.append((printer_id, base_name))
  756. elif base_name.endswith(".gcode"):
  757. root_name = base_name[: -len(".gcode")]
  758. possible_keys.append((printer_id, root_name))
  759. possible_keys.append((printer_id, f"{root_name}.3mf"))
  760. possible_keys.append((printer_id, base_name))
  761. else:
  762. possible_keys.append((printer_id, base_name))
  763. possible_keys.append((printer_id, f"{base_name}.3mf"))
  764. return possible_keys
  765. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  766. """The id of who started the print, unless that user has been deleted since.
  767. Deleting a user forgets them in printer_manager, but a print that ended a
  768. moment before still holds them.
  769. """
  770. if not print_user or print_user.get("user_id") is None:
  771. return None
  772. from backend.app.models.user import User
  773. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  774. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  775. """Check the cheap, process-local print ownership signals."""
  776. if printer_manager.get_current_print_user(printer_id):
  777. return True
  778. return any(
  779. key in _expected_prints or _active_prints.get(key) in _owned_print_archive_ids
  780. for key in _build_status_print_keys(printer_id, state)
  781. )
  782. def _bind_active_print(
  783. printer_id: int,
  784. archive_id: int,
  785. archive_filename: str | None,
  786. filename: str | None = None,
  787. subtask_name: str | None = None,
  788. ) -> None:
  789. """Track a running print under every name its completion may report.
  790. One set for every path that binds a print (new archive, expected print,
  791. restart resume, fallback): the archive's file name, the name the printer
  792. reported, and the subtask with and without ``.3mf``. Paths that registered
  793. fewer names lost the bound archive at completion, and with it the plate
  794. restore's height (#3240), whenever MQTT reported a name they had left out.
  795. """
  796. for name in {archive_filename, filename, f"{subtask_name}.3mf" if subtask_name else None, subtask_name}:
  797. if name:
  798. _active_prints[(printer_id, name)] = archive_id
  799. def _mark_owned_if_dispatched(archive) -> None:
  800. """Remember a running print's archive as Bambuddy's when it carries a
  801. dispatch marker Bambuddy writes itself: ``billing_run_id`` (minted per
  802. dispatch in the scheduler) or ``created_by_id`` (from the queue item)."""
  803. if archive.billing_run_id is not None or archive.created_by_id is not None:
  804. _owned_print_archive_ids.add(archive.id)
  805. async def _is_printer_kill_switch_enabled_cached() -> bool:
  806. """Return the kill-switch setting without querying on every MQTT frame."""
  807. global _kill_switch_setting_cache
  808. now = time.monotonic()
  809. if _kill_switch_setting_cache is not None:
  810. enabled, expires_at = _kill_switch_setting_cache
  811. if now < expires_at:
  812. return enabled
  813. async with async_session() as db:
  814. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  815. enabled = await is_printer_kill_switch_enabled(db)
  816. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  817. return enabled
  818. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  819. """Resolve whether the current print was started by Bambuddy.
  820. ``None`` means identity is not yet safe to decide. The kill switch must
  821. defer in that case: stopping a print is irreversible, and the first status
  822. frames after a restart may arrive before all subtask fields are populated.
  823. """
  824. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  825. return True
  826. # The printer's built-in calibration runs (Bambuddy's Calibrate, the
  827. # printer's screen) play gcode from its read-only system partition, where no
  828. # user file can be. Only that path counts: a calibration *name* proves
  829. # nothing, since Bambu Studio's pressure-advance print reports a user-style
  830. # path, and any print can be given that name.
  831. if str(getattr(state, "gcode_file", "") or "").startswith("/usr/"):
  832. return True
  833. # A1, A1 Mini, P1 and A2L report the same calibration as a bare file name,
  834. # which nothing distinguishes from a user's file given that name, so it is
  835. # not exempt: with the kill switch on, calibrate on those printers with the
  836. # switch off.
  837. possible_keys = _build_status_print_keys(printer_id, state)
  838. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  839. # is on disk. subtask_id is minted per print and pins the answer to the job
  840. # actually running, rather than to an unrelated one that reuses a filename.
  841. raw_subtask_id = getattr(state, "subtask_id", None)
  842. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  843. if subtask_id == "":
  844. # Not reported yet: the first frames after a restart can lack it.
  845. return None
  846. from backend.app.models.archive import PrintArchive
  847. if subtask_id == "0":
  848. # A print started outside the cloud from Bambu Studio, Handy or the
  849. # printer's screen reports "0", so there is no id to match: one of
  850. # Bambuddy's printing archives on this printer under the name the
  851. # printer reports, compared as the printer echoes names (spaces become
  852. # underscores). Nothing reported to compare yet: wait.
  853. reported = {_normalise_subtask_name(name) for _pid, name in possible_keys} - {""}
  854. if not reported:
  855. return None
  856. dispatched = await db.execute(
  857. select(PrintArchive)
  858. .where(
  859. PrintArchive.printer_id == printer_id,
  860. PrintArchive.status == "printing",
  861. or_(PrintArchive.billing_run_id.is_not(None), PrintArchive.created_by_id.is_not(None)),
  862. # An archive with a real id of its own is a print that reported
  863. # one: a "0" print is not it, even under the same name (one whose
  864. # completion was missed would otherwise cover it).
  865. or_(PrintArchive.subtask_id.is_(None), PrintArchive.subtask_id.in_(("", "0"))),
  866. )
  867. .order_by(PrintArchive.created_at.desc())
  868. )
  869. archive = next((a for a in dispatched.scalars() if _archive_name_forms(a) & reported), None)
  870. else:
  871. result = await db.execute(
  872. select(PrintArchive)
  873. .where(
  874. PrintArchive.printer_id == printer_id,
  875. PrintArchive.status == "printing",
  876. PrintArchive.subtask_id == subtask_id,
  877. )
  878. .order_by(PrintArchive.created_at.desc())
  879. .limit(1)
  880. )
  881. archive = result.scalar_one_or_none()
  882. # An archive row on its own proves nothing: `on_print_start` archives every
  883. # print it observes, including ones started from Bambu Studio or Handy, and
  884. # stamps them with the same status and subtask_id. Authorizing on its mere
  885. # existence would disable the kill switch the moment the 3MF finishes
  886. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  887. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  888. # (carried over from the queue item that started it).
  889. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  890. # Rehydrate the fast in-memory path for subsequent status frames. Include
  891. # both the archive filename and every normalized key reported by MQTT.
  892. _owned_print_archive_ids.add(archive.id)
  893. _active_prints[(printer_id, archive.filename)] = archive.id
  894. for key in possible_keys:
  895. _active_prints[key] = archive.id
  896. return True
  897. # No dispatch marker. Before calling this someone else's print, check whether
  898. # Bambuddy has a job of its own running on this printer: a library-file
  899. # dispatch has no archive at send time, and an archive created seconds later
  900. # by `on_print_start` carries neither marker. The queue row, which the
  901. # scheduler commits to status="printing" before the MQTT send, is the one
  902. # durable record every Bambuddy print has. It cannot be tied to this
  903. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  904. # print is irreversible, and refusing to act costs nothing but a log line.
  905. from backend.app.models.print_queue import PrintQueueItem
  906. dispatched_here = await db.scalar(
  907. select(PrintQueueItem.id)
  908. .where(
  909. PrintQueueItem.printer_id == printer_id,
  910. PrintQueueItem.status == "printing",
  911. )
  912. .limit(1)
  913. )
  914. if dispatched_here is not None:
  915. return None
  916. return False
  917. async def _send_kill_switch_provider_notification(
  918. printer_id: int,
  919. printer_name: str,
  920. data: dict,
  921. ) -> bool:
  922. """Send the immediate print-stopped provider notification.
  923. Returning a success flag lets the normal MQTT completion path retry when
  924. this early notification could not be delivered.
  925. """
  926. logger = logging.getLogger(__name__)
  927. try:
  928. async with async_session() as db:
  929. await notification_service.on_print_complete(
  930. printer_id,
  931. printer_name,
  932. "stopped",
  933. data,
  934. db,
  935. )
  936. return True
  937. except Exception as e:
  938. logger.warning(
  939. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  940. printer_id,
  941. e,
  942. )
  943. return False
  944. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  945. """Wait for an immediate kill-switch notification, if one was scheduled."""
  946. if task is None:
  947. return False
  948. try:
  949. return await task
  950. except Exception as e:
  951. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  952. return False
  953. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  954. """Capture the smart plug lifetime counter on the archive at print start.
  955. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  956. tracking survives a backend restart mid-print. The print-end handler reads
  957. this value back from the DB and computes the delta against the current
  958. plug counter.
  959. """
  960. _logger = logging.getLogger(__name__)
  961. try:
  962. candidates = await energy_plug_candidates(db, printer_id)
  963. if not candidates:
  964. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  965. return False
  966. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  967. if selected is None:
  968. # Naming the plugs matters here: with several linked to one printer
  969. # this is the difference between "the meter is offline" and "you
  970. # linked only accessories" (#2859).
  971. _logger.warning(
  972. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  973. printer_id,
  974. archive.id,
  975. ", ".join(plug.name for plug in candidates),
  976. )
  977. return False
  978. plug, energy = selected
  979. archive.energy_start_kwh = float(energy["total"])
  980. # With the plug's snapshots, what lets the cost follow the price over
  981. # the print rather than take the price at its end (#1251). A price that
  982. # can't be had must not cost the print its energy reading.
  983. archive.energy_start_at = utcnow_naive()
  984. archive.energy_start_plug_id = plug.id
  985. try:
  986. from backend.app.services.energy_price import current_price
  987. archive.energy_start_price = await current_price(db)
  988. except Exception as e:
  989. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  990. archive.energy_start_price = None
  991. await db.commit()
  992. _logger.info(
  993. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  994. f" ({context})" if context else "",
  995. archive.id,
  996. plug.name,
  997. energy["total"],
  998. )
  999. return True
  1000. except Exception as e:
  1001. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  1002. return False
  1003. def forget_print_creator(user_id: int) -> None:
  1004. """The print-start emails of a deleted user's jobs go to nobody, not to
  1005. whoever is given the id next (SQLite reuses it)."""
  1006. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  1007. del _expected_print_creators[key]
  1008. async def forget_printer(printer_id: int) -> None:
  1009. """Drop what is kept for a deleted printer's id, here and in the services.
  1010. SQLite used to give the id to the next printer created, which inherited it
  1011. all: the running print's owner (its prints passed the kill switch and were
  1012. billed to that user), the plate-clear gate, pending and suppressed
  1013. notifications, the camera feed, the plate references. Ids are no longer
  1014. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  1015. stay. Called after the delete is committed, and again by work that was in
  1016. flight and wrote state back.
  1017. Every printer-keyed map of this module is listed here or, with the reason,
  1018. in tests/unit/test_forget_printer.py.
  1019. """
  1020. from backend.app.api.routes import camera
  1021. from backend.app.services import (
  1022. bambu_ftp,
  1023. kprofile_drift,
  1024. layer_timelapse,
  1025. plate_detection,
  1026. print_dispatch_context,
  1027. usage_tracker,
  1028. )
  1029. from backend.app.services.notify_live_activities import notify_live_activities
  1030. from backend.app.services.obico_detection import obico_detection_service
  1031. from backend.app.services.printer_file_cache import printer_file_cache
  1032. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  1033. archive_ids = set()
  1034. for tracked in (_active_prints, _expected_prints):
  1035. for key in [key for key in tracked if key[0] == printer_id]:
  1036. archive_ids.add(tracked.pop(key))
  1037. for archive_id in archive_ids:
  1038. _owned_print_archive_ids.discard(archive_id)
  1039. _print_ams_mappings.pop(archive_id, None)
  1040. _print_cost_center_ids.pop(archive_id, None)
  1041. _print_plate_ids.pop(archive_id, None)
  1042. for tracked in (_expected_print_creators, _expected_print_registered_at):
  1043. for key in [key for key in tracked if key[0] == printer_id]:
  1044. del tracked[key]
  1045. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  1046. _ams_index_only_logged.discard(key)
  1047. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  1048. del _ams_alarm_cooldown[key]
  1049. # Pending work that would act on the id: an offline notice, a 3MF retry.
  1050. # A kill-switch notice is about a stop that happened and is left to finish.
  1051. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  1052. task = tasks.pop(printer_id, None)
  1053. if task is not None:
  1054. task.cancel()
  1055. for keyed in (
  1056. _stage22_finish_frames,
  1057. _stage22_finish_in_flight,
  1058. _inprint_frame_bank,
  1059. _inprint_frame_bank_ts,
  1060. _printer_reconciled_since_connect,
  1061. _printer_kprofiles_primed_since_connect,
  1062. _last_progress_milestone,
  1063. _first_layer_notified,
  1064. _kill_switch_notification_tasks,
  1065. _notified_hms_errors,
  1066. _hms_print_state,
  1067. _hms_forget_when_gone,
  1068. _timelapse_baselines,
  1069. _bed_cool_waiters,
  1070. _printer_last_connected,
  1071. _unknown_tag_last_broadcast,
  1072. _last_status_broadcast,
  1073. _connection_watchdog_last_attempt,
  1074. ):
  1075. keyed.pop(printer_id, None)
  1076. for marked in (
  1077. _unauthorized_print_kill_sent,
  1078. _user_stopped_printers,
  1079. _kill_switch_stopped,
  1080. _printer_offline_published,
  1081. _nozzle_count_updated,
  1082. ):
  1083. marked.discard(printer_id)
  1084. printer_manager.forget_printer(printer_id)
  1085. printer_file_cache.forget_printer(printer_id)
  1086. print_dispatch_context.clear(printer_id)
  1087. kprofile_drift.forget_printer(printer_id, deleted=True)
  1088. layer_timelapse.cancel_session(printer_id)
  1089. usage_tracker.forget_printer(printer_id)
  1090. obico_detection_service.forget_printer(printer_id)
  1091. bambu_ftp.clear_3mf_cache(printer_id)
  1092. await camera.forget_printer(printer_id)
  1093. printers.clear_cover_cache(printer_id)
  1094. print_scheduler.forget_printer(printer_id)
  1095. notify_live_activities.forget_printer(printer_id)
  1096. plate_detection.remove_printer_references(printer_id)
  1097. def register_expected_print(
  1098. printer_id: int,
  1099. filename: str,
  1100. archive_id: int,
  1101. ams_mapping: list[int] | None = None,
  1102. created_by_id: int | None = None,
  1103. cost_center_id: int | None = None,
  1104. plate_id: int | None = None,
  1105. ):
  1106. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1107. # Store with multiple filename variations to catch different naming patterns
  1108. _expected_prints[(printer_id, filename)] = archive_id
  1109. # Also store without .3mf extension if present
  1110. if filename.endswith(".3mf"):
  1111. base = filename[:-4]
  1112. _expected_prints[(printer_id, base)] = archive_id
  1113. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1114. # Store AMS mapping for usage tracking at print completion
  1115. if ams_mapping is not None:
  1116. _print_ams_mappings[archive_id] = ams_mapping
  1117. if cost_center_id is not None:
  1118. _print_cost_center_ids[archive_id] = cost_center_id
  1119. # Store plate_id for usage tracking when this is a single-plate dispatch from
  1120. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  1121. # file's filament total to the spool instead of just the printed plate (#1697).
  1122. if plate_id is not None:
  1123. _print_plate_ids[archive_id] = plate_id
  1124. # Store created_by_id so the user start email can be sent even when the archive
  1125. # itself has no created_by_id (e.g. library-file-based queue prints)
  1126. if created_by_id is not None:
  1127. _expected_print_creators[(printer_id, filename)] = created_by_id
  1128. if filename.endswith(".3mf"):
  1129. base = filename[:-4]
  1130. _expected_print_creators[(printer_id, base)] = created_by_id
  1131. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1132. # Record registration time for TTL-based eviction
  1133. _registered_at = time.monotonic()
  1134. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1135. if filename.endswith(".3mf"):
  1136. base = filename[:-4]
  1137. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1138. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1139. logging.getLogger(__name__).info(
  1140. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1141. )
  1142. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1143. """Undo :func:`register_expected_print` when the print never went out.
  1144. Registration has to happen *before* the MQTT print command, because the
  1145. printer can report the print before the line after the send executes. So
  1146. every path that registers and then fails to send — a cancel winning the
  1147. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1148. between — leaves an expectation for a print that will never arrive.
  1149. The TTL sweep evicts those after two hours, which is far longer than it
  1150. takes a user to react to a failed dispatch by pressing print again: that
  1151. reprint would be folded into the *old* archive and take the stale
  1152. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1153. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1154. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1155. are keyed by archive, not by file, so they may only be dropped once no
  1156. live key still points at that archive.
  1157. """
  1158. keys = [(printer_id, filename)]
  1159. if filename.endswith(".3mf"):
  1160. base = filename[:-4]
  1161. keys.append((printer_id, base))
  1162. keys.append((printer_id, f"{base}.gcode"))
  1163. removed = False
  1164. for key in keys:
  1165. if _expected_prints.pop(key, None) is not None:
  1166. removed = True
  1167. _expected_print_creators.pop(key, None)
  1168. _expected_print_registered_at.pop(key, None)
  1169. if archive_id not in set(_expected_prints.values()):
  1170. _print_ams_mappings.pop(archive_id, None)
  1171. _print_cost_center_ids.pop(archive_id, None)
  1172. _print_plate_ids.pop(archive_id, None)
  1173. if removed:
  1174. logging.getLogger(__name__).info(
  1175. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1176. printer_id,
  1177. filename,
  1178. archive_id,
  1179. )
  1180. def _compute_run_filament_grams(
  1181. status: str,
  1182. archive_filament_used_grams: float | None,
  1183. progress: float | int | None,
  1184. usage_results: list[dict] | None,
  1185. ) -> float | None:
  1186. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1187. Priority for every status:
  1188. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1189. weight delta — same source that drives "Total Consumed" on the
  1190. Inventory page, so Stats and Inventory totals stay aligned).
  1191. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1192. back to the canonical "this print used X" value).
  1193. 3. For partial statuses: ``estimate * progress%``.
  1194. 4. ``None`` if nothing is known.
  1195. """
  1196. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1197. if tracked_grams > 0:
  1198. return round(tracked_grams, 1)
  1199. if status == "completed":
  1200. return archive_filament_used_grams
  1201. if archive_filament_used_grams:
  1202. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1203. if scale > 0:
  1204. return round(archive_filament_used_grams * scale, 1)
  1205. return None
  1206. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  1207. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1208. stored_ams_mapping = data.get("ams_mapping")
  1209. if not stored_ams_mapping and archive_id:
  1210. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  1211. return stored_ams_mapping
  1212. def _get_start_plate_id(archive_id: int | None) -> int | None:
  1213. """Resolve plate_id for print start without consuming stored direct-Print state.
  1214. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1215. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1216. read it back at print-start without popping (the entry is popped on print
  1217. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1218. """
  1219. if archive_id is None:
  1220. return None
  1221. return _print_plate_ids.get(archive_id)
  1222. def _partial_progress_scale(progress: int | float | None) -> float:
  1223. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1224. Used by every site that multiplies a "would-have-used" slicer estimate
  1225. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1226. so the three sites in ``_background_notifications`` (and the per-plate
  1227. override helper) can't drift apart on the coercion shape.
  1228. """
  1229. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1230. def _scope_notification_archive_data_to_plate(
  1231. archive_data: dict,
  1232. archive_file_path: str | None,
  1233. plate_id: int | None,
  1234. print_status: str,
  1235. progress: int | float | None,
  1236. base_dir: Path,
  1237. ) -> dict:
  1238. """Override summed-across-plates totals in ``archive_data`` with the values
  1239. for ``plate_id`` so the completion notification reports what was actually
  1240. printed, not the whole project (#1785).
  1241. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1242. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1243. the archive card's "whole project" headline, wrong for the completion
  1244. notification of a single-plate print. The queue UI already re-reads the
  1245. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1246. notification payload (filament grams, time estimate, per-slot breakdown).
  1247. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1248. no per-plate values — in every fail case the original ``archive_data`` is
  1249. returned unchanged so the notification still sends.
  1250. """
  1251. if plate_id is None or not archive_file_path:
  1252. return archive_data
  1253. from backend.app.utils.threemf_tools import (
  1254. extract_filament_usage_from_3mf,
  1255. extract_print_time_from_3mf,
  1256. )
  1257. archive_path = base_dir / archive_file_path
  1258. if not archive_path.exists():
  1259. return archive_data
  1260. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1261. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1262. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1263. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1264. if plate_time:
  1265. archive_data["print_time_seconds"] = plate_time
  1266. # Gate both the grams headline AND the per-slot breakdown on the same
  1267. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1268. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1269. # to the project-level grams the archive columns already provide rather
  1270. # than ship a project-level headline next to an all-zero per-plate
  1271. # breakdown.
  1272. if plate_grams > 0:
  1273. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1274. archive_data["filament_slots"] = [
  1275. {
  1276. "slot_id": s.get("slot_id"),
  1277. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1278. "type": s.get("type", ""),
  1279. "color": s.get("color", ""),
  1280. }
  1281. for s in plate_slots
  1282. ]
  1283. return archive_data
  1284. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1285. """Best-effort filament metadata from the MQTT print-start snapshot.
  1286. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1287. file during print, see #1533) so the fallback PrintArchive still has
  1288. enough filament info to support the inventory views and AMS-expansion
  1289. planning the operator opens it for. Returns a dict with optional
  1290. ``filament_type`` and ``filament_color`` keys in the same
  1291. comma-separated format the 3MF extractor produces, so the rest of the
  1292. codebase treats the fallback archive identically to a normal one.
  1293. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1294. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1295. entries). When supplied, only the slots actually consumed by this
  1296. print contribute. Without it the function falls back to every loaded
  1297. AMS slot — less accurate but still useful.
  1298. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1299. that the unit tests pass directly, AND the on_print_start callback
  1300. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1301. bambu_mqtt service hands to main.py at runtime. The original
  1302. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1303. handled the inner shape and silently returned ``{}`` for every real
  1304. print start, leaving fallback archives' filament fields NULL — the
  1305. exact regression the fix was meant to close. Reported with a log
  1306. proving the AMS state was right there at
  1307. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1308. """
  1309. result: dict[str, str] = {}
  1310. # Look at the on_print_start wrapper first, then the inner shape.
  1311. raw_data = (data or {}).get("raw_data")
  1312. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1313. if not isinstance(ams_root, dict):
  1314. ams_root = (data or {}).get("ams") or {}
  1315. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1316. if not isinstance(ams_units, list) or not ams_units:
  1317. return result
  1318. from backend.app.services.print_scheduler import _global_tray_id
  1319. # Map global tray id → (type, color), addressed as the print's ams_mapping
  1320. # is: unit * 4 + tray, or the bare unit id for an AMS-HT (from 128).
  1321. loaded: dict[int, tuple[str, str]] = {}
  1322. for unit in ams_units:
  1323. if not isinstance(unit, dict):
  1324. continue
  1325. try:
  1326. unit_id = int(unit.get("id", 0))
  1327. except (TypeError, ValueError):
  1328. continue
  1329. for tray in unit.get("tray") or []:
  1330. if not isinstance(tray, dict):
  1331. continue
  1332. try:
  1333. tray_id = int(tray.get("id", 0))
  1334. except (TypeError, ValueError):
  1335. continue
  1336. ttype = (tray.get("tray_type") or "").strip()
  1337. # RRGGBBAA from the printer, stored as the 3MF path stores it:
  1338. # "#RRGGBB" (the Archives page's swatches and colour filter).
  1339. hex_color = (tray.get("tray_color") or "").strip().upper()[:6]
  1340. tcolor = f"#{hex_color}" if re.fullmatch(r"[0-9A-F]{6}", hex_color) else ""
  1341. if not ttype:
  1342. continue # Empty / unloaded slot.
  1343. loaded[_global_tray_id(unit_id, tray_id)] = (ttype, tcolor)
  1344. if not loaded:
  1345. return result
  1346. if ams_mapping:
  1347. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1348. filaments = [loaded[g] for g in used_ids if g in loaded]
  1349. if not filaments:
  1350. return result # Mapping points entirely at slots we have no data for.
  1351. else:
  1352. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1353. types_joined = ",".join(f[0] for f in filaments)
  1354. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1355. # Column limits per backend/app/models/archive.py: filament_type=50,
  1356. # filament_color=200.
  1357. if types_joined:
  1358. result["filament_type"] = types_joined[:50]
  1359. if colors_joined:
  1360. result["filament_color"] = colors_joined[:200]
  1361. return result
  1362. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1363. """Start a layer-timelapse session for *archive_id* when the printer has
  1364. an external camera configured. Returns True if a session was started.
  1365. Three call sites in on_print_start (expected-archive promotion, fallback
  1366. archive creation, fresh-archive creation) used to inline this same
  1367. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1368. on the first pass). Centralising the conditional + call here makes the
  1369. contract testable in isolation and keeps the three sites locked in step.
  1370. """
  1371. if not (printer.external_camera_enabled and printer.external_camera_url):
  1372. return False
  1373. from backend.app.services.layer_timelapse import start_session
  1374. start_session(
  1375. printer_id,
  1376. archive_id,
  1377. printer.external_camera_url,
  1378. printer.external_camera_type or "mjpeg",
  1379. snapshot_url=printer.external_camera_snapshot_url,
  1380. rotation=getattr(printer, "camera_rotation", 0),
  1381. )
  1382. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1383. return True
  1384. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1385. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1386. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1387. — since #2926 — the description the parser already resolved, which is preferred
  1388. when present so the queue's failure reason reads the same as the status
  1389. response. The short code still produces the bracketed label, and still
  1390. resolves the sentence for a caller whose entries predate the field. An entry
  1391. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1392. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1393. label when no description is on file. Returns None for an empty list so
  1394. callers can leave error_message unset.
  1395. """
  1396. if not hms_errors:
  1397. return None
  1398. from backend.app.services.hms_errors import get_error_description
  1399. parts: list[str] = []
  1400. for err in hms_errors:
  1401. try:
  1402. # `_hms_short_code` rather than a local derivation: this one used to
  1403. # format the error without masking it to 16 bits, so an `hms[]` entry
  1404. # whose code carries an alert-level group produced a five-digit label
  1405. # like "0500_3000A" — not a code the user can look up, and never a
  1406. # catalogue key, so the sentence was lost with it.
  1407. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1408. except (TypeError, ValueError):
  1409. continue
  1410. description = err.get("description") or get_error_description(short_code)
  1411. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1412. # groups and is not a code anyone can look up; its full code in the
  1413. # printer screen's four groups is (#2728).
  1414. full_code = str(err.get("full_code") or "")
  1415. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1416. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1417. return "; ".join(parts) if parts else None
  1418. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1419. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1420. print completes successfully. Gated to status=='completed': failed, cancelled
  1421. and aborted prints do not count as usage. Caller is responsible for committing
  1422. the session. No-op when the queue item has no linked library file (e.g. reprints
  1423. from an archive). See #1008."""
  1424. if queue_status != "completed" or item.library_file_id is None:
  1425. return
  1426. from backend.app.models.library import LibraryFile
  1427. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1428. if lib_file is None:
  1429. return
  1430. lib_file.print_count = (lib_file.print_count or 0) + 1
  1431. lib_file.last_printed_at = datetime.now(timezone.utc)
  1432. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1433. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1434. When on_print_complete fires with status 'failed' for a printer in this set we
  1435. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1436. rather than a 'print failed' notification.
  1437. """
  1438. _user_stopped_printers.add(printer_id)
  1439. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1440. _last_status_broadcast: dict[int, str] = {}
  1441. # Track printers where we've updated nozzle_count
  1442. _nozzle_count_updated: set[int] = set()
  1443. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1444. """Wait the debounce window then fire `on_printer_offline` if the printer
  1445. is still offline.
  1446. Scheduled by `on_printer_status_change` on the connected → disconnected
  1447. edge (#1752). Cancelled by the same handler if the printer reconnects
  1448. before the window elapses, so a single MQTT blip + recovery doesn't
  1449. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1450. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1451. route through the same status-change callback, so this covers both.
  1452. """
  1453. logger = logging.getLogger(__name__)
  1454. try:
  1455. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1456. still_offline = not printer_manager.is_connected(printer_id)
  1457. logger.info(
  1458. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1459. printer_id,
  1460. still_offline,
  1461. )
  1462. if not still_offline:
  1463. return
  1464. async with async_session() as db:
  1465. from backend.app.models.printer import Printer
  1466. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1467. printer = result.scalar_one_or_none()
  1468. if not printer:
  1469. logger.warning(
  1470. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1471. printer_id,
  1472. )
  1473. return
  1474. # Recorded only when the relay can publish it, so the reconnect's
  1475. # online event always has an offline before it.
  1476. if mqtt_relay.enabled and mqtt_relay.connected:
  1477. _printer_offline_published.add(printer_id)
  1478. try:
  1479. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1480. except Exception as e:
  1481. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1482. logger.info(
  1483. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1484. printer_id,
  1485. printer.name,
  1486. )
  1487. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1488. except asyncio.CancelledError:
  1489. raise
  1490. except Exception as e:
  1491. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1492. finally:
  1493. _printer_offline_notify_tasks.pop(printer_id, None)
  1494. def _hms_notify_key(error) -> str:
  1495. """What identifies a fault for notification de-duplication.
  1496. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1497. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1498. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1499. and -0006 together) shared a key and only the first was ever notified. An
  1500. entry without a full code falls back to attr and code together.
  1501. """
  1502. full_code = getattr(error, "full_code", "") or ""
  1503. if full_code:
  1504. return full_code.upper()
  1505. return f"{error.attr:08X}:{error.code}"
  1506. def _hms_fault_counts(error) -> bool:
  1507. """Whether a fault counts as a problem: the same rule the frontend's
  1508. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1509. It counts when Bambu publishes text for it or it offers action buttons, and
  1510. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1511. no actions does not count: those are things like "the top cover is open" or
  1512. "the chamber is hot, fan speed increased", which a printer can hold through
  1513. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1514. it always has; those are prompts such as "unable to start drying" (#2728).
  1515. """
  1516. if error.severity < 1:
  1517. return False
  1518. has_actions = bool(getattr(error, "actions", None))
  1519. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1520. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1521. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1522. """The new faults that count (see ``_hms_fault_counts``).
  1523. These go to the MQTT relay; the caller also needs a description before it
  1524. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1525. used to read ``severity >= 2`` when severity held the part byte; on the real
  1526. level that would drop the task-stopping errors (#2728).
  1527. """
  1528. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1529. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1530. """The faults on this printer not notified yet, and record them as notified.
  1531. Tracking is updated before anything is sent, so concurrent status callbacks
  1532. cannot notify the same fault twice. A notified fault is forgotten once it
  1533. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1534. and on is notified once (#3226), while one that clears and comes back much
  1535. later is notified again.
  1536. When ``print_state`` changes (a print resumed, started or finished), every
  1537. fault recorded so far is forgotten the first time it is gone, without the
  1538. wait: a runout fixed before resuming must be notified if it happens again a
  1539. few minutes later, while the printer sits paused. Not only the faults gone
  1540. at the change itself, because the update that flips the state can still
  1541. carry the old fault (a ``print_error`` entry stays until a payload brings
  1542. ``hms``).
  1543. """
  1544. now = time.time()
  1545. current = {_hms_notify_key(e) for e in errors}
  1546. seen = _notified_hms_errors.setdefault(printer_id, {})
  1547. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1548. if print_state is not None:
  1549. print_state = print_state.upper()
  1550. if _hms_print_state.get(printer_id, print_state) != print_state:
  1551. forget_when_gone.update(seen)
  1552. _hms_print_state[printer_id] = print_state
  1553. for key, last_seen in list(seen.items()):
  1554. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1555. del seen[key]
  1556. forget_when_gone.discard(key)
  1557. new = current - seen.keys()
  1558. for key in current:
  1559. seen[key] = now
  1560. if not seen:
  1561. _notified_hms_errors.pop(printer_id, None)
  1562. if not forget_when_gone:
  1563. _hms_forget_when_gone.pop(printer_id, None)
  1564. return _hms_errors_to_notify(errors, new)
  1565. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1566. # "Printing", -1 and 255 are "no stage" (#3211).
  1567. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1568. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1569. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1570. Records it as notified. Called only for a printing state with progress above 0.
  1571. Progress before the first layer is not progress through the print (#3211).
  1572. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1573. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1574. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1575. 75% notification together with Print Started, and since 75 was then on
  1576. record, 25 and 50 could never fire. So nothing counts while the printer
  1577. reports a layer count but has not started layer 1.
  1578. Without a layer count -- a print whose first frame carried no
  1579. ``total_layer_num``, until the pushall that asks for it is answered
  1580. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1581. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1582. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1583. reports neither keeps the old behaviour rather than never notifying.
  1584. """
  1585. if (state.layer_num or 0) < 1:
  1586. if (state.total_layers or 0) > 0:
  1587. return None
  1588. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1589. return None
  1590. progress = state.progress or 0
  1591. current_milestone = 0
  1592. if progress >= 75:
  1593. current_milestone = 75
  1594. elif progress >= 50:
  1595. current_milestone = 50
  1596. elif progress >= 25:
  1597. current_milestone = 25
  1598. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1599. _last_progress_milestone[printer_id] = current_milestone
  1600. return current_milestone
  1601. return None
  1602. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1603. """Handle printer status changes - broadcast via WebSocket."""
  1604. try:
  1605. notify_live_activities.observe(printer_id, state)
  1606. except Exception:
  1607. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1608. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1609. # transitions disconnected → connected — which covers both Bambuddy
  1610. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1611. # `reconcile_stale_active_prints` exactly once for this connection so
  1612. # any archive still in `status="printing"` that can't actually be
  1613. # running anymore (printer IDLE / different subtask / empty subtask)
  1614. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1615. # finished during a disconnect window + a smart-plug power cycle
  1616. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1617. # next boot. Reconciliation runs concurrently — it must not block the
  1618. # WebSocket dedup / broadcast logic below, and the connected edge is
  1619. # marked True BEFORE the await so concurrent status updates inside
  1620. # the same connection don't re-trigger reconciliation.
  1621. #
  1622. # Wait for a real push_status before reconciling (#1679): MQTT
  1623. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1624. # the connection, BEFORE `_request_push_all` round-trips. At that
  1625. # instant the `PrinterState` is still on construction defaults — most
  1626. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1627. # If reconcile spawns here, every in-flight archive falls through to
  1628. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1629. # creates a duplicate archive on the real PRINT COMPLETE and
  1630. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1631. # keeps the #1542 mechanism intact: once the first real push_status
  1632. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1633. # fires again with the flag still False — reconcile then runs against
  1634. # actual evidence.
  1635. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1636. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1637. _printer_reconciled_since_connect[printer_id] = True
  1638. spawn_background_task(
  1639. reconcile_stale_active_prints(printer_id),
  1640. name=f"reconcile-stale-prints-{printer_id}",
  1641. )
  1642. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1643. # Re-arm so the next reconnect triggers reconciliation again.
  1644. _printer_reconciled_since_connect[printer_id] = False
  1645. # Same edge, for the calibration table the AMS card reads its K values from.
  1646. #
  1647. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1648. # tables to ask for. A `state_known` gate alone is not enough: the first
  1649. # real push_status is what makes the state known, and the nozzle fields do
  1650. # not always arrive in it. Latching there would spend this connection's one
  1651. # attempt on a printer that could not yet say what was fitted.
  1652. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1653. if (
  1654. state.connected
  1655. and state_known
  1656. and nozzle_known
  1657. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1658. ):
  1659. _printer_kprofiles_primed_since_connect[printer_id] = True
  1660. spawn_background_task(
  1661. prime_kprofile_table(printer_id),
  1662. name=f"prime-kprofiles-{printer_id}",
  1663. )
  1664. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1665. _printer_kprofiles_primed_since_connect[printer_id] = False
  1666. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1667. # else in the AMS report changing -- a power cycle does it to every slot --
  1668. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1669. # while the printer is idle; needs_check is cheap and throttled per slot.
  1670. # Guarded: nothing here may stop the status broadcast below.
  1671. try:
  1672. if not state.connected:
  1673. kprofile_drift.forget_printer(printer_id)
  1674. elif kprofile_drift.needs_check(printer_id, state):
  1675. spawn_background_task(
  1676. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1677. name=f"reapply-kprofiles-{printer_id}",
  1678. )
  1679. except Exception:
  1680. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1681. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1682. # connected → disconnected. The "back online" channel is already covered
  1683. # by the print-failure notification (firmware reports gcode_state=FAILED
  1684. # on reconnect of an interrupted print), so there is no online
  1685. # notification. The MQTT relay gets both: offline after the debounce, and
  1686. # online on the reconnect that follows a published offline.
  1687. prev_connected = _printer_last_connected.get(printer_id)
  1688. _printer_last_connected[printer_id] = state.connected
  1689. if prev_connected is True and not state.connected:
  1690. existing = _printer_offline_notify_tasks.get(printer_id)
  1691. if existing is None or existing.done():
  1692. logging.getLogger(__name__).info(
  1693. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1694. printer_id,
  1695. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1696. )
  1697. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1698. _maybe_notify_printer_offline(printer_id),
  1699. name=f"printer-offline-notify-{printer_id}",
  1700. )
  1701. elif state.connected:
  1702. # Kept until the relay can actually send online: with its broker down
  1703. # now, the next status update after the reconnect sends it.
  1704. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1705. _printer_offline_published.discard(printer_id)
  1706. printer_info = printer_manager.get_printer(printer_id)
  1707. if printer_info:
  1708. try:
  1709. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1710. except Exception as e:
  1711. logging.getLogger(__name__).warning(
  1712. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1713. )
  1714. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1715. if pending is not None and not pending.done():
  1716. logging.getLogger(__name__).info(
  1717. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1718. printer_id,
  1719. )
  1720. pending.cancel()
  1721. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1722. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1723. temps = state.temperatures or {}
  1724. nozzle_temp = round(temps.get("nozzle", 0))
  1725. bed_temp = round(temps.get("bed", 0))
  1726. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1727. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1728. # Auto-detect dual-nozzle printers from MQTT temperature data
  1729. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1730. _nozzle_count_updated.add(printer_id)
  1731. # Update nozzle_count in database
  1732. async with async_session() as db:
  1733. from backend.app.models.printer import Printer
  1734. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1735. printer = result.scalar_one_or_none()
  1736. if printer and printer.nozzle_count != 2:
  1737. printer.nozzle_count = 2
  1738. await db.commit()
  1739. logging.getLogger(__name__).info(
  1740. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1741. )
  1742. # Include target temps for heating phase detection
  1743. bed_target = round(temps.get("bed_target", 0))
  1744. nozzle_target = round(temps.get("nozzle_target", 0))
  1745. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1746. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1747. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1748. #
  1749. # dry_countdown_stalled rides along because it is the one drying signal the
  1750. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1751. # dry_time stopped moving, so on the frame that flips it every other member
  1752. # of this key is identical and the push would be deduplicated away. Mid-print
  1753. # a temperature would eventually break the tie, but a parked command on an
  1754. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1755. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1756. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1757. ams_dry_key = (
  1758. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1759. if state.raw_data
  1760. else ()
  1761. )
  1762. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1763. #
  1764. # The filament identity fields are here because Configure Slot writes
  1765. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1766. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1767. # matched, this function returned before broadcasting, and the card kept
  1768. # showing the old filament until the 30s fallback poll or a page reload —
  1769. # even though the configure route asks the printer for a fresh pushall and
  1770. # that push does carry the new values. Reset always worked, because it
  1771. # clears tray_type.
  1772. #
  1773. # These fields only change when someone configures a slot or swaps a spool,
  1774. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1775. ams_tray_key = (
  1776. tuple(
  1777. (
  1778. t.get("id"),
  1779. t.get("tray_type", ""),
  1780. t.get("state"),
  1781. t.get("tray_color", ""),
  1782. t.get("tray_info_idx", ""),
  1783. t.get("tray_sub_brands", ""),
  1784. t.get("cali_idx"),
  1785. )
  1786. for a in (state.raw_data.get("ams") or [])
  1787. for t in a.get("tray", [])
  1788. )
  1789. if state.raw_data
  1790. else ()
  1791. )
  1792. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1793. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1794. # in the AMS change-hash (tray fields only, and widening that would fire
  1795. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1796. # screen changed no key at all and the card's inlet badges sat stale until a
  1797. # reload. Like the filament-backup flag, these only move when someone
  1798. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1799. fts_key = (
  1800. state.fila_switch.installed if state.fila_switch else False,
  1801. tuple(sorted(state.ams_switch_inlet.items())),
  1802. # Which hotend holds which slot. Unlike the two above this does move
  1803. # mid-print, on every filament change — but only between discrete slots,
  1804. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1805. # it live: it decides which hotend the Load dialog may offer and whether
  1806. # Unload has anything to act on.
  1807. tuple(
  1808. sorted(
  1809. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1810. # Sort on the extruder id alone: the other members are nullable
  1811. # and comparing None with an int raises.
  1812. key=lambda entry: entry[0],
  1813. )
  1814. ),
  1815. )
  1816. status_key = (
  1817. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1818. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1819. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1820. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1821. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1822. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1823. )
  1824. # Fields that change only when the machine does (a nozzle swap, a firmware
  1825. # update, developer mode) or once per print (its AMS mapping): no traffic,
  1826. # but on an idle printer nothing else moves the key when they change.
  1827. machine_key = (
  1828. tuple((n.nozzle_type, n.nozzle_diameter) for n in (state.nozzles or [])),
  1829. state.firmware_version,
  1830. state.developer_mode,
  1831. tuple(state.print_ams_mapping) if isinstance(state.print_ams_mapping, list) else None,
  1832. )
  1833. status_key = f"{status_key}:{machine_key}"
  1834. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1835. if not is_active_print:
  1836. _unauthorized_print_kill_sent.discard(printer_id)
  1837. elif printer_id in _unauthorized_print_kill_sent:
  1838. # stop_print() was already sent for this print; avoid all further
  1839. # ownership and settings work until the printer leaves an active state.
  1840. pass
  1841. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1842. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1843. _unauthorized_print_kill_sent.discard(printer_id)
  1844. else:
  1845. kill_switch_enabled = False
  1846. authorization: bool | None = None
  1847. status_logger = logging.getLogger(__name__)
  1848. try:
  1849. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1850. if kill_switch_enabled:
  1851. async with async_session() as db:
  1852. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1853. except Exception as e:
  1854. # Fail safe: a database/reconciliation error must never turn into an
  1855. # irreversible stop of a print whose ownership is still unknown.
  1856. authorization = None
  1857. status_logger.warning(
  1858. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1859. )
  1860. if not kill_switch_enabled or authorization is True:
  1861. _unauthorized_print_kill_sent.discard(printer_id)
  1862. elif authorization is None:
  1863. _unauthorized_print_kill_sent.discard(printer_id)
  1864. status_logger.debug(
  1865. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1866. printer_id,
  1867. )
  1868. else:
  1869. try:
  1870. stopped = printer_manager.stop_print(printer_id)
  1871. if stopped:
  1872. _unauthorized_print_kill_sent.add(printer_id)
  1873. _kill_switch_stopped.add(printer_id)
  1874. printer_info = printer_manager.get_printer(printer_id)
  1875. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1876. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1877. notification_data = {
  1878. "status": "stopped",
  1879. "filename": state.gcode_file or state.current_print or "",
  1880. "subtask_name": state.subtask_name or "",
  1881. "progress": state.progress,
  1882. "reason": "unauthorized_print",
  1883. }
  1884. status_logger.warning(
  1885. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1886. printer_id,
  1887. state.state,
  1888. )
  1889. try:
  1890. await ws_manager.broadcast(
  1891. {
  1892. "type": "kill_switch_triggered",
  1893. "printer_id": printer_id,
  1894. "printer_name": printer_name,
  1895. "filename": filename,
  1896. "reason": "unauthorized_print",
  1897. }
  1898. )
  1899. except Exception as e:
  1900. status_logger.warning(
  1901. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1902. )
  1903. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1904. if previous_task is not None and not previous_task.done():
  1905. previous_task.cancel()
  1906. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1907. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1908. name=f"kill-switch-notification-{printer_id}",
  1909. )
  1910. else:
  1911. status_logger.warning(
  1912. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1913. printer_id,
  1914. state.state,
  1915. )
  1916. except Exception as e:
  1917. status_logger.warning(
  1918. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1919. )
  1920. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1921. try:
  1922. printer_info = printer_manager.get_printer(printer_id)
  1923. if printer_info:
  1924. await mqtt_relay.on_printer_status(
  1925. printer_id,
  1926. state,
  1927. printer_info.name,
  1928. printer_info.serial_number,
  1929. printer_manager.is_awaiting_plate_clear(printer_id),
  1930. )
  1931. except Exception:
  1932. pass # Don't fail status callback if MQTT fails
  1933. if _last_status_broadcast.get(printer_id) == status_key:
  1934. return # No change, skip WebSocket broadcast
  1935. _last_status_broadcast[printer_id] = status_key
  1936. # Check for progress milestone notifications (25%, 50%, 75%)
  1937. progress = state.progress or 0
  1938. is_printing = state.state in ("RUNNING", "PRINTING")
  1939. if is_printing and progress > 0:
  1940. current_milestone = _progress_milestone_to_notify(printer_id, state)
  1941. if current_milestone is not None:
  1942. try:
  1943. from backend.app.models.printer import Printer
  1944. # Read the printer in a short session and release the connection
  1945. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1946. # pinned a pooled connection per milestone, per printer (issue #2572).
  1947. async with async_session() as db:
  1948. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1949. printer = result.scalar_one_or_none()
  1950. printer_name = printer.name if printer else f"Printer {printer_id}"
  1951. filename = state.subtask_name or state.gcode_file or "Unknown"
  1952. # remaining_time is in minutes, convert to seconds for notification
  1953. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1954. # Capture camera snapshot for notification image attachment (no DB held).
  1955. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1956. # Notification send needs a session (provider/template lookups).
  1957. async with async_session() as db:
  1958. await notification_service.on_print_progress(
  1959. printer_id,
  1960. printer_name,
  1961. filename,
  1962. current_milestone,
  1963. db,
  1964. remaining_time_seconds,
  1965. image_data=image_data,
  1966. )
  1967. except Exception as e:
  1968. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1969. elif progress < 5:
  1970. # Reset milestone tracking when print restarts or new print begins
  1971. _last_progress_milestone[printer_id] = 0
  1972. _first_layer_notified[printer_id] = False
  1973. # HMS error codes that should not trigger notifications even though they
  1974. # have known descriptions (e.g. user-initiated actions, not real errors).
  1975. _HMS_NOTIFICATION_SUPPRESS = {
  1976. "0500_400E", # Printing was cancelled (user action, not an error)
  1977. }
  1978. # Check for new HMS errors and send notifications
  1979. current_hms_errors = getattr(state, "hms_errors", []) or []
  1980. if current_hms_errors:
  1981. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  1982. if new_errors:
  1983. try:
  1984. from backend.app.models.printer import Printer
  1985. # Read the printer in a short session and release the connection
  1986. # BEFORE the ~15s camera snapshot below (issue #2572).
  1987. async with async_session() as db:
  1988. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1989. printer = result.scalar_one_or_none()
  1990. printer_name = printer.name if printer else f"Printer {printer_id}"
  1991. # Format error details for notification
  1992. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1993. module_names = {
  1994. 0x03: "Print/Task",
  1995. 0x05: "Nozzle/Extruder",
  1996. 0x07: "AMS/Filament",
  1997. 0x0C: "Motion Controller",
  1998. 0x12: "Chamber",
  1999. }
  2000. # Capture camera snapshot once for all error notifications (no DB held).
  2001. error_image_data = await _capture_snapshot_for_notification(
  2002. printer_id, printer, logging.getLogger(__name__)
  2003. )
  2004. # Notification sends need a session (provider/template lookups).
  2005. async with async_session() as db:
  2006. sent_count = 0
  2007. for error in new_errors:
  2008. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  2009. # Build short code like "0700_8010"
  2010. # Mask to 16 bits to handle printers that send larger values
  2011. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  2012. error_code_masked = error_code_int & 0xFFFF
  2013. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  2014. # Only notify for errors Bambu publishes text for — printers
  2015. # send undocumented codes that aren't real errors, and Bambu
  2016. # lists some with empty text. Resolved at parse time (#2926);
  2017. # short_code is still needed for the suppression set below.
  2018. description = error.description
  2019. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  2020. continue
  2021. error_type = f"{module_name} Error"
  2022. error_detail = description
  2023. await notification_service.on_printer_error(
  2024. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  2025. )
  2026. sent_count += 1
  2027. if sent_count:
  2028. logging.getLogger(__name__).info(
  2029. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  2030. )
  2031. # Also publish to MQTT relay (no DB): every new fault that
  2032. # counts, with or without text, the same set the UI counts.
  2033. printer_info = printer_manager.get_printer(printer_id)
  2034. if printer_info:
  2035. errors_data = [
  2036. {
  2037. "code": e.code,
  2038. "attr": e.attr,
  2039. "module": e.module,
  2040. "severity": e.severity,
  2041. }
  2042. for e in new_errors
  2043. ]
  2044. await mqtt_relay.on_printer_error(
  2045. printer_id, printer_info.name, printer_info.serial_number, errors_data
  2046. )
  2047. except Exception as e:
  2048. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  2049. else:
  2050. # No HMS errors: nothing to send, but faults gone long enough (or gone
  2051. # across a print state change) are forgotten. Some codes, e.g. chamber
  2052. # temperature regulation during PETG prints, toggle every few seconds.
  2053. _take_new_hms_faults(printer_id, [], state.state)
  2054. await ws_manager.send_printer_status(
  2055. printer_id,
  2056. printer_state_to_dict(
  2057. state,
  2058. printer_id,
  2059. printer_manager.get_model(printer_id),
  2060. printer_manager.get_drying_targets(printer_id),
  2061. ),
  2062. )
  2063. def _is_bambu_uuid(tray_uuid: str) -> bool:
  2064. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  2065. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  2066. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  2067. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  2068. K-profiles are per-nozzle and the printer's calibration table is numbered
  2069. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  2070. switch's other inlet therefore silently invalidates every configured slot in
  2071. it: the index stays put and now resolves against the other nozzle's table.
  2072. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  2073. and 0.020 on the right kept the left profile after the move, and a manual
  2074. RFID re-read only re-asserted the same wrong one.
  2075. Configuring a slot is a deliberate preparation step, so this re-selects
  2076. rather than re-configures: only the calibration binding moves, and only for
  2077. slots whose spool already has a stored profile for the new nozzle. A slot
  2078. Bambuddy knows nothing about is left exactly as the operator left it.
  2079. """
  2080. logger = logging.getLogger(__name__)
  2081. target_extruder = extruder_for_inlet(inlet)
  2082. if target_extruder is None:
  2083. return
  2084. client = printer_manager.get_client(printer_id)
  2085. state = printer_manager.get_status(printer_id)
  2086. if not client or not state or not state.raw_data:
  2087. return
  2088. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  2089. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  2090. # the nozzle width, which changes both the K profile to select and the
  2091. # preset the slot should carry.
  2092. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  2093. ams_raw = state.raw_data.get("ams")
  2094. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2095. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  2096. if not unit:
  2097. return
  2098. try:
  2099. async with async_session() as db:
  2100. for tray in unit.get("tray", []):
  2101. tray_id = int(tray.get("id", -1))
  2102. if tray_id < 0 or not tray.get("tray_type"):
  2103. continue
  2104. current_idx = tray.get("cali_idx")
  2105. profile = await find_slot_kprofile_for_extruder(
  2106. db,
  2107. printer_id,
  2108. ams_id,
  2109. tray_id,
  2110. target_extruder,
  2111. nozzle_diameter,
  2112. printer_manager.get_model(printer_id),
  2113. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2114. )
  2115. if profile is None or profile.cali_idx is None:
  2116. continue
  2117. if current_idx == profile.cali_idx:
  2118. continue # Already on the right one.
  2119. logger.info(
  2120. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2121. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2122. printer_id,
  2123. ams_id,
  2124. tray_id,
  2125. inlet,
  2126. target_extruder,
  2127. profile.name,
  2128. current_idx,
  2129. profile.cali_idx,
  2130. profile.k_value,
  2131. )
  2132. client.extrusion_cali_sel(
  2133. ams_id=ams_id,
  2134. tray_id=tray_id,
  2135. cali_idx=profile.cali_idx,
  2136. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2137. nozzle_diameter=nozzle_diameter,
  2138. )
  2139. except Exception as e:
  2140. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2141. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2142. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2143. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2144. from the delayed re-check -- which is why it takes the AMS data and print
  2145. state as arguments instead of reading them from the push (#3186).
  2146. """
  2147. logger = logging.getLogger(__name__)
  2148. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2149. # Auto-unlink spool assignments with stale fingerprints. Under the
  2150. # per-printer assignment lock since #3186: the held-removal re-check runs
  2151. # this outside any MQTT push, so it can now overlap one.
  2152. try:
  2153. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2154. from sqlalchemy.orm import selectinload
  2155. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2156. from backend.app.models.spool import Spool as _Spool
  2157. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2158. from backend.app.services.ams_slot_presence import spool_present
  2159. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2160. # Built-in assignments only. Since #2812 they survive a switch to
  2161. # Spoolman mode rather than being deleted by it, and this pass ends
  2162. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2163. # time as the AMS contents changed under the other mode, undoing the
  2164. # preservation more slowly but just as completely.
  2165. assignments = []
  2166. if not await spoolman_owns_assignments(db):
  2167. result = await db.execute(
  2168. select(SA)
  2169. .where(SA.printer_id == printer_id)
  2170. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2171. )
  2172. assignments = result.scalars().all()
  2173. # ``printing_now`` (top of this function) keeps a runout from
  2174. # unlinking the spool that fed the print — the next idle-time pass
  2175. # unlinks it if the user really did take it out.
  2176. stale = []
  2177. # Removals this pass is holding rather than unlinking (#3186).
  2178. held: set[tuple] = set()
  2179. for assignment in assignments:
  2180. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2181. if assignment.ams_id == 255:
  2182. ps = printer_manager.get_status(printer_id)
  2183. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2184. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2185. current_tray = None
  2186. for vt in vt_tray_raw:
  2187. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2188. current_tray = vt
  2189. break
  2190. if not current_tray:
  2191. # vt_tray data may not have arrived yet — keep assignment
  2192. continue
  2193. else:
  2194. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2195. if not current_tray:
  2196. if printing_now:
  2197. logger.info(
  2198. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2199. assignment.spool_id,
  2200. assignment.ams_id,
  2201. assignment.tray_id,
  2202. )
  2203. continue
  2204. # A whole AMS unit can drop out of one push and come back in
  2205. # the next; only a slot that stays gone is a removal (#3186).
  2206. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2207. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2208. held.add(hold_key)
  2209. logger.info(
  2210. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2211. "unlinking if it is still gone in %ds",
  2212. assignment.spool_id,
  2213. assignment.ams_id,
  2214. assignment.tray_id,
  2215. int(slot_unlink_grace.GRACE_SECONDS),
  2216. )
  2217. continue
  2218. logger.info(
  2219. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2220. assignment.spool_id,
  2221. assignment.ams_id,
  2222. assignment.tray_id,
  2223. )
  2224. stale.append(assignment) # Slot empty
  2225. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2226. # A Bambu Lab spool is in this slot — check if it's the same spool
  2227. # that's currently assigned. If yes, keep the assignment (avoids
  2228. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2229. # the printer's filament preset on every startup).
  2230. tray_uuid = current_tray.get("tray_uuid", "")
  2231. tag_uid = current_tray.get("tag_uid", "")
  2232. spool = assignment.spool
  2233. spool_matches = False
  2234. if spool:
  2235. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2236. spool.tag_uid
  2237. and tag_uid
  2238. and tag_uid != "0000000000000000"
  2239. and spool.tag_uid.upper() == tag_uid.upper()
  2240. ):
  2241. spool_matches = True
  2242. if spool_matches:
  2243. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2244. cur_color = current_tray.get("tray_color", "")
  2245. cur_type = current_tray.get("tray_type", "")
  2246. fp_color = assignment.fingerprint_color or ""
  2247. fp_type = assignment.fingerprint_type or ""
  2248. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2249. assignment.fingerprint_color = cur_color
  2250. assignment.fingerprint_type = cur_type
  2251. logger.debug(
  2252. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2253. assignment.spool_id,
  2254. assignment.ams_id,
  2255. assignment.tray_id,
  2256. )
  2257. continue
  2258. # Different BL spool or unrecognized — unlink so auto-assign can match
  2259. logger.info(
  2260. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2261. assignment.spool_id,
  2262. assignment.ams_id,
  2263. assignment.tray_id,
  2264. tray_uuid,
  2265. )
  2266. stale.append(assignment)
  2267. else:
  2268. cur_color = current_tray.get("tray_color", "")
  2269. cur_type = current_tray.get("tray_type", "")
  2270. cur_state = current_tray.get("state")
  2271. fp_color = assignment.fingerprint_color or ""
  2272. fp_type = assignment.fingerprint_type or ""
  2273. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2274. # the slot was empty when the user pre-assigned via SpoolBuddy
  2275. # (the firmware drops ams_filament_setting on empty slots, so
  2276. # MQTT was deferred). The moment any filament gets inserted
  2277. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2278. # reconfigured spool — fire the deferred configuration.
  2279. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2280. # extruder" code) OR, on firmwares that don't use the state
  2281. # enum meaningfully, a non-empty tray_type when state is
  2282. # NOT one of the firmware's explicit empty signals (9, 10).
  2283. # state-only was wrong for firmwares that never set 11 — A1
  2284. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2285. # always report state=3 — so the replay never fired for them
  2286. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2287. # explicit "empty" signals authoritative over any stale
  2288. # tray_type that might survive the relay's auto-clearing.
  2289. #
  2290. # tray_exist_bits comes first because that guard cannot tell
  2291. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2292. # writes state=9 when the bit is 0 and leaves it there when the
  2293. # bit returns. A non-RFID spool inserted into a pre-assigned
  2294. # slot brings no tray_type with it, so the stale 9 made this
  2295. # expression false forever and the deferred config never fired
  2296. # — the deadlock #1322 removed from the assign path, still in
  2297. # place here (#3084, #3100).
  2298. loaded = spool_present(current_tray) is True or (
  2299. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2300. )
  2301. if not fp_type.strip() and loaded and assignment.spool:
  2302. try:
  2303. from backend.app.api.routes.inventory import (
  2304. apply_spool_to_slot_via_mqtt,
  2305. )
  2306. await apply_spool_to_slot_via_mqtt(
  2307. db=db,
  2308. current_user=None,
  2309. spool=assignment.spool,
  2310. printer_id=printer_id,
  2311. ams_id=assignment.ams_id,
  2312. tray_id=assignment.tray_id,
  2313. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2314. current_tray_type=cur_type,
  2315. current_tray_sub_brands=current_tray.get("tray_sub_brands", ""),
  2316. )
  2317. logger.info(
  2318. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2319. assignment.spool_id,
  2320. printer_id,
  2321. assignment.ams_id,
  2322. assignment.tray_id,
  2323. )
  2324. except Exception:
  2325. logger.exception(
  2326. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2327. assignment.spool_id,
  2328. printer_id,
  2329. assignment.ams_id,
  2330. assignment.tray_id,
  2331. )
  2332. assignment.fingerprint_color = cur_color
  2333. assignment.fingerprint_type = cur_type
  2334. continue
  2335. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2336. # Blank tray data mid-print is a runout, not a swap: the
  2337. # firmware clears colour and type when it unloads a spool
  2338. # it just emptied. Unlinking here would erase the record
  2339. # of which spool fed the print so far.
  2340. if printing_now and not cur_color.strip() and not cur_type.strip():
  2341. logger.info(
  2342. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2343. "(runout?)",
  2344. assignment.spool_id,
  2345. assignment.ams_id,
  2346. assignment.tray_id,
  2347. )
  2348. continue
  2349. # Same reasoning off the print, on firmware's own say-so:
  2350. # a blank tray report from a slot whose tray_exist_bits
  2351. # bit is set describes a spool the AMS cannot identify —
  2352. # a non-RFID one, or one whose slot was reset — not a
  2353. # spool that was taken out. Deleting the assignment there
  2354. # threw away the identity the user had supplied, which is
  2355. # the only place it existed (#3100). A slot the bit calls
  2356. # empty, or one that carries no bit at all, still unlinks.
  2357. #
  2358. # Unless the slot was reported empty first: a removal
  2359. # already held means a spool came out and another went
  2360. # in, so the blank report keeps the hold running below
  2361. # rather than cancelling it (#3186).
  2362. if (
  2363. spool_present(current_tray) is True
  2364. and not cur_color.strip()
  2365. and not cur_type.strip()
  2366. and not slot_unlink_grace.is_held(
  2367. printer_id,
  2368. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2369. )
  2370. ):
  2371. logger.info(
  2372. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2373. "tray reports no filament data yet",
  2374. assignment.spool_id,
  2375. assignment.ams_id,
  2376. assignment.tray_id,
  2377. )
  2378. continue
  2379. # A blank report the presence bit does not vouch for is
  2380. # still only one push. An idle X1C cleared a whole AMS
  2381. # unit's bits, colour and type for a moment and lost
  2382. # four saved assignments that way (#3186); unlink only
  2383. # if the slot is still blank after the grace period.
  2384. if not cur_color.strip() and not cur_type.strip():
  2385. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2386. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2387. held.add(hold_key)
  2388. logger.info(
  2389. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2390. "unlinking if it is still blank in %ds",
  2391. assignment.spool_id,
  2392. assignment.ams_id,
  2393. assignment.tray_id,
  2394. int(slot_unlink_grace.GRACE_SECONDS),
  2395. )
  2396. continue
  2397. # Fingerprint mismatch — but check if tray now matches the
  2398. # assigned spool (e.g. auto-configure changed the tray).
  2399. # Both sides are reduced to the type the slot can carry
  2400. # before comparing: the assign path writes that rather
  2401. # than the spool's raw material (#2902), so a spool whose
  2402. # material is a product line — "PLA+", "HTPLA" — reports
  2403. # back as "PLA" and would otherwise fail this check and
  2404. # be auto-unlinked from the slot it was just assigned to.
  2405. # Reducing the printer's side too keeps slots configured
  2406. # by an older Bambuddy, still reporting "PLA+", matching.
  2407. spool = assignment.spool
  2408. if spool:
  2409. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2410. # Two ways the assign path can have arrived at the
  2411. # slot's type, so both count as "we wrote this".
  2412. # The material column is one; the spool's preset is
  2413. # the other, and it outranks the material when the
  2414. # spool has one -- a spool whose material says PLA
  2415. # and whose preset is "Bambu PLA Aero" puts
  2416. # PLA-AERO in the slot (#2902). Read from the stored
  2417. # preset name rather than resolving the preset,
  2418. # because this runs on every AMS push and a cloud
  2419. # lookup here would be both slow and unavailable on
  2420. # the unauthenticated replay path.
  2421. spool_types = {printer_filament_type(spool.material).upper()}
  2422. if spool.slicer_filament_name:
  2423. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2424. # An imported local preset stores its type outright,
  2425. # which is what the assign path used -- and the name
  2426. # above may be unset. One keyed read, and only on a
  2427. # mismatch, which is rare.
  2428. #
  2429. # slicer_filament is free text up to fifty characters,
  2430. # so the digits have to be checked against the range
  2431. # of the integer primary key they are about to be
  2432. # compared with. Postgres raises on an out-of-range
  2433. # integer rather than simply not matching, and that
  2434. # would poison this session and abandon the rest of
  2435. # the cleanup pass.
  2436. lp_ref = (spool.slicer_filament or "").strip()
  2437. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2438. from backend.app.models.local_preset import LocalPreset as _LP
  2439. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2440. if lp_type:
  2441. spool_types.add(printer_filament_type(lp_type).upper())
  2442. if (
  2443. _colors_similar(cur_color, spool_color)
  2444. and printer_filament_type(cur_type).upper() in spool_types
  2445. ):
  2446. logger.info(
  2447. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2448. assignment.spool_id,
  2449. assignment.ams_id,
  2450. assignment.tray_id,
  2451. )
  2452. assignment.fingerprint_color = cur_color
  2453. assignment.fingerprint_type = cur_type
  2454. continue
  2455. logger.info(
  2456. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2457. assignment.spool_id,
  2458. assignment.ams_id,
  2459. assignment.tray_id,
  2460. cur_color,
  2461. cur_type,
  2462. fp_color,
  2463. fp_type,
  2464. spool.rgba if spool else "?",
  2465. spool.material if spool else "?",
  2466. )
  2467. stale.append(assignment) # Spool changed
  2468. slot_unlink_grace.settle(printer_id, "inventory", held)
  2469. # Snapshot slots before delete — ORM attribute access after the
  2470. # commit would refresh against a deleted row.
  2471. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2472. for a in stale:
  2473. await db.delete(a)
  2474. if stale:
  2475. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2476. # Commit any changes (stale deletions and/or fingerprint updates)
  2477. await db.commit()
  2478. # Tell open browsers the assignment is gone (#2575). Only the manual
  2479. # REST assign/unassign endpoints broadcast this event; without it the
  2480. # frontend's spool-assignments cache keeps rendering the unlinked
  2481. # spool on the slot until an unrelated refetch — which reads exactly
  2482. # like "the fix didn't work" (reporter verified: a browser refresh
  2483. # after the swap showed the correct state all along).
  2484. for ams_id, tray_id in unlinked_slots:
  2485. await ws_manager.broadcast(
  2486. {
  2487. "type": "spool_assignment_changed",
  2488. "printer_id": printer_id,
  2489. "ams_id": ams_id,
  2490. "tray_id": tray_id,
  2491. }
  2492. )
  2493. except Exception as e:
  2494. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2495. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2496. """Delete Spoolman slot rows whose held removal has run its grace period.
  2497. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2498. talks to Spoolman for every tray; this only needs the local rows, so it
  2499. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2500. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2501. not in a slot the presence bit calls occupied -- and nothing else.
  2502. """
  2503. logger = logging.getLogger(__name__)
  2504. try:
  2505. async with async_session() as db:
  2506. from backend.app.api.routes.settings import get_setting
  2507. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2508. from backend.app.services.ams_slot_presence import spool_present
  2509. enabled = await get_setting(db, "spoolman_enabled")
  2510. if not enabled or enabled.lower() != "true":
  2511. return
  2512. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2513. if sync_mode and sync_mode != "auto":
  2514. return
  2515. trays: dict[tuple[int, int], dict] = {}
  2516. for ams_unit in ams_data or []:
  2517. if not isinstance(ams_unit, dict):
  2518. continue
  2519. for tray in ams_unit.get("tray", []):
  2520. if isinstance(tray, dict):
  2521. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2522. rows = (
  2523. (
  2524. await db.execute(
  2525. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2526. )
  2527. )
  2528. .scalars()
  2529. .all()
  2530. )
  2531. held: set[tuple] = set()
  2532. expired: list[tuple[int, int]] = []
  2533. for row in rows:
  2534. tray = trays.get((row.ams_id, row.tray_id))
  2535. if tray is None or printing_now:
  2536. continue
  2537. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2538. continue
  2539. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2540. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2541. continue
  2542. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2543. expired.append((row.ams_id, row.tray_id))
  2544. else:
  2545. held.add(hold_key)
  2546. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2547. if not expired:
  2548. return
  2549. # A statement rather than ORM deletes, like the sync pass: the two
  2550. # can overlap, and a row the other already removed must not fail
  2551. # this commit.
  2552. for ams_id, tray_id in expired:
  2553. await db.execute(
  2554. delete(SpoolmanSlotAssignment).where(
  2555. SpoolmanSlotAssignment.printer_id == printer_id,
  2556. SpoolmanSlotAssignment.ams_id == ams_id,
  2557. SpoolmanSlotAssignment.tray_id == tray_id,
  2558. )
  2559. )
  2560. await db.commit()
  2561. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2562. for ams_id, tray_id in expired:
  2563. await ws_manager.broadcast(
  2564. {
  2565. "type": "spool_assignment_changed",
  2566. "printer_id": printer_id,
  2567. "ams_id": ams_id,
  2568. "tray_id": tray_id,
  2569. }
  2570. )
  2571. except Exception as e:
  2572. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2573. async def _recheck_held_unlinks(printer_id: int) -> None:
  2574. """Re-run just the slot cleanup against the printer's current AMS state.
  2575. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2576. passes otherwise run only when the AMS hash changes, and a slot that went
  2577. empty and stayed empty may never change it again.
  2578. """
  2579. status = printer_manager.get_status(printer_id)
  2580. # A disconnected printer's state is its last report, not a new one: acting
  2581. # on it would "confirm" a removal nobody has seen for the whole grace
  2582. # period. Leave the holds; the first push after reconnecting decides.
  2583. if status is None or not status.connected:
  2584. return
  2585. ams_raw = status.raw_data.get("ams")
  2586. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2587. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2588. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2589. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2590. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2591. async def on_ams_change(printer_id: int, ams_data: list):
  2592. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2593. logger = logging.getLogger(__name__)
  2594. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  2595. # on_print_complete may pop _active_sessions during our awaits (#880).
  2596. from backend.app.services.usage_tracker import _active_sessions
  2597. _print_active = printer_id in _active_sessions
  2598. # A slot that reports empty while a print is running is a filament runout,
  2599. # not a spool swap: the spool is still physically in the AMS, just
  2600. # consumed. Dropping either inventory backend's slot link there loses the
  2601. # only record of which spool fed the print, so the completion path can't
  2602. # charge the runout segment to anything. Both cleanup passes below consult
  2603. # this; computed once, up front, so neither depends on the other having run.
  2604. _unlink_state = printer_manager.get_status(printer_id)
  2605. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2606. # The session alone is not enough: a restart that finds a stale persisted
  2607. # session registers none for the print that is running.
  2608. _print_active = _print_active or printing_now
  2609. # MQTT relay - publish AMS change
  2610. try:
  2611. printer_info = printer_manager.get_printer(printer_id)
  2612. if printer_info:
  2613. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2614. except Exception:
  2615. pass # Don't fail AMS callback if MQTT fails
  2616. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2617. # This ensures frontend gets immediate updates when AMS slots are configured
  2618. try:
  2619. state = printer_manager.get_status(printer_id)
  2620. if state:
  2621. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2622. await ws_manager.send_printer_status(
  2623. printer_id,
  2624. printer_state_to_dict(
  2625. state,
  2626. printer_id,
  2627. printer_manager.get_model(printer_id),
  2628. printer_manager.get_drying_targets(printer_id),
  2629. ),
  2630. )
  2631. except Exception as e:
  2632. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2633. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2634. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2635. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  2636. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2637. # "no existing assignment" for the same (printer, ams, tray) and race to
  2638. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2639. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2640. # bug stayed latent there. See _ams_assignment_locks comment for details.
  2641. try:
  2642. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2643. from sqlalchemy.orm import selectinload
  2644. from backend.app.api.routes.settings import get_setting
  2645. from backend.app.models.spool import Spool
  2646. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2647. from backend.app.services.spool_tag_matcher import (
  2648. auto_assign_spool,
  2649. create_spool_from_tray,
  2650. find_matching_untagged_spool,
  2651. get_spool_by_tag,
  2652. is_bambu_tag,
  2653. is_valid_tag,
  2654. link_tag_to_inventory_spool,
  2655. tag_belongs_to_archived_spool,
  2656. )
  2657. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2658. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2659. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2660. if not _spoolman_on or _spoolman_on.lower() != "true":
  2661. for ams_unit in ams_data:
  2662. if not isinstance(ams_unit, dict):
  2663. continue
  2664. ams_id = int(ams_unit.get("id", 0))
  2665. for tray in ams_unit.get("tray", []):
  2666. if not isinstance(tray, dict):
  2667. continue
  2668. tray_id = int(tray.get("id", 0))
  2669. tag_uid = tray.get("tag_uid", "")
  2670. tray_uuid = tray.get("tray_uuid", "")
  2671. tray_info_idx = tray.get("tray_info_idx", "")
  2672. if not tray.get("tray_type"):
  2673. # Slot reported empty — drop any cached unknown-tag
  2674. # broadcast so reinserting the same spool re-prompts.
  2675. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2676. continue # Empty slot
  2677. # Check if assignment already exists for this slot
  2678. existing = await db.execute(
  2679. select(SA)
  2680. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2681. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2682. )
  2683. existing_assignment = existing.scalar_one_or_none()
  2684. if existing_assignment:
  2685. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2686. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2687. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2688. # Skip during active prints: the usage tracker handles deduction
  2689. # precisely via 3MF data on print completion. Without this guard the
  2690. # AMS remain% SET and the usage tracker ADD both fire from the same
  2691. # MQTT message, doubling the deduction (#880).
  2692. if _print_active:
  2693. continue
  2694. remain_raw = tray.get("remain")
  2695. if (
  2696. remain_raw is not None
  2697. and existing_assignment.spool
  2698. and not existing_assignment.spool.weight_locked
  2699. ):
  2700. try:
  2701. remain_val = int(remain_raw)
  2702. except (TypeError, ValueError):
  2703. remain_val = -1
  2704. if 1 <= remain_val <= 100:
  2705. lw = existing_assignment.spool.label_weight or 1000
  2706. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2707. current_used = existing_assignment.spool.weight_used or 0
  2708. if new_used > current_used + 1:
  2709. logger.info(
  2710. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2711. existing_assignment.spool_id,
  2712. current_used,
  2713. new_used,
  2714. remain_val,
  2715. )
  2716. existing_assignment.spool.weight_used = new_used
  2717. await db.commit()
  2718. # A K-profile the slot lost (the default K after a reset or
  2719. # power cycle) is put back by kprofile_drift on the next idle
  2720. # push; a different real profile was picked on purpose and
  2721. # stays (#3219, item 44).
  2722. continue
  2723. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2724. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2725. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2726. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  2727. # An archived spool still in the AMS: the slot
  2728. # stays free rather than adopting its tag.
  2729. continue
  2730. if not spool:
  2731. # Try matching an untagged inventory spool (same material/color)
  2732. spool = await find_matching_untagged_spool(db, tray)
  2733. if spool:
  2734. await link_tag_to_inventory_spool(db, spool, tray)
  2735. elif _auto_add_unknown:
  2736. spool = await create_spool_from_tray(db, tray)
  2737. else:
  2738. # Auto-add disabled: surface the slot so the
  2739. # user can add it manually via the UI.
  2740. await _broadcast_unknown_tag(
  2741. printer_id=printer_id,
  2742. ams_id=ams_id,
  2743. tray_id=tray_id,
  2744. tag_uid=tag_uid,
  2745. tray_uuid=tray_uuid,
  2746. tray_type=tray.get("tray_type"),
  2747. tray_color=tray.get("tray_color"),
  2748. tray_sub_brands=tray.get("tray_sub_brands"),
  2749. tray_count=len(ams_unit.get("tray", [])),
  2750. )
  2751. continue
  2752. # Slot matched (existing tag, untagged inventory
  2753. # match, or freshly auto-created spool) — drop any
  2754. # stale dedup so a future tag swap re-prompts.
  2755. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2756. await auto_assign_spool(
  2757. printer_id,
  2758. ams_id,
  2759. tray_id,
  2760. spool,
  2761. printer_manager,
  2762. db,
  2763. tray_info_idx=tray_info_idx,
  2764. )
  2765. await db.commit()
  2766. await ws_manager.broadcast(
  2767. {
  2768. "type": "spool_auto_assigned",
  2769. "printer_id": printer_id,
  2770. "ams_id": ams_id,
  2771. "tray_id": tray_id,
  2772. "spool_id": spool.id,
  2773. }
  2774. )
  2775. logger.info(
  2776. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2777. spool.id,
  2778. printer_id,
  2779. ams_id,
  2780. tray_id,
  2781. )
  2782. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  2783. db, tag_uid, tray_uuid
  2784. ):
  2785. # Non-BL spool with some tag — let user choose (not
  2786. # an archived one's, whose slot stays free)
  2787. await _broadcast_unknown_tag(
  2788. printer_id=printer_id,
  2789. ams_id=ams_id,
  2790. tray_id=tray_id,
  2791. tag_uid=tag_uid,
  2792. tray_uuid=tray_uuid,
  2793. tray_type=tray.get("tray_type"),
  2794. tray_color=tray.get("tray_color"),
  2795. tray_sub_brands=tray.get("tray_sub_brands"),
  2796. tray_count=len(ams_unit.get("tray", [])),
  2797. )
  2798. # No-tag slots (generic non-RFID filament) are left alone:
  2799. # nothing to identify, prompting "+ Add" would just create
  2800. # ghost spools with empty tags on every confirm.
  2801. except Exception as e:
  2802. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2803. try:
  2804. async with async_session() as db:
  2805. from backend.app.api.routes.settings import get_setting
  2806. from backend.app.models.printer import Printer
  2807. # Check if Spoolman is enabled
  2808. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2809. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2810. return
  2811. # Check sync mode
  2812. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2813. if sync_mode and sync_mode != "auto":
  2814. return # Only sync on auto mode
  2815. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2816. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2817. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2818. # always owned by per-print tracking, never by AMS auto-sync. The
  2819. # setting is still read by the settings UI for backwards compat but
  2820. # has no effect on the sync path here.
  2821. # Get Spoolman URL
  2822. spoolman_url = await get_setting(db, "spoolman_url")
  2823. if not spoolman_url:
  2824. return
  2825. # Get or create Spoolman client
  2826. client = await get_spoolman_client()
  2827. if not client:
  2828. try:
  2829. client = await init_spoolman_client(spoolman_url)
  2830. except ValueError as exc:
  2831. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2832. return
  2833. # Check if Spoolman is reachable
  2834. if not await client.health_check():
  2835. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2836. return
  2837. # Get printer name for location
  2838. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2839. printer = result.scalar_one_or_none()
  2840. printer_name = printer.name if printer else f"Printer {printer_id}"
  2841. # OPTIMIZATION: Fetch all spools once before processing trays
  2842. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2843. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2844. try:
  2845. cached_spools = await client.get_spools()
  2846. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2847. except Exception as e:
  2848. logger.error(
  2849. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2850. printer_id,
  2851. e,
  2852. )
  2853. return
  2854. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2855. from sqlalchemy.orm import selectinload
  2856. from backend.app.models.spool_assignment import SpoolAssignment
  2857. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2858. from backend.app.services.ams_slot_presence import spool_present
  2859. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2860. # Built-in remaining weight, used by sync_ams_tray only when the
  2861. # firmware reports an unusable remain%/tray_weight for a slot.
  2862. #
  2863. # Left empty since #2812. This block runs in Spoolman mode only,
  2864. # and until then the built-in table was emptied on the switch, so
  2865. # there was never anything here to read and the fallback was inert.
  2866. # Preserving those rows makes it live again, and it is keyed by slot
  2867. # rather than by spool: after a mode switch the tray may well hold
  2868. # different filament, and ``create_spool`` writes ``remaining_weight``
  2869. # unconditionally, so a stale figure would be seeded into a brand new
  2870. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2871. # intent survives for whoever revisits the cross-mode fallback.
  2872. inventory_weights: dict[tuple[int, int], float] = {}
  2873. if not await spoolman_owns_assignments(db):
  2874. try:
  2875. assign_result = await db.execute(
  2876. select(SpoolAssignment)
  2877. .options(selectinload(SpoolAssignment.spool))
  2878. .where(SpoolAssignment.printer_id == printer_id)
  2879. )
  2880. for assignment in assign_result.scalars().all():
  2881. spool = assignment.spool
  2882. if spool and spool.label_weight > 0:
  2883. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2884. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2885. except Exception as e:
  2886. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2887. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2888. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2889. try:
  2890. slot_result = await db.execute(
  2891. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2892. )
  2893. for slot in slot_result.scalars().all():
  2894. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2895. except Exception as e:
  2896. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2897. # Sync each AMS tray and collect slot changes for DB persistence
  2898. synced = 0
  2899. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2900. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2901. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  2902. for ams_unit in ams_data:
  2903. if not isinstance(ams_unit, dict):
  2904. continue
  2905. ams_id = int(ams_unit.get("id", 0))
  2906. trays = ams_unit.get("tray", [])
  2907. for tray_data in trays:
  2908. if not isinstance(tray_data, dict):
  2909. continue
  2910. tray_id_raw = int(tray_data.get("id", 0))
  2911. tray = client.parse_ams_tray(ams_id, tray_data)
  2912. if not tray:
  2913. # Empty tray slot — record for local assignment cleanup
  2914. # and drop any cached unknown-tag broadcast so a
  2915. # reinserted spool re-prompts.
  2916. #
  2917. # Not during a running print: a slot that empties there
  2918. # is a filament runout, and the spool is still in the
  2919. # AMS. `spoolman_slot_assignments` is how a tag-less
  2920. # spool assigned through the Bambuddy UI is resolved at
  2921. # completion (#1459), so deleting the row mid-print
  2922. # loses the runout segment's usage — the same failure
  2923. # the internal inventory's auto-unlink had.
  2924. #
  2925. # Nor when firmware's presence bit says the slot is
  2926. # occupied. parse_ams_tray calls a tray with no type or
  2927. # no colour empty, and a spool the AMS cannot read has
  2928. # neither until something configures it — so a tag-less
  2929. # spool assigned through the UI had its row deleted by
  2930. # the first idle push after it was inserted. Same
  2931. # deletion as the internal inventory's in #3100, same
  2932. # answer, so the two modes stay in step.
  2933. #
  2934. # And only once the slot has stayed empty for the grace
  2935. # period -- the internal inventory's #3186 answer, for
  2936. # the same one-push blank.
  2937. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  2938. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  2939. if not printing_now and (
  2940. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  2941. ):
  2942. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2943. empty_slots.append((ams_id, tray_id_raw))
  2944. else:
  2945. spoolman_held.add(hold_key)
  2946. logger.info(
  2947. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  2948. "unlinking if it is still empty in %ds",
  2949. ams_id,
  2950. tray_id_raw,
  2951. linked_spool,
  2952. int(slot_unlink_grace.GRACE_SECONDS),
  2953. )
  2954. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2955. continue
  2956. spool_tag = (
  2957. tray.tray_uuid
  2958. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2959. else tray.tag_uid
  2960. )
  2961. # Provide the hint only when no RFID is available
  2962. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2963. try:
  2964. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2965. result = await client.sync_ams_tray(
  2966. tray,
  2967. printer_name,
  2968. db,
  2969. # Per-print tracking is the only weight writer (#1119).
  2970. # AMS auto-sync still maintains spool metadata / slot
  2971. # assignments but no longer touches remaining_weight.
  2972. disable_weight_sync=True,
  2973. cached_spools=cached_spools,
  2974. inventory_remaining=inv_remaining,
  2975. spoolman_spool_id_hint=hint,
  2976. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2977. )
  2978. if result is None and spool_tag and not auto_add_unknown_rfid:
  2979. # Spoolman skipped auto-create per user setting — surface
  2980. # the slot so the UI can offer "+ Add to inventory".
  2981. await _broadcast_unknown_tag(
  2982. printer_id=printer_id,
  2983. ams_id=ams_id,
  2984. tray_id=tray.tray_id,
  2985. tag_uid=tray.tag_uid or "",
  2986. tray_uuid=tray.tray_uuid or "",
  2987. tray_type=tray.tray_type,
  2988. tray_color=tray.tray_color,
  2989. tray_sub_brands=tray.tray_sub_brands,
  2990. tray_count=len(trays),
  2991. )
  2992. elif result:
  2993. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2994. if result:
  2995. synced += 1
  2996. if result.get("id"):
  2997. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2998. # If a new spool was created, add it to the cache
  2999. # so subsequent trays can find it if they reference the same tag
  3000. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  3001. if not spool_exists:
  3002. cached_spools.append(result)
  3003. logger.debug(
  3004. "[Printer %s] Added newly created spool %s to cache",
  3005. printer_id,
  3006. result["id"],
  3007. )
  3008. # Reconcile slot_preset_mappings (the same row internal
  3009. # mode keeps in sync via inventory + spool_tag_matcher).
  3010. # Without this the slot card surfaces the previous spool's
  3011. # preset name — same bug shape, different inventory mode.
  3012. from backend.app.services.slot_preset_writer import (
  3013. upsert_slot_preset_for_spoolman_spool,
  3014. )
  3015. await upsert_slot_preset_for_spoolman_spool(
  3016. db=db,
  3017. spoolman_spool=result,
  3018. tray_info_idx=tray.tray_info_idx or "",
  3019. tray_sub_brands=tray.tray_sub_brands or "",
  3020. tray_type=tray.tray_type or "",
  3021. printer_id=printer_id,
  3022. ams_id=ams_id,
  3023. tray_id=tray.tray_id,
  3024. )
  3025. except Exception as e:
  3026. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3027. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3028. if synced > 0:
  3029. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3030. # Persist slot assignment changes to the local table
  3031. if slot_changes or empty_slots:
  3032. try:
  3033. for ams_id, tray_id, spool_id in slot_changes:
  3034. await db.execute(
  3035. text(
  3036. "INSERT INTO spoolman_slot_assignments"
  3037. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  3038. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  3039. " ON CONFLICT(printer_id, ams_id, tray_id)"
  3040. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  3041. ),
  3042. {
  3043. "printer_id": printer_id,
  3044. "ams_id": ams_id,
  3045. "tray_id": tray_id,
  3046. "spool_id": spool_id,
  3047. },
  3048. )
  3049. for ams_id, tray_id in empty_slots:
  3050. await db.execute(
  3051. delete(SpoolmanSlotAssignment).where(
  3052. SpoolmanSlotAssignment.printer_id == printer_id,
  3053. SpoolmanSlotAssignment.ams_id == ams_id,
  3054. SpoolmanSlotAssignment.tray_id == tray_id,
  3055. )
  3056. )
  3057. await db.commit()
  3058. except Exception as e:
  3059. await db.rollback()
  3060. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3061. else:
  3062. # Tell open browsers the slot changed. This loop rewrites
  3063. # slot_preset_mappings via upsert_slot_preset_for_spoolman_spool
  3064. # above, and the AMS slot card reads that row ahead of the
  3065. # live tray_info_idx -- so with no event the card keeps
  3066. # showing the previous spool's preset name. Internal mode
  3067. # raises spool_auto_assigned for the same reason; this loop
  3068. # broadcast nothing at all, which made Spoolman mode the
  3069. # worse half of the same bug. On the else branch so a
  3070. # failed commit stays silent and a broadcast failure cannot
  3071. # roll back rows that are already committed.
  3072. for ams_id, tray_id, *_ in (*slot_changes, *empty_slots):
  3073. await ws_manager.broadcast(
  3074. {
  3075. "type": "spool_assignment_changed",
  3076. "printer_id": printer_id,
  3077. "ams_id": ams_id,
  3078. "tray_id": tray_id,
  3079. }
  3080. )
  3081. except Exception as e:
  3082. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3083. # Largest finish photo attached to a notification; a bigger one is still linked.
  3084. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3085. async def _finish_photo_for_notification(
  3086. db, archive, archive_id: int, filename: str
  3087. ) -> tuple[str | None, bytes | None]:
  3088. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3089. With authentication off the link is the archive's own photo route, as it
  3090. always was: it opens without a login and doesn't expire. With
  3091. authentication on that route needs a media token, which nothing tapping a
  3092. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3093. link only ever answered 401. The photo is then saved as a notification
  3094. photo as well (utils/notification_photos.py) and the link points there: an
  3095. unguessable name that opens this one photo and nothing else, for 3 days.
  3096. The link is relative when no External URL is set. Bytes over
  3097. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3098. ``(None, None)`` when the photo can't be found.
  3099. """
  3100. from backend.app.api.routes.settings import get_setting
  3101. from backend.app.core.auth import is_auth_enabled
  3102. from backend.app.utils.archive_paths import find_archive_photo
  3103. from backend.app.utils.notification_photos import save_notification_photo
  3104. log = logging.getLogger(__name__)
  3105. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3106. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3107. photo_bytes: bytes | None = None
  3108. try:
  3109. photo_path = find_archive_photo(archive, filename)
  3110. if photo_path is not None:
  3111. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3112. except Exception as e:
  3113. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3114. try:
  3115. auth_on = await is_auth_enabled(db)
  3116. except Exception:
  3117. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3118. if auth_on:
  3119. url = None
  3120. if photo_bytes:
  3121. try:
  3122. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3123. url = f"{base}/api/v1/notifications/photos/{name}"
  3124. except Exception as e:
  3125. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3126. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3127. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3128. return url, None
  3129. if photo_bytes:
  3130. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3131. return url, photo_bytes
  3132. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3133. """Capture a camera snapshot for notification image attachment.
  3134. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3135. Uses: external camera > buffered frame > fresh capture.
  3136. Turns the chamber light on for the picture when the printer asks for it
  3137. (#1655). ``light=False`` is for callers that capture all through a print,
  3138. where the light would flash with every frame.
  3139. """
  3140. if not printer:
  3141. return None
  3142. async with camera_light(printer if light else None):
  3143. return await _capture_snapshot_frame(printer_id, printer, logger)
  3144. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3145. """The capture behind ``_capture_snapshot_for_notification``."""
  3146. try:
  3147. from backend.app.api.routes.settings import get_setting
  3148. async with async_session() as db:
  3149. capture_enabled = await get_setting(db, "capture_finish_photo")
  3150. if capture_enabled is not None and capture_enabled.lower() != "true":
  3151. return None
  3152. # Try external camera first
  3153. if printer.external_camera_enabled and printer.external_camera_url:
  3154. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3155. from backend.app.api.routes.camera import live_frame_for_capture
  3156. from backend.app.services.external_camera import capture_frame
  3157. # An external camera allows one reader, so capturing while a viewer
  3158. # is attached fails (#2707). A None here falls through to the paths
  3159. # below exactly as a failed capture did.
  3160. defer, buffered = live_frame_for_capture(printer_id)
  3161. if defer:
  3162. frame_data = buffered
  3163. else:
  3164. frame_data = await capture_frame(
  3165. printer.external_camera_url,
  3166. printer.external_camera_type or "mjpeg",
  3167. snapshot_url=printer.external_camera_snapshot_url,
  3168. )
  3169. if frame_data and len(frame_data) <= 2_500_000:
  3170. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3171. return _apply_camera_rotation(frame_data, printer, logger)
  3172. # Try buffered frame from active stream
  3173. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3174. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3175. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3176. buffered_frame = get_buffered_frame(printer_id)
  3177. if (active_for_printer or active_chamber) and buffered_frame:
  3178. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3179. if len(buffered_frame) <= 2_500_000:
  3180. return _apply_camera_rotation(buffered_frame, printer, logger)
  3181. # Fresh capture from printer camera
  3182. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3183. from backend.app.services.camera import capture_camera_frame_bytes
  3184. frame_data = await capture_camera_frame_bytes(
  3185. printer.ip_address, printer.access_code, printer.model, timeout=15
  3186. )
  3187. if frame_data and len(frame_data) <= 2_500_000:
  3188. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3189. return _apply_camera_rotation(frame_data, printer, logger)
  3190. except Exception as e:
  3191. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3192. return None
  3193. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3194. """#1867: bank a recent in-print camera frame for the finish photo.
  3195. Called on every layer change and (#2547) on every print-progress advance.
  3196. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3197. path has a pre-End-G-code image for prints that end with a plate swap.
  3198. Both drivers are print telemetry that stops the instant printing ends: no
  3199. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3200. plate swap) executes. So the last banked frame is always the finished print,
  3201. never the swapped plate — that property is what the #1867 path relies on and
  3202. it must survive any change to the throttle below.
  3203. Layer changes alone were not enough: they stop when the *final* layer
  3204. begins, which on a three-minute last layer left the bank stale by the whole
  3205. length of that layer (#2547). Progress keeps ticking through it.
  3206. Best-effort: any failure just leaves the previous banked frame.
  3207. """
  3208. logger = logging.getLogger(__name__)
  3209. client = printer_manager.get_client(printer_id)
  3210. state = client.state if client else None
  3211. if not state or state.state != "RUNNING":
  3212. return
  3213. # Only during actual extrusion — firmware ticks layer_num during the
  3214. # pre-print calibration sequence, whose sub-stages are non-zero.
  3215. if state.mc_print_sub_stage not in (None, 0):
  3216. return
  3217. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3218. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3219. # now that progress advances also drive banking, that exemption would fire a
  3220. # camera grab on every percent tick of the last layer. Bambu printers accept
  3221. # one RTSP client at a time, so each grab contends with the live view.
  3222. now = time.monotonic()
  3223. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3224. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3225. return
  3226. total = state.total_layers or 0
  3227. try:
  3228. async with async_session() as db:
  3229. from backend.app.models.printer import Printer
  3230. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3231. printer = result.scalar_one_or_none()
  3232. if not printer:
  3233. return
  3234. # Reuses the notification snapshot path, which honours the
  3235. # `capture_finish_photo` setting (returns None when disabled) so we
  3236. # don't bank frames the user never asked for. Without the chamber light
  3237. # (#1655): this runs every 25 seconds for the whole print.
  3238. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3239. if frame:
  3240. _inprint_frame_bank[printer_id] = frame
  3241. _inprint_frame_bank_ts[printer_id] = now
  3242. logger.debug(
  3243. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3244. printer_id,
  3245. layer_num,
  3246. total,
  3247. len(frame),
  3248. )
  3249. except Exception as e:
  3250. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3251. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3252. """Apply camera rotation to snapshot image if configured."""
  3253. from backend.app.services.camera import apply_camera_rotation
  3254. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3255. async def _send_print_start_notification(
  3256. printer_id: int,
  3257. data: dict,
  3258. archive_data: dict | None = None,
  3259. logger=None,
  3260. ):
  3261. """Helper to send print start notification with optional archive data."""
  3262. if logger is None:
  3263. logger = logging.getLogger(__name__)
  3264. try:
  3265. async with async_session() as db:
  3266. from backend.app.models.printer import Printer
  3267. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3268. printer = result.scalar_one_or_none()
  3269. printer_name = printer.name if printer else f"Printer {printer_id}"
  3270. # Capture camera snapshot for notification image attachment
  3271. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3272. if image_data:
  3273. if archive_data is None:
  3274. archive_data = {}
  3275. archive_data["image_data"] = image_data
  3276. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3277. # Send user-specific email notification for print start
  3278. if archive_data and archive_data.get("created_by_id"):
  3279. await notification_service.send_user_print_email(
  3280. event_type="user_print_start",
  3281. created_by_id=archive_data["created_by_id"],
  3282. printer_name=printer_name,
  3283. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3284. db=db,
  3285. )
  3286. except Exception as e:
  3287. logger.warning("Notification on_print_start failed: %s", e)
  3288. async def _dispatch_user_print_email(
  3289. status: str,
  3290. created_by_id: int | None,
  3291. printer_name: str,
  3292. filename: str,
  3293. db,
  3294. image_data: bytes | None = None,
  3295. finish_photo_url: str | None = None,
  3296. ) -> None:
  3297. """Send a user-specific print-completion email based on print status.
  3298. Maps the normalised print status to the correct event type and delegates
  3299. to :meth:`NotificationService.send_user_print_email`. A single helper
  3300. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3301. "stopped"`` dispatch block at every call site.
  3302. Does nothing if *created_by_id* is ``None``.
  3303. """
  3304. if created_by_id is None:
  3305. return
  3306. if status == "completed":
  3307. event_type = "user_print_complete"
  3308. elif status == "failed":
  3309. event_type = "user_print_failed"
  3310. elif status in ("stopped", "aborted", "cancelled"):
  3311. event_type = "user_print_stopped"
  3312. else:
  3313. return
  3314. await notification_service.send_user_print_email(
  3315. event_type=event_type,
  3316. created_by_id=created_by_id,
  3317. printer_name=printer_name,
  3318. filename=filename,
  3319. db=db,
  3320. image_data=image_data,
  3321. finish_photo_url=finish_photo_url,
  3322. )
  3323. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3324. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3325. try:
  3326. from backend.app.services.archive import extract_printable_objects_from_archive
  3327. client = printer_manager.get_client(printer_id)
  3328. if not client:
  3329. return
  3330. # Extract with positions for UI overlay, scoped to the plate that
  3331. # is printing — resolve_plate_id is the same resolver /cover uses,
  3332. # so the object list can't disagree with the thumbnail it is drawn
  3333. # over (#2522).
  3334. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3335. app_settings.base_dir / archive.file_path,
  3336. plate_number=resolve_plate_id(client.state),
  3337. )
  3338. if printable_objects:
  3339. client.state.printable_objects = printable_objects
  3340. client.state.printable_objects_bbox_all = bbox_all
  3341. client.state.skipped_objects = []
  3342. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3343. except Exception as e:
  3344. logger.debug("Failed to extract printable objects from archive: %s", e)
  3345. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3346. """Put the skip-objects list back after a restart mid-print.
  3347. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3348. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3349. which the #1304 guard suppresses on the first RUNNING push after startup.
  3350. Everything else this hook restores (the archive, the usage-tracking session,
  3351. the timelapse baseline) was already handled; the object list was not, so a
  3352. restart mid-print took skip-objects away for the rest of that print.
  3353. Nothing recovered it either: the printer card gates its Skip button on the
  3354. object count, and the one endpoint that can rebuild the list is reachable
  3355. only from the modal that button opens.
  3356. Anchored on ``subtask_id``, which the firmware mints per print, so a
  3357. leftover ``status="printing"`` row from a completion we never saw cannot
  3358. hand this print someone else's objects. Without one, nothing is loaded
  3359. rather than guessed — the reload path on ``GET /print/objects`` covers that
  3360. case on demand.
  3361. """
  3362. client = printer_manager.get_client(printer_id)
  3363. if client is None or client.state.printable_objects:
  3364. return
  3365. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  3366. if subtask_id in ("", "0"):
  3367. return
  3368. from backend.app.models.archive import PrintArchive
  3369. archive = await db.scalar(
  3370. select(PrintArchive)
  3371. .where(
  3372. PrintArchive.printer_id == printer_id,
  3373. PrintArchive.status == "printing",
  3374. PrintArchive.subtask_id == subtask_id,
  3375. )
  3376. .order_by(PrintArchive.created_at.desc())
  3377. .limit(1)
  3378. )
  3379. if archive is not None:
  3380. _load_objects_from_archive(archive, printer_id, logger)
  3381. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3382. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3383. # past it; the second covers a handshake that failed again on the way back and
  3384. # armed a fresh one. Module-level so tests can shrink them.
  3385. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3386. # Retry ladder for the other temporary give-up: the file service answered and
  3387. # the transfer still did not finish, which at print start is usually the printer
  3388. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3389. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3390. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3391. # two cover a printer that stays busy well into the print.
  3392. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3393. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3394. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3395. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3396. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3397. # by view, so two views race), the cool-off retry task, and print completion.
  3398. # Without this they each read file_path == "" and each run a full copy, so the row
  3399. # ends up pointing at one timestamped directory while the others sit orphaned.
  3400. #
  3401. # Keyed by printer rather than archive because a printer runs one print at a time,
  3402. # which makes the two equally strong here — and it bounds the dict by printer
  3403. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3404. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3405. # resuming, so "no waiters" is not a question this API can answer.
  3406. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3407. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True) -> bool:
  3408. """Fill in a no-3MF archive from a 3MF that turned up later.
  3409. Returns True when the row was upgraded. Safe to call speculatively: it
  3410. verifies the archive still exists, is still a fallback, and that the file
  3411. is a readable 3MF before touching anything.
  3412. Serialised per printer — see ``_fallback_recovery_locks``.
  3413. """
  3414. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3415. async with lock:
  3416. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id, price=price)
  3417. async def _recover_fallback_archive_locked(
  3418. archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True
  3419. ) -> bool:
  3420. """The body of :func:`_recover_fallback_archive`, under its per-printer lock.
  3421. ``price`` is False when the print's end is being handled: the archive
  3422. still reads "printing" then, and its end prices it.
  3423. """
  3424. import zipfile
  3425. from backend.app.models.archive import PrintArchive
  3426. from backend.app.services.archive import ArchiveService
  3427. logger = logging.getLogger(__name__)
  3428. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3429. return False
  3430. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3431. # A truncated or half-written download is worse than no download: it
  3432. # would replace an honest empty archive with wrong metadata.
  3433. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3434. return False
  3435. async with async_session() as db:
  3436. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3437. if archive is None or archive.deleted_at is not None:
  3438. return False
  3439. if archive.file_path:
  3440. # Already recovered, or never was a fallback. Either way there is a
  3441. # real 3MF attached and overwriting it is not this function's job.
  3442. return False
  3443. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3444. service = ArchiveService(db)
  3445. recovered = await service.archive_print(
  3446. printer_id=printer_id,
  3447. source_file=source_3mf,
  3448. print_data={**print_data, "status": archive.status or "printing"},
  3449. subtask_id=archive.subtask_id,
  3450. update_archive_id=archive.id,
  3451. )
  3452. if recovered is None:
  3453. return False
  3454. logger.info(
  3455. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3456. archive_id,
  3457. source_3mf,
  3458. recovered.file_size,
  3459. )
  3460. if price and recovered.status == "printing":
  3461. # Print start priced it from the default rate, having no 3MF to
  3462. # estimate from; now it has one. An ended print is left alone: its
  3463. # end prices it. A print Bambuddy didn't dispatch has no start
  3464. # plate; the one the archive just read from the 3MF stands in.
  3465. _schedule_archive_cost_estimate(
  3466. printer_id,
  3467. recovered.id,
  3468. printer_manager,
  3469. ams_mapping=_get_start_ams_mapping(print_data, recovered.id),
  3470. plate_id=_get_start_plate_id(recovered.id) or recovered.plate_id,
  3471. session_factory=async_session,
  3472. )
  3473. # `archive_updated`, not `archive_created` — the row was already on the
  3474. # Archives page as an empty card and is now filled in, not new.
  3475. await ws_manager.send_archive_updated(
  3476. {
  3477. "id": recovered.id,
  3478. "printer_id": recovered.printer_id,
  3479. "filename": recovered.filename,
  3480. "print_name": recovered.print_name,
  3481. "status": recovered.status,
  3482. }
  3483. )
  3484. return True
  3485. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path, *, price: bool = True) -> bool:
  3486. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3487. Called from the paths that pull a 3MF for a print that is already under way
  3488. — chiefly the cover endpoint, which downloads the very file the archive flow
  3489. could not get and, before #2957, used it for a thumbnail and nothing else.
  3490. The bytes are already local, so this costs a parse and a row update.
  3491. No-op when the running print has a real archive, which is the common case.
  3492. """
  3493. from backend.app.models.archive import PrintArchive
  3494. logger = logging.getLogger(__name__)
  3495. # `_active_prints` is keyed on the raw names seen at print start — the
  3496. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3497. # Callers here arrive with whichever variant their own path produced, so
  3498. # match on the same normalization the download cache uses rather than on an
  3499. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3500. # endpoint find an archive registered under "Desktop_Goose".
  3501. wanted = normalize_3mf_name(name)
  3502. archive_id = None
  3503. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3504. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3505. archive_id = value
  3506. break
  3507. if archive_id is None:
  3508. return False
  3509. async with async_session() as db:
  3510. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3511. # Cheap pre-check so the common case (a normal archive) does no work.
  3512. if archive is None or archive.file_path or archive.deleted_at is not None:
  3513. return False
  3514. try:
  3515. return await _recover_fallback_archive(archive_id, path, printer_id, price=price)
  3516. except Exception as e:
  3517. # Recovery is opportunistic. A failure here must never take down the
  3518. # caller, which is usually just trying to render a thumbnail.
  3519. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3520. return False
  3521. def _schedule_fallback_3mf_retry(
  3522. printer_id: int,
  3523. archive_id: int,
  3524. filenames: list[str],
  3525. delays: tuple[float, ...] | None = None,
  3526. reason: str = REASON_FTPS_COOLOFF,
  3527. ) -> None:
  3528. """Re-attempt the 3MF download after a temporary give-up.
  3529. ``reason`` says which give-up this is, and picks the default ladder: an
  3530. FTPS cool-off has to be waited out, while a transfer that timed out under
  3531. contention is worth asking about again straight away (#3063). It is only
  3532. read for the ladder and the log line -- the retry itself is identical, since
  3533. in both cases the file is on the printer and the last attempt at it failed
  3534. for a reason that does not last.
  3535. """
  3536. logger = logging.getLogger(__name__)
  3537. if delays is None:
  3538. delays = (
  3539. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3540. if reason == REASON_FTP_TRANSFER_FAILED
  3541. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3542. )
  3543. async def _retry() -> None:
  3544. from backend.app.models.archive import PrintArchive
  3545. from backend.app.models.printer import Printer
  3546. for delay in delays:
  3547. await asyncio.sleep(delay)
  3548. async with async_session() as db:
  3549. archive = (
  3550. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3551. ).scalar_one_or_none()
  3552. if archive is None or archive.deleted_at is not None or archive.file_path:
  3553. return
  3554. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3555. if printer is None:
  3556. return
  3557. # Read the fields while the session is open rather than touching
  3558. # a detached instance minutes later, mid-download.
  3559. printer_ip = printer.ip_address
  3560. printer_code = printer.access_code
  3561. printer_model = printer.model
  3562. # Someone else may have fetched it in the meantime — the cover
  3563. # endpoint routinely does, and its copy is the same bytes.
  3564. for name in filenames:
  3565. cached = get_cached_3mf(printer_id, name)
  3566. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3567. return
  3568. if ftps_handshake_blocked(printer_ip):
  3569. logger.info(
  3570. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3571. printer_id,
  3572. archive_id,
  3573. )
  3574. continue
  3575. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3576. for candidate in filenames:
  3577. # Bare name only. These come from the print-start flow, which
  3578. # already strips the path, but the local temp write must not
  3579. # depend on that holding for every future caller — a name that
  3580. # is absolute or contains ".." would otherwise escape the data
  3581. # volume via the `/` operator.
  3582. name = Path(candidate).name
  3583. if not name or name in (".", ".."):
  3584. continue
  3585. if not name.endswith(".3mf"):
  3586. name = f"{name}.3mf"
  3587. temp_path = app_settings.archive_dir / "temp" / name
  3588. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3589. try:
  3590. hit = await download_file_try_paths_async(
  3591. printer_ip,
  3592. printer_code,
  3593. ftp_probe_paths(name),
  3594. temp_path,
  3595. socket_timeout=ftp_timeout,
  3596. printer_model=printer_model,
  3597. max_total_timeout=RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  3598. )
  3599. except Exception as e:
  3600. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3601. continue
  3602. if not hit:
  3603. continue
  3604. cache_3mf_download(printer_id, name, temp_path)
  3605. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3606. return
  3607. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3608. async def _guarded() -> None:
  3609. try:
  3610. await _retry()
  3611. except asyncio.CancelledError:
  3612. raise
  3613. except Exception as e:
  3614. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3615. finally:
  3616. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3617. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3618. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3619. if existing and not existing.done():
  3620. existing.cancel()
  3621. task = asyncio.create_task(_guarded())
  3622. _fallback_3mf_retry_tasks[printer_id] = task
  3623. logger.info(
  3624. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3625. archive_id,
  3626. reason,
  3627. printer_id,
  3628. ", ".join(f"{d:g}s" for d in delays),
  3629. )
  3630. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3631. """Whether an archive created here should ask for the print's outcome (#1898).
  3632. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3633. branches below: a queued job already has its archive and takes the
  3634. expected-print branch, where the queue item's own ``confirm_outcome``
  3635. decides. The queue is still consulted, because a restart mid-print empties
  3636. ``_expected_prints`` — without the check the setting could override a queue
  3637. item that deliberately has the flag off. Any failure answers "don't ask":
  3638. an unwanted prompt is worse than a missing one, and this must never be the
  3639. reason a print goes unarchived.
  3640. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3641. leaves one behind when a completion cannot be matched to it
  3642. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3643. only takes it back once the printer has sat connected and terminal for
  3644. minutes. Until then every screen-started print on that printer would
  3645. silently lose its prompt, so the row is held against ``observed_name`` by
  3646. the same comparison a completion uses: a positive disagreement means the row
  3647. is about some other run and this print is external after all.
  3648. """
  3649. logger = logging.getLogger(__name__)
  3650. try:
  3651. # A savepoint rather than a rollback of the caller's transaction on
  3652. # failure: a failed statement leaves the transaction unusable, but a
  3653. # full rollback also expires every object the caller has loaded (the
  3654. # printer, the archive it just created), and on an async session the
  3655. # next attribute read then raises instead of reloading. Everything here
  3656. # is a read, so undoing the savepoint loses nothing.
  3657. async with db.begin_nested():
  3658. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3659. except Exception as e:
  3660. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3661. return False
  3662. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3663. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3664. from backend.app.api.routes.settings import get_setting, setting_is_true
  3665. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3666. return False
  3667. from backend.app.models.print_queue import PrintQueueItem
  3668. dispatched_here = await db.scalar(
  3669. select(PrintQueueItem)
  3670. .where(
  3671. PrintQueueItem.printer_id == printer_id,
  3672. PrintQueueItem.status == "printing",
  3673. )
  3674. .limit(1)
  3675. )
  3676. if dispatched_here is None:
  3677. return True
  3678. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3679. observed = (observed_name or "").strip()
  3680. if not expected or not observed or _subtask_names_match(expected, observed):
  3681. logger.info(
  3682. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3683. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3684. printer_id,
  3685. dispatched_here.id,
  3686. )
  3687. return False
  3688. logger.info(
  3689. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3690. "%r; treating this as an externally started print.",
  3691. dispatched_here.id,
  3692. printer_id,
  3693. expected,
  3694. observed,
  3695. )
  3696. return True
  3697. async def _dispatch_outcome_confirmation_safely(
  3698. db,
  3699. printer_id: int,
  3700. printer_name: str,
  3701. data: dict,
  3702. archive_id: int,
  3703. archive_data: dict | None = None,
  3704. ) -> None:
  3705. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3706. The completion task sends the per-user print email on the same session
  3707. right after the prompt. A failed statement in the prompt leaves that
  3708. session needing a rollback, and without one the email step fails with
  3709. PendingRollbackError; the prompt is the optional part, so it must not be
  3710. the reason the email never goes out.
  3711. """
  3712. try:
  3713. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3714. except Exception as e:
  3715. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  3716. try:
  3717. await db.rollback()
  3718. except Exception:
  3719. pass
  3720. async def dispatch_outcome_confirmation(
  3721. db,
  3722. printer_id: int,
  3723. printer_name: str,
  3724. data: dict,
  3725. archive_id: int,
  3726. archive_data: dict | None = None,
  3727. ) -> bool:
  3728. """Emit the post-print outcome prompt for a completed archive (#1898).
  3729. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3730. queue item, or from ``confirm_outcome_external_prints`` for a print
  3731. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3732. question still open. Mints the per-archive capability token the one-tap
  3733. verdict links carry.
  3734. Lives here rather than inline in ``on_print_complete``'s notification task
  3735. because that task swallows every exception: extracted, the gate and the two
  3736. emissions can be driven by a test, which is the only thing standing between
  3737. a regression here and a farm that quietly stops asking.
  3738. Returns whether a prompt was sent.
  3739. """
  3740. logger = logging.getLogger(__name__)
  3741. from backend.app.models.archive import PrintArchive
  3742. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3743. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3744. return False
  3745. import secrets as _secrets
  3746. # A spent token stays on the row so the one-tap route can recognise it, so
  3747. # "has a token" no longer means "answerable". A prompt going out now needs a
  3748. # live one: mint a new token whenever the stored one is already spent, or
  3749. # every button in the new message would land on the already-answered page.
  3750. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  3751. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  3752. confirm_archive.confirm_token_used_at = None
  3753. await db.commit()
  3754. from backend.app.api.routes.settings import get_external_base_url, get_setting
  3755. base = await get_external_base_url(db)
  3756. if not await get_setting(db, "external_url"):
  3757. # Both the Telegram inline keyboard and the ntfy action buttons need an
  3758. # absolute URL, so an unconfigured install used to get a message body
  3759. # with two unusable relative paths and no buttons at all. The shared
  3760. # fallback at least produces tappable links; say which setting makes
  3761. # them resolve from a phone.
  3762. logger.warning(
  3763. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  3764. "Set Settings → External URL so they resolve away from this host.",
  3765. base,
  3766. )
  3767. token = confirm_archive.confirm_token
  3768. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  3769. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  3770. confirm_url = f"{base}/archives?confirm={archive_id}"
  3771. await ws_manager.send_print_confirm_request(
  3772. printer_id,
  3773. {
  3774. "archive_id": archive_id,
  3775. "print_name": confirm_archive.print_name or confirm_archive.filename,
  3776. },
  3777. )
  3778. await notification_service.on_print_confirm_request(
  3779. printer_id,
  3780. printer_name,
  3781. data,
  3782. db,
  3783. archive_data=archive_data,
  3784. good_url=good_url,
  3785. reject_url=reject_url,
  3786. confirm_url=confirm_url,
  3787. archive_id=archive_id,
  3788. )
  3789. return True
  3790. async def _printer_gone(db, printer_id: int) -> bool:
  3791. """Whether the printer was deleted. A column read: the session's loaded
  3792. Printer would otherwise answer for the database."""
  3793. from backend.app.models.printer import Printer
  3794. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  3795. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  3796. """Remove the archive just written if its printer was deleted meanwhile.
  3797. The delete route sweeps the printer's archives before it commits, so a row
  3798. committed after that sweep (the check before writing passed while the
  3799. delete was still uncommitted) is left for a printer that will never report
  3800. the print's end. A row the sweep reached is the route's: deleted with the
  3801. printer's archives, or detached (printer_id NULL) when the user kept them,
  3802. and then left as it is. Either way nothing is registered for it. Run after
  3803. the archive's commit, before anything is registered for it.
  3804. """
  3805. from backend.app.models.archive import PrintArchive
  3806. if not await _printer_gone(db, printer_id):
  3807. return False
  3808. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  3809. if owner == printer_id:
  3810. logging.getLogger(__name__).info(
  3811. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  3812. )
  3813. await ArchiveService(db).delete_archive(archive_id)
  3814. await forget_printer(printer_id)
  3815. return True
  3816. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  3817. """After an IntegrityError on a print start's archive write: whether it was
  3818. the printer being deleted, forgotten then (the caller returns).
  3819. PostgreSQL: the delete route locks the printer from its archive sweep to its
  3820. commit, so an archive written or adopted for it meanwhile (one that sets
  3821. printer_id) waits and the printer's foreign key then refuses it. That is
  3822. the printer being deleted, not an error; anything else is re-raised by the
  3823. caller.
  3824. """
  3825. await db.rollback()
  3826. if not await _printer_gone(db, printer_id):
  3827. return False
  3828. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  3829. await forget_printer(printer_id)
  3830. return True
  3831. async def _forget_if_printer_gone(printer_id: int) -> None:
  3832. """At the end of a print start: the slow steps after the last check (smart
  3833. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  3834. printer's delete and its forget_printer, and then wrote state back.
  3835. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  3836. SQLite; PostgreSQL refuses it.)
  3837. Its own session: those steps can leave the handler's needing a rollback (a
  3838. write to the archive the delete removed). Never raises: it runs inside the
  3839. fallback branch's try, whose except reports the archive as failed.
  3840. """
  3841. try:
  3842. async with async_session() as db:
  3843. gone = await _printer_gone(db, printer_id)
  3844. if gone:
  3845. await forget_printer(printer_id)
  3846. except Exception:
  3847. logging.getLogger(__name__).warning(
  3848. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  3849. )
  3850. async def _announce_plate_check_failed(printer_id: int, printer_name: str, reason: str) -> None:
  3851. """Tell the UI a plate check could not run. It does not block the print,
  3852. but an unchecked plate is not an empty one."""
  3853. try:
  3854. await ws_manager.broadcast(
  3855. {"type": "plate_check_failed", "printer_id": printer_id, "printer_name": printer_name, "reason": reason}
  3856. )
  3857. except Exception as e:
  3858. logging.getLogger(__name__).warning("[PLATE CHECK] Could not announce the failed check: %s", e)
  3859. def _expected_print_keys(printer_id: int, filename: str | None, subtask_name: str | None) -> list[tuple[int, str]]:
  3860. """The ``_expected_prints`` keys a print start may be registered under."""
  3861. keys: list[tuple[int, str]] = []
  3862. if subtask_name:
  3863. keys.append((printer_id, subtask_name))
  3864. keys.append((printer_id, f"{subtask_name}.3mf"))
  3865. keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3866. if filename:
  3867. fname = filename.split("/")[-1] if "/" in filename else filename
  3868. keys.append((printer_id, fname))
  3869. # Strip extensions to match
  3870. base = fname.replace(".gcode", "").replace(".3mf", "")
  3871. keys.append((printer_id, base))
  3872. keys.append((printer_id, f"{base}.3mf"))
  3873. return keys
  3874. async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, subtask_name: str | None) -> bool:
  3875. """Whether this print start is one Bambuddy sent to the printer."""
  3876. if any(key in _expected_prints for key in _expected_print_keys(printer_id, filename, subtask_name)):
  3877. return True
  3878. from backend.app.models.archive import PrintArchive
  3879. from backend.app.models.print_queue import PrintQueueItem
  3880. # The queue row the scheduler sets to printing before it sends -- but only
  3881. # when it was sent as this print: a row left printing by a run whose end
  3882. # was missed names another file.
  3883. dispatched_names = (
  3884. await db.execute(
  3885. select(PrintArchive.filename)
  3886. .join(PrintQueueItem, PrintQueueItem.archive_id == PrintArchive.id)
  3887. .where(PrintQueueItem.printer_id == printer_id, PrintQueueItem.status == "printing")
  3888. )
  3889. ).scalars()
  3890. observed = [name for name in (subtask_name, (filename or "").rsplit("/", 1)[-1]) if name]
  3891. return any(
  3892. _subtask_names_match(_subtask_name_from_filename(dispatched), _subtask_name_from_filename(seen))
  3893. for dispatched in dispatched_names
  3894. if dispatched
  3895. for seen in observed
  3896. )
  3897. async def on_print_start(printer_id: int, data: dict):
  3898. """Handle print start - archive the 3MF file immediately."""
  3899. logger = logging.getLogger(__name__)
  3900. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3901. try:
  3902. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  3903. except Exception:
  3904. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  3905. # Clear any stale user-stopped flag from previous print cycles
  3906. _user_stopped_printers.discard(printer_id)
  3907. _kill_switch_stopped.discard(printer_id)
  3908. # A new print starts its milestones from zero (#3211). The status path only
  3909. # resets on progress below 5 while not printing, which a printer that goes
  3910. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  3911. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  3912. # or on resume from pause, so it cannot repeat a milestone mid-print.
  3913. _last_progress_milestone[printer_id] = 0
  3914. _kill_switch_notification_tasks.pop(printer_id, None)
  3915. # #1721: drop any leftover pre-captured finish frame from a prior print
  3916. # so a never-consumed cache entry can't bleed into the new print's photo.
  3917. _stage22_finish_frames.pop(printer_id, None)
  3918. # #1867: same for the in-print frame bank — a queued print must not reuse
  3919. # the previous job's banked frame.
  3920. _inprint_frame_bank.pop(printer_id, None)
  3921. _inprint_frame_bank_ts.pop(printer_id, None)
  3922. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3923. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3924. # print's flag instead of inheriting it.
  3925. print_dispatch_context.adopt(printer_id)
  3926. # Cancel any active bed cooldown waiter for this printer
  3927. if _bed_cool_waiters.pop(printer_id, None):
  3928. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  3929. # Clear cached cover images so the new print's thumbnail is fetched fresh
  3930. from backend.app.api.routes.printers import clear_cover_cache
  3931. clear_cover_cache(printer_id)
  3932. await ws_manager.send_print_start(printer_id, data)
  3933. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  3934. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  3935. # MQTT relay - publish print start
  3936. try:
  3937. printer_info = printer_manager.get_printer(printer_id)
  3938. if printer_info:
  3939. await mqtt_relay.on_print_start(
  3940. printer_id,
  3941. printer_info.name,
  3942. printer_info.serial_number,
  3943. data.get("filename", ""),
  3944. data.get("subtask_name", ""),
  3945. )
  3946. except Exception:
  3947. pass # Don't fail print start callback if MQTT fails
  3948. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  3949. # and mapping, and the seeded tray-change log.
  3950. #
  3951. # Unconditional, for both inventory backends. This only *captures* — the
  3952. # writing is still split, with the internal tracker skipped at completion
  3953. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  3954. # carries its plate-scoped 3MF figures and stored mapping, but not the
  3955. # tray-change log, and that log is the only record of which spool fed
  3956. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  3957. # it on one side only would leave Spoolman users with the mid-print
  3958. # restart bug this fixes for everyone else.
  3959. try:
  3960. async with async_session() as db:
  3961. from backend.app.api.routes.settings import get_setting
  3962. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  3963. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3964. await usage_on_print_start(
  3965. printer_id,
  3966. data,
  3967. printer_manager,
  3968. db=db,
  3969. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  3970. )
  3971. except Exception as e:
  3972. logger.warning("Usage tracker on_print_start failed: %s", e)
  3973. # Track if notification was sent (to avoid sending twice)
  3974. notification_sent = False
  3975. # Smart plug automation: turn on plug when print starts
  3976. try:
  3977. async with async_session() as db:
  3978. await smart_plug_manager.on_print_start(printer_id, db)
  3979. except Exception as e:
  3980. logger.warning("Smart plug on_print_start failed: %s", e)
  3981. async with async_session() as db:
  3982. from backend.app.models.printer import Printer
  3983. from backend.app.services.bambu_ftp import list_files_async
  3984. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3985. printer = result.scalar_one_or_none()
  3986. # Plate detection check - pause if objects detected on build plate
  3987. logger.info(
  3988. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  3989. )
  3990. if printer and printer.plate_detection_enabled:
  3991. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  3992. # Release the pooled DB connection before the plate-detection camera
  3993. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  3994. # printer SELECT has run so far — nothing to persist — so this commit
  3995. # is a data-noop that ends the read transaction and returns the
  3996. # connection to the pool during the I/O (issue #2572). expire_on_commit
  3997. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  3998. # archive lookups below re-acquire a fresh connection on next execute.
  3999. await db.commit()
  4000. try:
  4001. from backend.app.services.plate_detection import check_plate_empty
  4002. # Build ROI tuple from printer settings if available
  4003. roi = None
  4004. if all(
  4005. [
  4006. printer.plate_detection_roi_x is not None,
  4007. printer.plate_detection_roi_y is not None,
  4008. printer.plate_detection_roi_w is not None,
  4009. printer.plate_detection_roi_h is not None,
  4010. ]
  4011. ):
  4012. roi = (
  4013. printer.plate_detection_roi_x,
  4014. printer.plate_detection_roi_y,
  4015. printer.plate_detection_roi_w,
  4016. printer.plate_detection_roi_h,
  4017. )
  4018. # Auto-turn on chamber light if it's off for better detection
  4019. light_was_off = False
  4020. client = printer_manager.get_client(printer_id)
  4021. if client and client.state:
  4022. light_was_off = not client.state.chamber_light
  4023. if light_was_off:
  4024. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  4025. client.set_chamber_light(True)
  4026. # Wait for light to physically turn on and camera to adjust exposure
  4027. await asyncio.sleep(2.5)
  4028. plate_photo_data = None
  4029. objects_detected = False
  4030. check_failure: str | None = None
  4031. try:
  4032. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  4033. plate_result = await check_plate_empty(
  4034. printer_id=printer_id,
  4035. ip_address=printer.ip_address,
  4036. access_code=printer.access_code,
  4037. model=printer.model,
  4038. include_debug_image=False,
  4039. external_camera_url=printer.external_camera_url,
  4040. external_camera_type=printer.external_camera_type,
  4041. use_external=printer.external_camera_enabled,
  4042. roi=roi,
  4043. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  4044. )
  4045. # No reference to compare against is a check that did not
  4046. # run either: say so rather than call the plate empty.
  4047. check_failure = getattr(plate_result, "failure_reason", None) or (
  4048. "not_calibrated" if plate_result.needs_calibration else None
  4049. )
  4050. objects_detected = not check_failure and not plate_result.is_empty
  4051. if objects_detected:
  4052. # Objects detected - pause the print!
  4053. logger.warning(
  4054. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  4055. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  4056. )
  4057. pause_client = printer_manager.get_client(printer_id)
  4058. if pause_client:
  4059. pause_client.pause_print()
  4060. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  4061. # Snapshot while the light's still on — restoring it first
  4062. # would leave the notification with a dark photo.
  4063. try:
  4064. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  4065. except Exception as snap_err:
  4066. logger.warning(
  4067. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  4068. )
  4069. finally:
  4070. # Restore chamber light to original state as soon as the
  4071. # camera is done with it, whatever happened above.
  4072. if light_was_off and client:
  4073. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  4074. try:
  4075. client.set_chamber_light(False)
  4076. except Exception as light_err:
  4077. logger.warning(
  4078. "[PLATE CHECK] Failed to restore chamber light for printer %s: %s",
  4079. printer_id,
  4080. light_err,
  4081. )
  4082. if objects_detected:
  4083. # Send notification about plate not empty
  4084. await ws_manager.broadcast(
  4085. {
  4086. "type": "plate_not_empty",
  4087. "printer_id": printer_id,
  4088. "printer_name": printer.name,
  4089. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  4090. }
  4091. )
  4092. # Also send push notification
  4093. try:
  4094. await notification_service.on_plate_not_empty(
  4095. printer_id=printer_id,
  4096. printer_name=printer.name,
  4097. db=db,
  4098. difference_percent=plate_result.difference_percent,
  4099. image_data=plate_photo_data,
  4100. )
  4101. except Exception as notif_err:
  4102. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4103. elif check_failure:
  4104. logger.warning(
  4105. "[PLATE CHECK] Plate check could not run for printer %s (%s): %s; proceeding with print",
  4106. printer_id,
  4107. check_failure,
  4108. plate_result.message,
  4109. )
  4110. await _announce_plate_check_failed(printer_id, printer.name, check_failure)
  4111. else:
  4112. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4113. except Exception as plate_err:
  4114. # Don't block print on plate detection errors
  4115. logger.warning(
  4116. "[PLATE CHECK] Plate check could not run for printer %s: %s; proceeding with print",
  4117. printer_id,
  4118. plate_err,
  4119. )
  4120. await _announce_plate_check_failed(printer_id, printer.name, "error")
  4121. if not printer:
  4122. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4123. if not notification_sent:
  4124. await _send_print_start_notification(printer_id, data, logger=logger)
  4125. return
  4126. # Skip the printer's own jobs — a calibration run is not a user's print.
  4127. # See is_internal_printer_job for what counts and why both fields are
  4128. # tested; the pressure-advance line reports as a subtask name with no
  4129. # /usr/ path, which the old prefix-only test here missed entirely.
  4130. #
  4131. # No notification either. The event describes the printer calibrating
  4132. # itself, so "Print started" is as wrong as the archive was, and the
  4133. # matching completion is suppressed in on_print_complete for the same
  4134. # reason. Checked before the auto-archive switches, whose "off" path
  4135. # still notifies.
  4136. # A /usr/ path is the printer's own file. A name alone is not proof: a
  4137. # print Bambuddy dispatched is never one, whatever it is called.
  4138. # Dispatched = an expected print, or, after a restart that lost those,
  4139. # a queue job printing on the printer.
  4140. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")) and (
  4141. (data.get("filename") or "").startswith("/usr/")
  4142. or not await _dispatched_by_bambuddy(db, printer_id, data.get("filename", ""), data.get("subtask_name", ""))
  4143. ):
  4144. logger.info(
  4145. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4146. data.get("filename", ""),
  4147. data.get("subtask_name", ""),
  4148. )
  4149. return
  4150. # The global switch is the master: off, no printer archives prints
  4151. # started outside Bambuddy; on, each printer's own switch decides.
  4152. from backend.app.api.routes.settings import get_setting
  4153. _global_auto_archive = await get_setting(db, "auto_archive")
  4154. archives_prints = printer.auto_archive and (
  4155. _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4156. )
  4157. if not archives_prints:
  4158. # auto-archive disabled — check if there's an expected print (dispatched
  4159. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4160. # If so, fall through to the expected-print handling below so the archive
  4161. # is tracked in _active_prints and usage tracking works at completion.
  4162. _fn = data.get("filename", "")
  4163. _sn = data.get("subtask_name", "")
  4164. _check_keys: list[tuple[int, str]] = []
  4165. if _sn:
  4166. _check_keys += [
  4167. (printer_id, _sn),
  4168. (printer_id, f"{_sn}.3mf"),
  4169. (printer_id, f"{_sn}.gcode.3mf"),
  4170. ]
  4171. if _fn:
  4172. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4173. _check_keys.append((printer_id, _base_fn))
  4174. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4175. _check_keys += [
  4176. (printer_id, _no_archive_base),
  4177. (printer_id, f"{_no_archive_base}.3mf"),
  4178. ]
  4179. _has_expected = any(k in _expected_prints for k in _check_keys)
  4180. if not _has_expected:
  4181. # No expected print — truly external print (started from slicer/touchscreen)
  4182. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4183. if not notification_sent:
  4184. _no_archive_creator: int | None = None
  4185. for _key in _check_keys:
  4186. _expected_prints.pop(_key, None)
  4187. _expected_print_registered_at.pop(_key, None)
  4188. popped_creator = _expected_print_creators.pop(_key, None)
  4189. if _no_archive_creator is None:
  4190. _no_archive_creator = popped_creator
  4191. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4192. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4193. return
  4194. else:
  4195. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4196. # Get the filename and subtask_name
  4197. filename = data.get("filename", "")
  4198. subtask_name = data.get("subtask_name", "")
  4199. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4200. # present, it lets us match an archive across a backend restart (#972):
  4201. # same id → same print → resume the existing row instead of cancelling
  4202. # it and recreating from scratch (which loses started_at). Treat "0"
  4203. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4204. raw_mqtt = data.get("raw_data") or {}
  4205. subtask_id = raw_mqtt.get("subtask_id")
  4206. if subtask_id is not None:
  4207. subtask_id = str(subtask_id).strip()
  4208. if subtask_id in ("", "0"):
  4209. subtask_id = None
  4210. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4211. if not filename and not subtask_name:
  4212. # Send notification without archive data (no filename)
  4213. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4214. if not notification_sent:
  4215. await _send_print_start_notification(printer_id, data, logger=logger)
  4216. return
  4217. # Check if this is an expected print from reprint/scheduled
  4218. expected_keys = _expected_print_keys(printer_id, filename, subtask_name)
  4219. expected_archive_id = None
  4220. for key in expected_keys:
  4221. expected_archive_id = _expected_prints.pop(key, None)
  4222. _expected_print_registered_at.pop(key, None)
  4223. if expected_archive_id:
  4224. # Clean up other possible keys for this print
  4225. for other_key in expected_keys:
  4226. _expected_prints.pop(other_key, None)
  4227. _expected_print_registered_at.pop(other_key, None)
  4228. break
  4229. if expected_archive_id:
  4230. # This is a reprint/scheduled print - use existing archive, don't create new one
  4231. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4232. # Bambuddy dispatched it: the kill switch's fast path keeps it as
  4233. # Bambuddy's once the expected entry is consumed here.
  4234. _owned_print_archive_ids.add(expected_archive_id)
  4235. from backend.app.models.archive import PrintArchive
  4236. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4237. archive = result.scalar_one_or_none()
  4238. # Deleted after this handler loaded it (the plate check waits
  4239. # seconds) but before the route forgot the expected print: the
  4240. # archive the route kept or deleted is left as the route left it.
  4241. if archive and await _printer_gone(db, printer_id):
  4242. logger.info(
  4243. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4244. )
  4245. await forget_printer(printer_id)
  4246. return
  4247. if archive:
  4248. # As it was before this adoption: put back if the printer turns
  4249. # out to have been deleted while it was adopted (below).
  4250. before_adoption = {
  4251. attr.columns[0].name: getattr(archive, attr.key)
  4252. for attr in sa_inspect(PrintArchive).column_attrs
  4253. if attr.key != "id"
  4254. }
  4255. # Update archive status to printing
  4256. archive.status = "printing"
  4257. archive.started_at = datetime.now(timezone.utc)
  4258. # The previous run's outcome is not this one's: a reprint that
  4259. # completes must not keep showing why the last one failed.
  4260. archive.failure_reason = None
  4261. archive.completed_at = None
  4262. # The previous run's answer is still on this row and the
  4263. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4264. # so without a reset the second run inherits the first run's
  4265. # verdict: no prompt at all, and a green "good" badge on a run
  4266. # nobody ever judged.
  4267. if archive.confirm_requested:
  4268. archive.user_verdict = None
  4269. archive.user_verdict_source = None
  4270. archive.user_verdict_at = None
  4271. archive.confirm_token = None
  4272. archive.confirm_token_used_at = None
  4273. # Reprint of an archive reuses the source row. Without resetting
  4274. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4275. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4276. # extracts the *original* print's last frame, which then ships in
  4277. # the completion notification (#1707). Clear the path so the
  4278. # scanner runs fresh; also unlink the old video file so reprints
  4279. # don't accumulate orphans in the archive directory. Photos list
  4280. # is left alone — accumulating one finish photo per run is fine.
  4281. # The print-start baseline (#2704) is stale for the same reason:
  4282. # it describes the printer before the previous run. The capture
  4283. # below overwrites it, but clear it here too so an early failure
  4284. # can't leave the scan diffing against the wrong snapshot.
  4285. #
  4286. # Unlinked only when it is the same plate printing again. Every
  4287. # plate of a Send All shares this archive, and the video on it
  4288. # can be the only copy of another plate's run -- the printer's
  4289. # was deleted once it attached (#3275). That one is left in the
  4290. # archive directory, which goes with the archive. A video whose
  4291. # plate is not on record (attached by hand, or before the
  4292. # column existed) is kept too where the 3MF has other plates,
  4293. # or cannot be read: nothing tells it apart from another plate's,
  4294. # and keeping costs one file where deleting can cost the only
  4295. # copy. On an archive with exactly one plate it is that plate's.
  4296. archive.timelapse_baseline = None
  4297. stale_timelapse_relpath = archive.timelapse_path
  4298. stale_timelapse_plate_id = archive.timelapse_plate_id
  4299. starting_plate_id = _print_plate_ids.get(expected_archive_id)
  4300. if stale_timelapse_relpath:
  4301. archive.timelapse_path = None
  4302. archive.timelapse_plate_id = None
  4303. stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
  4304. if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
  4305. from backend.app.services.archive import plate_indexes_in_3mf
  4306. plates = await asyncio.to_thread(
  4307. plate_indexes_in_3mf,
  4308. app_settings.base_dir / archive.file_path, # SEC-PATH-OK: stored relative archive path
  4309. )
  4310. stale_is_this_plates = len(plates) == 1
  4311. if stale_timelapse_relpath and not stale_is_this_plates:
  4312. logger.info(
  4313. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4314. stale_timelapse_relpath,
  4315. stale_timelapse_plate_id,
  4316. expected_archive_id,
  4317. starting_plate_id,
  4318. )
  4319. # The video is deleted once the adoption stands (below).
  4320. delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
  4321. # Persist a restart-stable id so a later restart resumes this
  4322. # archive by subtask_id instead of name-matching + duplicating
  4323. # it (#1485). The printer often hasn't echoed subtask_id back
  4324. # this soon after dispatch, so fall back to the id Bambuddy
  4325. # minted when it sent the print command. Scoped to this
  4326. # expected-print branch on purpose: an expected match means
  4327. # Bambuddy dispatched this exact print in this process, so the
  4328. # client's last-dispatch id genuinely belongs to it — using it
  4329. # for an externally-started print could mis-tag the archive.
  4330. effective_subtask_id = subtask_id
  4331. if not effective_subtask_id:
  4332. _client = printer_manager.get_client(printer_id)
  4333. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4334. if _dispatched:
  4335. effective_subtask_id = str(_dispatched).strip() or None
  4336. # Update on first-set OR on reprint (the queue dispatcher mints
  4337. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4338. # the rewrite for reprints leaves the archive holding the FIRST
  4339. # run's id; if MQTT then reconnects mid-print, the reconciler
  4340. # (#1542) compares the stale stored id against the printer's
  4341. # live id, sees a mismatch, and synthesises a bogus PRINT
  4342. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4343. # in #1807. Inequality check preserves the noop-on-stable-push
  4344. # behaviour the earlier `not archive.subtask_id` guard provided.
  4345. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4346. archive.subtask_id = effective_subtask_id
  4347. # #1403 follow-up: VP-queue archives are created with
  4348. # printer_id=None at queue-add time (we don't know which
  4349. # printer will run the job yet). When the print actually
  4350. # starts on a specific printer the expected-archive lookup
  4351. # used to skip this assignment, leaving printer_id=None
  4352. # forever — which then disables the "Scan for timelapse"
  4353. # button in ArchivesPage (gated on !archive.printer_id).
  4354. if archive.printer_id != printer_id:
  4355. archive.printer_id = printer_id
  4356. adopting_id = archive.id # a rollback expires the object
  4357. try:
  4358. await db.commit()
  4359. except (IntegrityError, StaleDataError):
  4360. # The archive stays unchanged, or is gone: "delete archives"
  4361. # removed the row under the adoption, which then matched no
  4362. # row (StaleDataError) rather than being refused.
  4363. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4364. return
  4365. raise
  4366. # The printer can be deleted between the check above and this
  4367. # commit (the route's transaction lasts seconds), and the commit
  4368. # then adopted the archive anyway: status, verdict and timelapse
  4369. # changed, and the deleted printer's id written on a row the
  4370. # route had detached or never touched. Undo the adoption.
  4371. if await _printer_gone(db, printer_id):
  4372. logger.info(
  4373. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4374. printer_id,
  4375. archive.id,
  4376. )
  4377. # Everything as before this adoption. The printer it had
  4378. # then stays, unless it was the deleted one: the route
  4379. # detached that row (kept) or deleted it (no row matches).
  4380. previous_printer = before_adoption["printer_id"]
  4381. await db.execute(
  4382. update(PrintArchive)
  4383. .where(PrintArchive.id == archive.id)
  4384. .values(
  4385. {
  4386. **before_adoption,
  4387. "printer_id": None if previous_printer == printer_id else previous_printer,
  4388. }
  4389. )
  4390. )
  4391. await db.commit()
  4392. await forget_printer(printer_id)
  4393. return
  4394. if delete_stale_video and stale_timelapse_relpath:
  4395. try:
  4396. stale_path = app_settings.base_dir / stale_timelapse_relpath
  4397. if stale_path.is_file():
  4398. stale_path.unlink()
  4399. logger.info(
  4400. "Deleted stale timelapse %s on reprint of archive %s",
  4401. stale_timelapse_relpath,
  4402. expected_archive_id,
  4403. )
  4404. except OSError as e:
  4405. logger.warning(
  4406. "Failed to delete stale timelapse %s on reprint: %s",
  4407. stale_timelapse_relpath,
  4408. e,
  4409. )
  4410. # Track as active print
  4411. _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
  4412. # Start timelapse session if external camera is enabled (#1353).
  4413. # Queue / VP-dispatched prints land here in the expected-archive
  4414. # branch and used to skip start_session entirely — frames were
  4415. # never captured and the post-print stitch silently returned None.
  4416. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4417. # Inject ams_mapping into usage tracker session — the session was created
  4418. # before expected-print promotion, so it may have ams_mapping=None when
  4419. # the MQTT request topic subscription failed (common on P1S/A1).
  4420. _stored_map = _print_ams_mappings.get(expected_archive_id)
  4421. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  4422. if _stored_map or _stored_plate_id is not None:
  4423. try:
  4424. from backend.app.services.usage_tracker import _active_sessions
  4425. _ut_session = _active_sessions.get(printer_id)
  4426. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4427. _ut_session.ams_mapping = _stored_map
  4428. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4429. # plate_id injection covers direct-Print of plate N of a multi-plate
  4430. # 3MF — queue prints already capture it via the on_print_start queue
  4431. # lookup, but direct-Print never goes through the queue (#1697).
  4432. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4433. _ut_session.plate_id = _stored_plate_id
  4434. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4435. except Exception:
  4436. pass
  4437. # Set up energy tracking (#941: persist start on archive row)
  4438. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4439. await ws_manager.send_archive_updated(
  4440. {
  4441. "id": archive.id,
  4442. "status": "printing",
  4443. }
  4444. )
  4445. # Send notification with archive data (reprint/scheduled)
  4446. if not notification_sent:
  4447. # Use archive's created_by_id; fall back to the creator registered via
  4448. # register_expected_print (handles library-file-based queue items where
  4449. # the freshly-created archive has no created_by_id yet).
  4450. # Pop ALL matching keys so no stale entries remain in the dict.
  4451. fallback_creator = None
  4452. for key in expected_keys:
  4453. popped = _expected_print_creators.pop(key, None)
  4454. if fallback_creator is None:
  4455. fallback_creator = popped
  4456. archive_data = {
  4457. "print_time_seconds": archive.print_time_seconds,
  4458. "created_by_id": archive.created_by_id or fallback_creator,
  4459. }
  4460. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4461. # Extract printable objects from the archived 3MF file
  4462. _load_objects_from_archive(archive, printer_id, logger)
  4463. # Store Spoolman tracking data for per-filament usage reporting
  4464. try:
  4465. await _store_spoolman_print_data(
  4466. printer_id,
  4467. archive.id,
  4468. archive.file_path,
  4469. db,
  4470. printer_manager,
  4471. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4472. plate_id=_get_start_plate_id(archive.id),
  4473. )
  4474. except Exception as e:
  4475. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4476. # Price the print from its spools now rather than only at completion (#3261)
  4477. _schedule_archive_cost_estimate(
  4478. printer_id,
  4479. archive.id,
  4480. printer_manager,
  4481. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4482. plate_id=_get_start_plate_id(archive.id),
  4483. session_factory=async_session,
  4484. )
  4485. # Capture timelapse file baseline for snapshot-diff on completion
  4486. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4487. # hit this branch — without the baseline the completion-time scan
  4488. # falls into its "take baseline now" fallback, which snapshots
  4489. # AFTER the new MP4 already exists and never matches a diff
  4490. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4491. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4492. await _forget_if_printer_gone(printer_id)
  4493. return # Skip creating a new archive
  4494. # The archive was deleted after the job was queued.
  4495. if not archives_prints:
  4496. # Only the expected print brought a printer that does not
  4497. # archive this far; with it gone, nothing is archived.
  4498. return
  4499. # Otherwise archive the print anew rather than drop it, so it still
  4500. # gets its notification, usage tracking and history.
  4501. logger.warning(
  4502. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4503. expected_archive_id,
  4504. printer_id,
  4505. )
  4506. # Check if there's already a "printing" archive for this printer/file
  4507. # This prevents duplicates when backend restarts during an active print
  4508. from backend.app.models.archive import PrintArchive
  4509. existing_archive: PrintArchive | None = None
  4510. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4511. # across a backend restart for the same print, so this is the most
  4512. # reliable way to reattach. Only a row still printing: a cancelled one
  4513. # has been through completion (usage, history, notifications) already,
  4514. # and reopening it would count the print twice.
  4515. if subtask_id:
  4516. by_id = await db.execute(
  4517. select(PrintArchive)
  4518. .where(PrintArchive.printer_id == printer_id)
  4519. .where(PrintArchive.subtask_id == subtask_id)
  4520. .where(PrintArchive.status == "printing")
  4521. .order_by(PrintArchive.created_at.desc())
  4522. .limit(1)
  4523. )
  4524. existing_archive = by_id.scalar_one_or_none()
  4525. # Fallback match: name-based lookup. Kept as-is for prints whose
  4526. # subtask_id is missing ("0" / local / non-cloud prints).
  4527. if existing_archive is None:
  4528. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4529. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4530. # A print started from the printer's screen names its file in full,
  4531. # so the forms above double its extension. The file itself is the
  4532. # one exact match, and nothing looser is added (#3009).
  4533. if _subtask_is_the_file(subtask_name, filename):
  4534. archive_filenames.append(subtask_name)
  4535. existing = await db.execute(
  4536. select(PrintArchive)
  4537. .where(PrintArchive.printer_id == printer_id)
  4538. .where(PrintArchive.status == "printing")
  4539. .where(
  4540. or_(
  4541. PrintArchive.print_name == check_name,
  4542. PrintArchive.filename.in_(archive_filenames),
  4543. )
  4544. )
  4545. .order_by(PrintArchive.created_at.desc())
  4546. .limit(1)
  4547. )
  4548. existing_archive = existing.scalar_one_or_none()
  4549. if existing_archive:
  4550. # subtask_id match → always resume, regardless of age. Same print,
  4551. # just a backend restart.
  4552. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4553. if subtask_match:
  4554. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4555. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4556. _mark_owned_if_dispatched(existing_archive)
  4557. if existing_archive.energy_start_kwh is None:
  4558. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4559. if not notification_sent:
  4560. archive_data = {
  4561. "print_time_seconds": existing_archive.print_time_seconds,
  4562. "created_by_id": existing_archive.created_by_id,
  4563. }
  4564. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4565. _load_objects_from_archive(existing_archive, printer_id, logger)
  4566. return
  4567. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4568. # stale from the printer's *current* progress, not wall-clock age.
  4569. # A genuinely long print used to trip a blind 4h cutoff and have its
  4570. # live archive cancelled + duplicated on every backend restart
  4571. # (#1485). If the printer reports real progress, this name-matched
  4572. # 'printing' archive IS that ongoing print — resume it whatever its
  4573. # age. Only treat it as a stale leftover when the printer clearly
  4574. # shows a different, freshly-started print: near-0% progress on an
  4575. # archive far too old to still be at 0%. Unknown progress (printer
  4576. # not connected) never cancels — resuming is the safe default.
  4577. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4578. live_status = printer_manager.get_status(printer_id)
  4579. live_progress = getattr(live_status, "progress", None) if live_status else None
  4580. looks_stale = (
  4581. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4582. )
  4583. # Two subtask ids are two prints, however young the archive: one
  4584. # whose completion was missed must not swallow the next print of
  4585. # the same file. Except Bambuddy's own reprint, which reuses the
  4586. # row and mints a fresh id (#1807): the id it last sent says so,
  4587. # and after a restart, which forgets it, this printer's queue job
  4588. # running the archive.
  4589. if (
  4590. not looks_stale
  4591. and subtask_id
  4592. and existing_archive.subtask_id
  4593. and existing_archive.subtask_id != subtask_id
  4594. ):
  4595. _client = printer_manager.get_client(printer_id)
  4596. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  4597. if _dispatched:
  4598. looks_stale = _dispatched != subtask_id
  4599. else:
  4600. from backend.app.models.print_queue import PrintQueueItem as _PQI
  4601. queue_run = await db.scalar(
  4602. select(_PQI.id)
  4603. .where(_PQI.archive_id == existing_archive.id)
  4604. .where(_PQI.printer_id == printer_id)
  4605. .where(_PQI.status == "printing")
  4606. .limit(1)
  4607. )
  4608. looks_stale = queue_run is None
  4609. if looks_stale:
  4610. logger.warning(
  4611. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  4612. " — marking cancelled and creating new archive",
  4613. existing_archive.id,
  4614. archive_age,
  4615. live_progress,
  4616. existing_archive.subtask_id,
  4617. subtask_id,
  4618. )
  4619. existing_archive.status = "cancelled"
  4620. # Canonical key, not a sentence (issue #2974). "No status update
  4621. # received" is what both stale paths actually observed; which of
  4622. # the two it was is already carried by ``status`` -- cancelled
  4623. # here, the reconciled outcome at the reconnect site -- so one
  4624. # key loses no information and gives the Statistics breakdown a
  4625. # single bucket instead of two untranslatable prose strings.
  4626. existing_archive.failure_reason = "noStatusUpdate"
  4627. await db.commit()
  4628. # Its print keys go with it; the new archive registers its own.
  4629. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id]:
  4630. del _active_prints[_key]
  4631. # Fall through to create new archive (don't return)
  4632. else:
  4633. logger.info(
  4634. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4635. )
  4636. # Track this as the active print
  4637. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4638. _mark_owned_if_dispatched(existing_archive)
  4639. # Attach subtask_id retroactively so future restarts can resume.
  4640. # Compare for inequality (not "is empty") to also pick up reprint
  4641. # dispatches that mint a fresh id — see #1807 for the bogus
  4642. # "Print Stopped" the strict-empty guard caused on reconnect.
  4643. if subtask_id and existing_archive.subtask_id != subtask_id:
  4644. existing_archive.subtask_id = subtask_id
  4645. await db.commit()
  4646. # Also set up energy tracking if not already tracked (#941: persisted column)
  4647. if existing_archive.energy_start_kwh is None:
  4648. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4649. # Send notification with archive data (existing archive)
  4650. if not notification_sent:
  4651. archive_data = {
  4652. "print_time_seconds": existing_archive.print_time_seconds,
  4653. "created_by_id": existing_archive.created_by_id,
  4654. }
  4655. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4656. # Extract printable objects from the archived 3MF file
  4657. _load_objects_from_archive(existing_archive, printer_id, logger)
  4658. return
  4659. # Build list of possible 3MF filenames to try
  4660. possible_names = []
  4661. # Bambu printers typically store files as "Name.gcode.3mf"
  4662. # The subtask_name is usually the best source for the filename
  4663. if subtask_name:
  4664. if _subtask_is_the_file(subtask_name, filename):
  4665. # A print started from the printer's own screen reports the
  4666. # file's full name, extension included. That is the file, so
  4667. # no extension is appended to it (#3009).
  4668. possible_names.append(subtask_name)
  4669. else:
  4670. # Try common Bambu naming patterns
  4671. possible_names.append(f"{subtask_name}.gcode.3mf")
  4672. possible_names.append(f"{subtask_name}.3mf")
  4673. # Try original filename with .3mf extension
  4674. if filename:
  4675. # Extract just the filename part, not the full path
  4676. fname = filename.split("/")[-1] if "/" in filename else filename
  4677. if fname.endswith(".3mf"):
  4678. possible_names.append(fname)
  4679. elif fname.endswith(".gcode"):
  4680. base = fname.rsplit(".", 1)[0]
  4681. possible_names.append(f"{base}.gcode.3mf")
  4682. possible_names.append(f"{base}.3mf")
  4683. else:
  4684. possible_names.append(f"{fname}.gcode.3mf")
  4685. possible_names.append(f"{fname}.3mf")
  4686. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4687. space_variants = []
  4688. for name in possible_names:
  4689. if " " in name:
  4690. space_variants.append(name.replace(" ", "_"))
  4691. possible_names.extend(space_variants)
  4692. # Remove duplicates while preserving order
  4693. seen = set()
  4694. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4695. logger.info("Trying filenames: %s", possible_names)
  4696. # Release the pooled DB connection before the 3MF FTP download. Reaching
  4697. # here means none of the expected-/existing-archive write branches ran
  4698. # (they all return earlier) — only SELECTs have executed on this path, so
  4699. # this commit persists nothing; it ends the read transaction so the
  4700. # connection returns to the pool during the download. That download tries
  4701. # up to five remote paths per candidate filename with retry/backoff and
  4702. # can run for minutes under FTP contention; holding the session across it
  4703. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  4704. # work runs during the download — the new-archive writes below re-acquire
  4705. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  4706. await db.commit()
  4707. # Try to find and download the 3MF file
  4708. temp_path = None
  4709. downloaded_filename = None
  4710. # Cache check: cover endpoint may have already pulled this 3MF during
  4711. # the print (frontend opens the card and shows the thumbnail) — reuse
  4712. # that file instead of re-downloading 36MB over the same FTP link that
  4713. # just served it (#972). The cache keys on a normalized filename so
  4714. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  4715. for try_filename in possible_names:
  4716. if not try_filename.endswith(".3mf"):
  4717. continue
  4718. cached = get_cached_3mf(printer_id, try_filename)
  4719. if cached:
  4720. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  4721. temp_path = cached
  4722. downloaded_filename = try_filename
  4723. break
  4724. # Does this printer keep the sliced file somewhere FTPS can reach? On
  4725. # H2-series and P2S the answer is routinely no — the file stays on
  4726. # internal eMMC and port 990 only ever serves external storage — and
  4727. # then the whole sweep below (six filenames x five directories x four
  4728. # retries, then the directory walk) is ~110 connections that cannot
  4729. # succeed. Skip it and say why (#2780).
  4730. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  4731. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  4732. # running rather than because the file is somewhere unreachable. The
  4733. # distinction is the whole of #2957: one is permanent, the other clears
  4734. # in minutes with the file still sitting on the printer.
  4735. blocked_by_ftps_cooloff = False
  4736. # Set when a probe reached the printer and still came back without the
  4737. # file -- a timeout mid-transfer, a refused connection, anything that is
  4738. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  4739. # caught by name below, so a file that genuinely is not on the card
  4740. # leaves this False and schedules nothing. Anything else means the
  4741. # transfer, not the file, is what failed, and that does not last (#3063).
  4742. ftp_transfer_failed = False
  4743. # The print's name, for a fallback archive whose `subtask_name` the
  4744. # plate guard below had to disown. Display only, and deliberately kept
  4745. # apart from `subtask_name`: that variable is what every file lookup
  4746. # here is built from, and once a name has been shown to fetch another
  4747. # plate's 3MF it must not key `_active_prints` either, or the cover
  4748. # endpoint hands the same contradicted file to
  4749. # `_recover_fallback_archive` and fills the row in with it (#3126).
  4750. display_name_after_plate_reject: str | None = None
  4751. # Get FTP retry settings
  4752. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  4753. # ...but "the printer put it on eMMC" is where it went, not whether we
  4754. # can read it. An H2D with a card in mirrors the job to /cache and
  4755. # serves it happily, and skipping on the URL alone cost that reporter
  4756. # every archive for two days (#2856). So ask the printer instead of
  4757. # guessing: the dispatch named the exact file, which is one connection
  4758. # walking five paths rather than the sweep's ~110. Only when the probe
  4759. # comes back empty does the verdict's reason stand.
  4760. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  4761. if ftps_handshake_blocked(printer.ip_address):
  4762. # Deliberately NOT recorded as a cool-off give-up. This branch
  4763. # only runs on an unreachable verdict, and that verdict is the
  4764. # honest, permanent reason the archive is empty — the probe was
  4765. # a long shot on top of it. Blaming the cool-off here would
  4766. # schedule a retry for a file sitting on internal eMMC, which is
  4767. # the sweep #2780 removed (#2957).
  4768. logger.debug(
  4769. "Not probing for %s on printer %s: its file service is not answering over TLS",
  4770. storage.probe_filename,
  4771. printer_id,
  4772. )
  4773. else:
  4774. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  4775. probe_path.parent.mkdir(parents=True, exist_ok=True)
  4776. try:
  4777. probe_hit = await download_file_try_paths_async(
  4778. printer.ip_address,
  4779. printer.access_code,
  4780. ftp_probe_paths(storage.probe_filename),
  4781. probe_path,
  4782. socket_timeout=ftp_timeout,
  4783. printer_model=printer.model,
  4784. )
  4785. except Exception as e:
  4786. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  4787. probe_hit = False
  4788. if probe_hit:
  4789. downloaded_filename = storage.probe_filename
  4790. temp_path = probe_path
  4791. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  4792. # Naming the path, not just the file: a printer that keeps
  4793. # uploads around for weeks can serve a same-named copy of an
  4794. # earlier slice, and without the directory in the log that
  4795. # mismatch is invisible rather than merely rare (#1820).
  4796. logger.info(
  4797. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  4798. downloaded_filename,
  4799. probe_hit,
  4800. printer_id,
  4801. storage.reason,
  4802. )
  4803. if not storage.reachable and not downloaded_filename:
  4804. # Same opening words whether or not a probe ran, because that is
  4805. # the phrase support asks people to grep for — only the tail says
  4806. # which of the two happened.
  4807. logger.info(
  4808. "Skipping the 3MF lookup for printer %s: %s — %s",
  4809. printer_id,
  4810. storage.reason,
  4811. "no copy of it on external storage either"
  4812. if storage.probe_filename
  4813. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  4814. )
  4815. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  4816. if not try_filename.endswith(".3mf"):
  4817. continue
  4818. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  4819. # printers, so try it first — deferring it to last cost #972's reporter
  4820. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  4821. # landing on the path that actually had the file.
  4822. remote_paths = [
  4823. f"/{try_filename}",
  4824. f"/cache/{try_filename}",
  4825. f"/model/{try_filename}",
  4826. f"/data/{try_filename}",
  4827. f"/data/Metadata/{try_filename}",
  4828. ]
  4829. temp_path = app_settings.archive_dir / "temp" / try_filename
  4830. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4831. for remote_path in remote_paths:
  4832. if ftps_handshake_blocked(printer.ip_address):
  4833. # The printer's FTPS service is not completing a TLS
  4834. # handshake, so it has no path we could reach — walking the
  4835. # remaining candidates only re-runs the same failure
  4836. # (#2780). Fall through to the no-3MF archive now.
  4837. #
  4838. # Remember *why*, though. This is the one give-up that is
  4839. # temporary: the cool-off clears in minutes and the file was
  4840. # on the printer the whole time. The fallback archive is
  4841. # stamped with it so a retry can be scheduled, and so the
  4842. # Archives banner stops blaming storage (#2957).
  4843. blocked_by_ftps_cooloff = True
  4844. logger.warning(
  4845. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  4846. printer_id,
  4847. )
  4848. break
  4849. logger.debug("Trying FTP download: %s", remote_path)
  4850. try:
  4851. if ftp_retry_enabled:
  4852. downloaded = await with_ftp_retry(
  4853. download_file_async,
  4854. printer.ip_address,
  4855. printer.access_code,
  4856. remote_path,
  4857. temp_path,
  4858. timeout=ftp_timeout,
  4859. socket_timeout=ftp_timeout,
  4860. printer_model=printer.model,
  4861. max_retries=ftp_retry_count,
  4862. retry_delay=ftp_retry_delay,
  4863. operation_name=f"Download 3MF from {remote_path}",
  4864. cooloff_ip=printer.ip_address,
  4865. non_retry_exceptions=(FileNotOnPrinterError,),
  4866. )
  4867. else:
  4868. downloaded = await download_file_async(
  4869. printer.ip_address,
  4870. printer.access_code,
  4871. remote_path,
  4872. temp_path,
  4873. timeout=ftp_timeout,
  4874. socket_timeout=ftp_timeout,
  4875. printer_model=printer.model,
  4876. )
  4877. if downloaded:
  4878. downloaded_filename = try_filename
  4879. logger.info("Downloaded: %s", remote_path)
  4880. # Populate shared cache so the cover endpoint (if it
  4881. # runs next) doesn't refetch the same 36MB over FTP.
  4882. cache_3mf_download(printer_id, try_filename, temp_path)
  4883. break
  4884. # with_ftp_retry returns None once it has spent its budget,
  4885. # and download_file_async returns False on a timeout, so an
  4886. # exhausted transfer arrives here rather than as an
  4887. # exception (#3063).
  4888. ftp_transfer_failed = True
  4889. except FileNotOnPrinterError:
  4890. # 550 — file isn't at this path. Advance to next candidate
  4891. # without burning the retry budget.
  4892. logger.debug("3MF not at %s (550), trying next path", remote_path)
  4893. except Exception as e:
  4894. ftp_transfer_failed = True
  4895. logger.debug("FTP download failed for %s: %s", remote_path, e)
  4896. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  4897. break
  4898. # If still not found, try listing directories to find matching file
  4899. # Different printer models use different directory structures. Skipped
  4900. # when the printer's FTPS handshake is failing — the directory walk is
  4901. # five more connections that cannot get further than the download did.
  4902. if (
  4903. not downloaded_filename
  4904. and storage.reachable
  4905. and (filename or subtask_name)
  4906. and not ftps_handshake_blocked(printer.ip_address)
  4907. ):
  4908. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  4909. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  4910. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  4911. # Every folder is listed before one file is picked, so a file named
  4912. # for the print in a later folder wins over one that merely
  4913. # contains the name in an earlier folder.
  4914. listed_paths: list[str] = []
  4915. for search_dir in search_dirs:
  4916. try:
  4917. dir_files = await list_files_async(
  4918. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  4919. )
  4920. except Exception as e:
  4921. logger.debug("Failed to list %s: %s", search_dir, e)
  4922. continue
  4923. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  4924. if threemf_files:
  4925. logger.info(
  4926. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  4927. )
  4928. listed_paths += [
  4929. posixpath.join(search_dir, f.get("name", "")) for f in dir_files if not f.get("is_directory")
  4930. ]
  4931. for remote_full_path in _3mf_files_for_print(listed_paths, search_term):
  4932. fname = posixpath.basename(remote_full_path)
  4933. logger.info("Found matching file: %s", remote_full_path)
  4934. temp_path = app_settings.archive_dir / "temp" / fname
  4935. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4936. try:
  4937. if ftp_retry_enabled:
  4938. downloaded = await with_ftp_retry(
  4939. download_file_async,
  4940. printer.ip_address,
  4941. printer.access_code,
  4942. remote_full_path,
  4943. temp_path,
  4944. timeout=ftp_timeout,
  4945. socket_timeout=ftp_timeout,
  4946. printer_model=printer.model,
  4947. max_retries=ftp_retry_count,
  4948. retry_delay=ftp_retry_delay,
  4949. operation_name=f"Download 3MF from {remote_full_path}",
  4950. cooloff_ip=printer.ip_address,
  4951. )
  4952. else:
  4953. downloaded = await download_file_async(
  4954. printer.ip_address,
  4955. printer.access_code,
  4956. remote_full_path,
  4957. temp_path,
  4958. timeout=ftp_timeout,
  4959. socket_timeout=ftp_timeout,
  4960. printer_model=printer.model,
  4961. )
  4962. except Exception as e:
  4963. logger.debug("Failed to download %s: %s", remote_full_path, e)
  4964. continue
  4965. if downloaded:
  4966. downloaded_filename = fname
  4967. logger.info("Found and downloaded: %s", remote_full_path)
  4968. cache_3mf_download(printer_id, fname, temp_path)
  4969. break
  4970. # The listing named the file, so it is on the card;
  4971. # only the transfer failed (#3063).
  4972. ftp_transfer_failed = True
  4973. # Validate the downloaded 3MF actually matches the plate that's running
  4974. # (#1204): subtask_name lags across consecutive plates of the same model,
  4975. # so the first FTP candidate (built from subtask_name) can land on the
  4976. # previous plate's still-resident upload. Cross-check the slice_info
  4977. # plate index against the plate parsed from gcode_file (always fresh —
  4978. # it's the field whose change triggered this callback).
  4979. if downloaded_filename and temp_path:
  4980. expected_plate = parse_plate_id(filename)
  4981. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  4982. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  4983. logger.warning(
  4984. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  4985. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  4986. downloaded_filename,
  4987. actual_plate,
  4988. expected_plate,
  4989. subtask_name,
  4990. )
  4991. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  4992. retry_succeeded = False
  4993. if corrected_subtask and corrected_subtask != subtask_name:
  4994. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  4995. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  4996. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  4997. for remote_path in (
  4998. f"/{try_filename}",
  4999. f"/cache/{try_filename}",
  5000. f"/model/{try_filename}",
  5001. f"/data/{try_filename}",
  5002. f"/data/Metadata/{try_filename}",
  5003. ):
  5004. try:
  5005. if ftp_retry_enabled:
  5006. downloaded = await with_ftp_retry(
  5007. download_file_async,
  5008. printer.ip_address,
  5009. printer.access_code,
  5010. remote_path,
  5011. retry_temp_path,
  5012. timeout=ftp_timeout,
  5013. socket_timeout=ftp_timeout,
  5014. printer_model=printer.model,
  5015. max_retries=ftp_retry_count,
  5016. retry_delay=ftp_retry_delay,
  5017. operation_name=f"Re-download 3MF from {remote_path}",
  5018. cooloff_ip=printer.ip_address,
  5019. non_retry_exceptions=(FileNotOnPrinterError,),
  5020. )
  5021. else:
  5022. downloaded = await download_file_async(
  5023. printer.ip_address,
  5024. printer.access_code,
  5025. remote_path,
  5026. retry_temp_path,
  5027. timeout=ftp_timeout,
  5028. socket_timeout=ftp_timeout,
  5029. printer_model=printer.model,
  5030. )
  5031. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  5032. logger.info(
  5033. "[CALLBACK] Re-download succeeded with corrected name %s "
  5034. "(plate %s) — replacing wrong file",
  5035. try_filename,
  5036. expected_plate,
  5037. )
  5038. try:
  5039. temp_path.unlink(missing_ok=True)
  5040. except OSError:
  5041. pass
  5042. temp_path = retry_temp_path
  5043. downloaded_filename = try_filename
  5044. subtask_name = corrected_subtask
  5045. cache_3mf_download(printer_id, try_filename, temp_path)
  5046. retry_succeeded = True
  5047. break
  5048. elif downloaded:
  5049. # Wrong plate again — discard and keep trying
  5050. try:
  5051. retry_temp_path.unlink(missing_ok=True)
  5052. except OSError:
  5053. pass
  5054. except FileNotOnPrinterError:
  5055. continue
  5056. except Exception as e:
  5057. logger.debug("Re-download failed for %s: %s", remote_path, e)
  5058. if retry_succeeded:
  5059. break
  5060. # If the retry didn't find a matching file, drop the wrong 3MF
  5061. # so the no-3MF fallback below creates an archive whose name
  5062. # at least reflects the right plate.
  5063. if not retry_succeeded:
  5064. logger.warning(
  5065. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  5066. expected_plate,
  5067. )
  5068. try:
  5069. temp_path.unlink(missing_ok=True)
  5070. except OSError:
  5071. pass
  5072. temp_path = None
  5073. downloaded_filename = None
  5074. # Whatever the sweep's transport did earlier, it is not why
  5075. # this archive ends up empty: a 3MF downloaded fine, it was
  5076. # just the wrong plate. Retrying would re-fetch that same
  5077. # contradicted file under the same stale names and hand it
  5078. # to _recover_fallback_archive, which checks that a
  5079. # candidate is a readable 3MF but not which plate it is --
  5080. # so the row would be filled in with another plate's
  5081. # filament and cost, the exact swap #2957 removed (#3063).
  5082. ftp_transfer_failed = False
  5083. # Disown the name for *lookups*: it has just been shown to
  5084. # fetch another plate's 3MF, and it keys `_active_prints`
  5085. # below, where the cover endpoint's own download of that
  5086. # same name would find this archive and fill it in with the
  5087. # file we are discarding here.
  5088. #
  5089. # Keep it for the *title*, which is a separate question.
  5090. # ``swap_plate_suffix`` returns None both for a name that
  5091. # carries no "- Plate N" / "_plate_N" suffix and for no
  5092. # name at all, and those are not the same situation: a name
  5093. # without a suffix holds no stale plate number to be wrong
  5094. # about. Blanking both uses at once dropped the project
  5095. # name too, and the row fell through to the gcode_file path
  5096. # titled "plate_1" though the real name was in hand.
  5097. # #1204's own premise is consecutive plates *of the same
  5098. # model*, so the project part is right either way (#3126).
  5099. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  5100. subtask_name = corrected_subtask or ""
  5101. # Deleted while the 3MF was being fetched (that can take minutes): no
  5102. # archive, timelapse or tracking for a printer that will never report
  5103. # the print's end. forget_printer again: the download registered its
  5104. # 3MF cache entry after the delete cleared the id. (A delete committing
  5105. # while the archive is written is caught after its commit.)
  5106. if await _printer_gone(db, printer_id):
  5107. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  5108. await forget_printer(printer_id)
  5109. return
  5110. if not downloaded_filename or not temp_path:
  5111. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  5112. # Create a fallback archive without 3MF data so the print is still tracked
  5113. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  5114. try:
  5115. from backend.app.models.archive import PrintArchive
  5116. # Why the card is empty. The two temporary causes outrank the
  5117. # storage verdict because they say the sweep never got a fair
  5118. # answer: a cool-off skipped it at the transport, and a failed
  5119. # transfer reached the printer but never finished. Either way
  5120. # the file is still on the card, so reporting where the printer
  5121. # files its jobs would describe a setting that is not the
  5122. # problem (#2957, #3063).
  5123. if blocked_by_ftps_cooloff:
  5124. no_3mf_reason = REASON_FTPS_COOLOFF
  5125. elif storage.reachable and ftp_transfer_failed:
  5126. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5127. else:
  5128. no_3mf_reason = storage.reason
  5129. # Derive print name from subtask_name or filename. The
  5130. # plate guard's disowned name comes second: it is a real name
  5131. # for a real print, and only the gcode_file path is left
  5132. # otherwise -- which titles the row "plate_1" (#3126).
  5133. print_name = subtask_name or display_name_after_plate_reject or filename
  5134. if print_name:
  5135. # Clean up the name (remove extensions, path parts)
  5136. print_name = print_name.split("/")[-1]
  5137. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5138. else:
  5139. print_name = "Unknown Print"
  5140. # Recover estimated print time from MQTT (best-effort for notifications)
  5141. fallback_print_time = None
  5142. mqtt_remaining = data.get("remaining_time")
  5143. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5144. fallback_print_time = int(mqtt_remaining)
  5145. if fallback_print_time is None:
  5146. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5147. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5148. fallback_print_time = int(mc_remaining * 60)
  5149. # Best-effort filament metadata from MQTT — see
  5150. # _extract_filament_data_from_mqtt. Without this the fallback
  5151. # archive's filament fields stayed NULL even though the AMS
  5152. # state at print start was sitting right there in `data`.
  5153. # The slicer's ams_mapping (when present) narrows the result
  5154. # to slots actually used by the print (#1533).
  5155. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  5156. # Create minimal archive entry
  5157. fallback_archive = PrintArchive(
  5158. printer_id=printer_id,
  5159. filename=filename or f"{print_name}.3mf",
  5160. file_path="", # Empty - no 3MF file available
  5161. file_size=0,
  5162. print_name=print_name,
  5163. print_time_seconds=fallback_print_time,
  5164. status="printing",
  5165. started_at=datetime.now(timezone.utc),
  5166. subtask_id=subtask_id,
  5167. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5168. filament_type=mqtt_filament_meta.get("filament_type"),
  5169. filament_color=mqtt_filament_meta.get("filament_color"),
  5170. extra_data={
  5171. "no_3mf_available": True,
  5172. # Why the card is empty, when we know -- see above. The
  5173. # banner reads this to stop telling H2/P2 owners to
  5174. # switch on a setting that is already on and would not
  5175. # have helped (#2780).
  5176. "no_3mf_reason": no_3mf_reason,
  5177. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5178. "_print_data": data,
  5179. },
  5180. )
  5181. db.add(fallback_archive)
  5182. try:
  5183. await db.commit()
  5184. except IntegrityError:
  5185. # Not "Failed to create fallback archive" below, and no
  5186. # start notification for a printer that is gone.
  5187. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5188. return
  5189. raise
  5190. await db.refresh(fallback_archive)
  5191. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5192. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5193. return
  5194. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5195. # Track as active print
  5196. _bind_active_print(printer_id, fallback_archive.id, fallback_archive.filename, filename, subtask_name)
  5197. # Record starting energy if smart plug available (#941: persisted column)
  5198. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5199. # Send WebSocket notification
  5200. await ws_manager.send_archive_created(
  5201. {
  5202. "id": fallback_archive.id,
  5203. "printer_id": fallback_archive.printer_id,
  5204. "filename": fallback_archive.filename,
  5205. "print_name": fallback_archive.print_name,
  5206. "status": fallback_archive.status,
  5207. }
  5208. )
  5209. # MQTT relay - publish archive created
  5210. try:
  5211. await mqtt_relay.on_archive_created(
  5212. archive_id=fallback_archive.id,
  5213. print_name=fallback_archive.print_name,
  5214. printer_name=printer.name,
  5215. status=fallback_archive.status,
  5216. )
  5217. except Exception:
  5218. pass # Don't fail if MQTT fails
  5219. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5220. try:
  5221. await _store_spoolman_print_data(
  5222. printer_id,
  5223. fallback_archive.id,
  5224. fallback_archive.file_path,
  5225. db,
  5226. printer_manager,
  5227. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  5228. plate_id=_get_start_plate_id(fallback_archive.id),
  5229. )
  5230. except Exception as e:
  5231. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5232. # Both temporary give-ups are worth coming back for, and for
  5233. # the same reason: the file is on the printer and the last look
  5234. # failed at the transport rather than finding nothing. One waits
  5235. # out the handshake block (#2957), the other waits for the
  5236. # printer to stop being busy (#3063). Deliberately not scheduled
  5237. # for a storage verdict: a file on internal eMMC will not appear
  5238. # at any FTPS path however long we wait, and retrying it is
  5239. # exactly the sweep #2780 removed.
  5240. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5241. # `possible_names`, not the raw MQTT strings: it is the exact
  5242. # list this flow just tried, already stripped of any path
  5243. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5244. # some firmware) and deduped.
  5245. _schedule_fallback_3mf_retry(
  5246. printer_id=printer_id,
  5247. archive_id=fallback_archive.id,
  5248. filenames=list(possible_names),
  5249. reason=no_3mf_reason,
  5250. )
  5251. # Send notification without archive data (file not found)
  5252. if not notification_sent:
  5253. await _send_print_start_notification(printer_id, data, logger=logger)
  5254. # The same baseline the other two on_print_start branches take
  5255. # (#2704), and last for the same reason they are: it lists the
  5256. # printer's timelapse directory, so a slow card must not delay
  5257. # the _active_prints registration, the energy reading, the
  5258. # archive-created event or the start notification above it.
  5259. #
  5260. # This branch never took one, so every no-3MF archive reached
  5261. # completion with no baseline in memory and none on the row, and
  5262. # the completion scan fell into its "snapshot now" fallback --
  5263. # which runs after the printer has written the video, so the new
  5264. # file landed inside the baseline and no diff ever matched
  5265. # (#2957 follow-up).
  5266. #
  5267. # Skipped when the FTPS cool-off is what produced this fallback:
  5268. # the listing needs the same connection that just failed, so it
  5269. # could only record that the card was unreadable. The scan
  5270. # handles that case by refusing to choose between candidates.
  5271. if not blocked_by_ftps_cooloff:
  5272. await _capture_timelapse_baseline_at_start(
  5273. printer, printer_id, logger, archive_id=fallback_archive.id
  5274. )
  5275. await _forget_if_printer_gone(printer_id)
  5276. return
  5277. except Exception as e:
  5278. logger.error("Failed to create fallback archive: %s", e)
  5279. # Send notification without archive data (file not found)
  5280. if not notification_sent:
  5281. await _send_print_start_notification(printer_id, data, logger=logger)
  5282. return
  5283. try:
  5284. # Archive the file with status "printing"
  5285. service = ArchiveService(db)
  5286. try:
  5287. archive = await service.archive_print(
  5288. printer_id=printer_id,
  5289. source_file=temp_path,
  5290. print_data={**data, "status": "printing"},
  5291. subtask_id=subtask_id,
  5292. )
  5293. except IntegrityError:
  5294. # archive_print removed the folder it had copied the 3MF into.
  5295. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5296. return
  5297. raise
  5298. if archive:
  5299. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5300. # Set on the row rather than passed to archive_print, which also
  5301. # serves the queue dispatcher — there the queue item decides.
  5302. # Guarded because this branch has no ``except``: an unhandled
  5303. # write error would take the _active_prints registration, the
  5304. # start notification, the energy reading and the timelapse
  5305. # baseline below it with it, and a missing prompt is by far the
  5306. # cheaper failure.
  5307. archive_id = archive.id
  5308. try:
  5309. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5310. archive.confirm_requested = True
  5311. await db.commit()
  5312. except Exception as e:
  5313. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5314. # The rollback expires every loaded object, and on an async
  5315. # session reading one afterwards raises instead of
  5316. # reloading, so the two this branch goes on to use are
  5317. # fetched again. The archive itself was committed by
  5318. # archive_print; only the flag is lost.
  5319. try:
  5320. await db.rollback()
  5321. archive = await db.get(PrintArchive, archive_id)
  5322. printer = await db.get(Printer, printer_id)
  5323. except Exception as reload_error:
  5324. logger.warning(
  5325. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5326. )
  5327. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5328. return
  5329. # Track this active print (use both original filename and downloaded filename)
  5330. _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
  5331. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5332. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5333. # Record starting energy from smart plug if available (#941: persisted column)
  5334. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5335. await ws_manager.send_archive_created(
  5336. {
  5337. "id": archive.id,
  5338. "printer_id": archive.printer_id,
  5339. "filename": archive.filename,
  5340. "print_name": archive.print_name,
  5341. "status": archive.status,
  5342. }
  5343. )
  5344. # MQTT relay - publish archive created
  5345. try:
  5346. await mqtt_relay.on_archive_created(
  5347. archive_id=archive.id,
  5348. print_name=archive.print_name,
  5349. printer_name=printer.name,
  5350. status=archive.status,
  5351. )
  5352. except Exception:
  5353. pass # Don't fail if MQTT fails
  5354. # Send notification with archive data (new archive created)
  5355. if not notification_sent:
  5356. archive_data = {
  5357. "print_time_seconds": archive.print_time_seconds,
  5358. "created_by_id": archive.created_by_id,
  5359. }
  5360. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5361. # Extract printable objects for skip object functionality
  5362. try:
  5363. from backend.app.services.archive import extract_printable_objects_from_3mf
  5364. client = printer_manager.get_client(printer_id)
  5365. if client:
  5366. with open(temp_path, "rb") as f:
  5367. threemf_data = f.read()
  5368. # Extract with positions for UI overlay, scoped to the
  5369. # plate that is printing — an all-plates 3MF carries
  5370. # every plate's objects (#2522).
  5371. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5372. threemf_data,
  5373. plate_number=resolve_plate_id(client.state),
  5374. include_positions=True,
  5375. )
  5376. if printable_objects:
  5377. # Store objects in printer state
  5378. client.state.printable_objects = printable_objects
  5379. client.state.printable_objects_bbox_all = bbox_all
  5380. client.state.skipped_objects = [] # Reset skipped objects for new print
  5381. logger.info(
  5382. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5383. )
  5384. except Exception as e:
  5385. logger.debug("Failed to extract printable objects: %s", e)
  5386. # Store Spoolman tracking data for per-filament usage reporting
  5387. try:
  5388. await _store_spoolman_print_data(
  5389. printer_id,
  5390. archive.id,
  5391. archive.file_path,
  5392. db,
  5393. printer_manager,
  5394. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5395. plate_id=_get_start_plate_id(archive.id),
  5396. )
  5397. except Exception as e:
  5398. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5399. # Price the print from its spools now rather than only at completion (#3261)
  5400. _schedule_archive_cost_estimate(
  5401. printer_id,
  5402. archive.id,
  5403. printer_manager,
  5404. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5405. plate_id=_get_start_plate_id(archive.id),
  5406. session_factory=async_session,
  5407. )
  5408. # Capture timelapse file baseline for snapshot-diff on completion
  5409. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5410. await _forget_if_printer_gone(printer_id)
  5411. finally:
  5412. # Keep temp_path around until print completes so the cover endpoint
  5413. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5414. # the file. If the cache entry was evicted early (file vanished),
  5415. # clean up any stragglers here to avoid leaking disk on retries.
  5416. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5417. if temp_path and temp_path.exists() and cached_now != temp_path:
  5418. temp_path.unlink()
  5419. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5420. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5421. # tests can shrink them without waiting out real delays.
  5422. #
  5423. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  5424. # looking. Across 247 support bundles the attempt that found the video was #1
  5425. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  5426. # decaying one, which is the signature of a budget that expires while files are
  5427. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  5428. # prints make big videos and the printer writes them after the print ends, so
  5429. # the poll now runs for minutes and costs one FTP LIST per round.
  5430. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  5431. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  5432. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  5433. def _timelapse_scan_max_attempts() -> int:
  5434. """Round cap for the poll, derived from the wall-clock budget.
  5435. The deadline alone is not a sufficient bound: it assumes each round really
  5436. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5437. and an FTP list that fails immediately would otherwise spin against the
  5438. printer at full speed for the whole window. Whichever bound is reached
  5439. first ends the poll.
  5440. """
  5441. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5442. # A zero interval makes the wall-clock budget meaningless; fall back to
  5443. # the round count the production interval would have given.
  5444. return 32
  5445. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5446. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  5447. """Video filenames already attached to some other archive of this printer.
  5448. Used to disambiguate when more than one file is new since the baseline —
  5449. which happens when a previous print's video landed after this print's
  5450. baseline was taken. Ordering the candidates would be the obvious fix and is
  5451. the wrong one: it can only be done on mtime or on the filename timestamp,
  5452. both of which come from the printer's own clock, and a LAN-only printer
  5453. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  5454. ``attach_timelapse`` saves the video into the archive directory under the
  5455. printer's original filename, and the later MP4 conversion keeps the stem,
  5456. so the stem of ``timelapse_path`` recovers what was claimed.
  5457. """
  5458. from backend.app.models.archive import PrintArchive
  5459. rows = await db.execute(
  5460. select(PrintArchive.timelapse_path).where(
  5461. PrintArchive.printer_id == printer_id,
  5462. PrintArchive.id != exclude_archive_id,
  5463. PrintArchive.timelapse_path.is_not(None),
  5464. )
  5465. )
  5466. return {Path(p).stem for p in rows.scalars().all() if p}
  5467. def _timelapse_listing_is_trustworthy(printer) -> bool:
  5468. """Whether an *empty* timelapse listing for *printer* can be believed.
  5469. ``list_files_async`` answers ``[]`` when its connect fails rather than
  5470. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  5471. from one holding no videos. Everywhere that only wants to know "is there a
  5472. video yet" the difference does not matter — both mean "not yet, retry".
  5473. It matters where an empty listing is recorded as a *baseline*. Recording
  5474. "the card held nothing" for a card that was never read means every video on
  5475. it counts as new once the cool-off expires, and the completion scan then
  5476. attaches a stale video to this print and deletes it from the printer
  5477. (#2957 follow-up). Those two callers ask this first.
  5478. """
  5479. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  5480. ip_address = getattr(printer, "ip_address", None)
  5481. if not ip_address:
  5482. return True
  5483. return not ftps_handshake_blocked(ip_address)
  5484. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5485. """List video files from printer's timelapse directory.
  5486. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5487. Returns (video_files, found_path) where video_files is a list of file dicts
  5488. and found_path is the directory where they were found, or ([], None).
  5489. An empty return does not distinguish "no videos" from "could not read the
  5490. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  5491. baseline callers consult before believing one.
  5492. """
  5493. from backend.app.services.bambu_ftp import list_files_async
  5494. logger = logging.getLogger(__name__)
  5495. # No card in the slot means no /timelapse to walk — four connections that
  5496. # can only fail, on a path whose failures are swallowed and so would go on
  5497. # costing time silently forever (#2780).
  5498. #
  5499. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5500. # inside the loop's own try/except, so a caller that passed something
  5501. # unexpected used to get an empty listing rather than an exception. Keep
  5502. # that, instead of making this gate the first thing that can raise here.
  5503. printer_id = getattr(printer, "id", None)
  5504. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5505. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5506. return [], None
  5507. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  5508. try:
  5509. found_files = await list_files_async(
  5510. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5511. )
  5512. if found_files:
  5513. video_files = [
  5514. f
  5515. for f in found_files
  5516. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5517. ]
  5518. if video_files:
  5519. return video_files, timelapse_path
  5520. except Exception as e:
  5521. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5522. continue
  5523. return [], None
  5524. async def _capture_timelapse_baseline_at_start(
  5525. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5526. ) -> None:
  5527. """Snapshot the printer's timelapse directory at print start so the
  5528. completion-time scan can pick the new file by set-difference.
  5529. Must be called from every on_print_start path that proceeds to a real
  5530. print — both the new-archive branch and the expected-archive branch (which
  5531. queue / VP-dispatched prints take). Without a baseline,
  5532. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5533. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5534. so the new file ends up in the "baseline" set and no diff ever matches.
  5535. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  5536. unreliable — the snapshot-diff approach sidesteps that entirely.
  5537. When ``archive_id`` is known the baseline is also written to the archive
  5538. row, so it survives a restart and the manual "Scan for Timelapse" button
  5539. can run the same diff instead of falling back to clock-based matching
  5540. (#2704). Only baselines taken at print start are persisted — one taken at
  5541. completion already contains the new video and would poison a later scan.
  5542. """
  5543. names: set[str] | None = None
  5544. try:
  5545. if not _timelapse_listing_is_trustworthy(printer):
  5546. # Recorded anyway, deliberately. An empty baseline taken off a card
  5547. # we could not read is not authoritative, but it is still the right
  5548. # *default*: Bambuddy deletes each video from the printer once it is
  5549. # attached, so the usual card holds exactly one video at completion
  5550. # and an empty baseline resolves it correctly. Persisting NULL
  5551. # instead would send completion to take its own snapshot, by which
  5552. # point this print's video is on the card and would be swallowed by
  5553. # it. The ambiguity is handled where it actually bites — see
  5554. # ``require_unambiguous`` in the scan (#2957 follow-up).
  5555. logger.warning(
  5556. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  5557. "handshake cool-off, so the card could not be read — treating it as empty",
  5558. printer_id,
  5559. )
  5560. baseline_files, _ = await _list_timelapse_videos(printer)
  5561. names = {f.get("name", "") for f in baseline_files}
  5562. _timelapse_baselines[printer_id] = names
  5563. logger.info(
  5564. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  5565. len(names),
  5566. printer_id,
  5567. )
  5568. except Exception as e:
  5569. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  5570. if archive_id is None:
  5571. return
  5572. try:
  5573. async with async_session() as db:
  5574. from backend.app.models.archive import PrintArchive
  5575. archive = await db.get(PrintArchive, archive_id)
  5576. if archive is not None:
  5577. # Written even when the listing failed, and then as NULL. A
  5578. # reprint reuses the archive row, so leaving the previous run's
  5579. # baseline in place would have the scan diff this print against
  5580. # the state of the printer before the *last* one — and a stale
  5581. # baseline reads as authoritative, where NULL correctly falls
  5582. # back to a fresh snapshot.
  5583. archive.timelapse_baseline = sorted(names) if names is not None else None
  5584. await db.commit()
  5585. except Exception as e:
  5586. # In-memory baseline still covers the normal completion path.
  5587. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  5588. async def _scan_for_timelapse_with_retries(
  5589. archive_id: int, baseline_names: set[str] | None = None, *, plate_id: int | None = None
  5590. ):
  5591. """Poll the printer for this print's timelapse and attach it.
  5592. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  5593. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  5594. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  5595. (#2704). Comparing the current listing against the set of filenames that
  5596. existed when the print started needs no clock at all, because the printer
  5597. writes the video only once the print has ended.
  5598. Baseline precedence: the caller's in-memory set, then the one persisted on
  5599. the archive at print start, then a snapshot taken now. The last of those is
  5600. a poor substitute — by completion the new video may already be on the card,
  5601. in which case it lands in the "baseline" and no diff can ever match — but it
  5602. is all that is available for a print that began before Bambuddy started.
  5603. On success the video is deleted from the printer, which keeps ``/timelapse``
  5604. down to the unclaimed files and makes the next diff unambiguous.
  5605. """
  5606. logger = logging.getLogger(__name__)
  5607. # Cleared when the baseline had to be taken off a card we could not read, so
  5608. # the attach step refuses to choose between several candidates (#2957).
  5609. baseline_trusted = True
  5610. # --- Phase 1: establish the baseline -------------------------------------
  5611. try:
  5612. async with async_session() as db:
  5613. from backend.app.models.printer import Printer
  5614. service = ArchiveService(db)
  5615. archive = await service.get_archive(archive_id)
  5616. if not archive:
  5617. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  5618. return
  5619. if archive.timelapse_path:
  5620. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  5621. return
  5622. if not archive.printer_id:
  5623. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  5624. return
  5625. if baseline_names is not None:
  5626. logger.info(
  5627. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  5628. len(baseline_names),
  5629. archive_id,
  5630. )
  5631. elif archive.timelapse_baseline is not None:
  5632. # Persisted at print start — survives a restart mid-print.
  5633. baseline_names = set(archive.timelapse_baseline)
  5634. logger.info(
  5635. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  5636. len(baseline_names),
  5637. archive_id,
  5638. )
  5639. else:
  5640. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5641. printer = result.scalar_one_or_none()
  5642. if not printer:
  5643. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  5644. return
  5645. if not _timelapse_listing_is_trustworthy(printer):
  5646. # The card is unreadable at the one moment a baseline has to
  5647. # be taken, so the empty listing below means "we never
  5648. # looked", not "these are all new". Carry on with it anyway
  5649. # — the usual card holds exactly one video, which resolves
  5650. # correctly — but stop the poll from *choosing* between
  5651. # several, which is how a stale video got attached to this
  5652. # print and then deleted off the printer (#2957 follow-up).
  5653. baseline_trusted = False
  5654. logger.warning(
  5655. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  5656. "handshake cool-off. A single new video still resolves; several will not be "
  5657. "guessed between — use Scan for Timelapse to pick one by hand",
  5658. archive_id,
  5659. archive.printer_id,
  5660. )
  5661. baseline_files, _ = await _list_timelapse_videos(printer)
  5662. baseline_names = {f.get("name", "") for f in baseline_files}
  5663. logger.info(
  5664. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  5665. len(baseline_names),
  5666. archive_id,
  5667. )
  5668. except Exception as e:
  5669. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  5670. return
  5671. # --- Phase 2: poll for a file that was not there when the print began -----
  5672. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  5673. max_attempts = _timelapse_scan_max_attempts()
  5674. seen_names: set[str] = set()
  5675. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  5676. attempt = 0
  5677. while True:
  5678. await asyncio.sleep(delay)
  5679. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  5680. attempt += 1
  5681. try:
  5682. from backend.app.models.printer import Printer
  5683. # Read phase: fetch archive + printer in a short session and release
  5684. # the pooled connection BEFORE the FTP list/download below. Holding it
  5685. # across the FTP round-trips left one connection idle-in-transaction per
  5686. # in-flight scan (issue #2572).
  5687. async with async_session() as db:
  5688. service = ArchiveService(db)
  5689. archive = await service.get_archive(archive_id)
  5690. if not archive:
  5691. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  5692. return
  5693. if archive.timelapse_path:
  5694. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  5695. return
  5696. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5697. printer = result.scalar_one_or_none()
  5698. if not printer:
  5699. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  5700. return
  5701. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  5702. # I/O phase (no DB connection held): FTP list + download.
  5703. video_files, found_path = await _list_timelapse_videos(printer)
  5704. # The poll can run for dozens of rounds, so only narrate a round
  5705. # that saw something change. Repeating the whole listing every 30 s
  5706. # would bury the one interesting line in the support bundle.
  5707. names_now = {f.get("name", "") for f in video_files}
  5708. changed = attempt == 1 or names_now != seen_names
  5709. seen_names = names_now
  5710. speak = logger.info if changed else logger.debug
  5711. if video_files:
  5712. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  5713. if changed:
  5714. for f in video_files[:5]:
  5715. logger.info("[TIMELAPSE] - %s", f.get("name"))
  5716. attached = await _attach_first_unclaimed_timelapse(
  5717. archive_id,
  5718. printer,
  5719. video_files,
  5720. baseline_names,
  5721. claimed,
  5722. attempt,
  5723. logger,
  5724. quiet=not changed,
  5725. require_unambiguous=not baseline_trusted,
  5726. plate_id=plate_id,
  5727. )
  5728. if attached:
  5729. return
  5730. else:
  5731. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  5732. except Exception as e:
  5733. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  5734. if attempt >= max_attempts or time.monotonic() >= deadline:
  5735. break
  5736. # No name-match fallback: it compared the print name against the filename,
  5737. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  5738. # bundles it fired 159 times and matched zero times, so all it added was a
  5739. # misleading log line before giving up.
  5740. logger.warning(
  5741. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  5742. archive_id,
  5743. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  5744. )
  5745. async def _attach_first_unclaimed_timelapse(
  5746. archive_id: int,
  5747. printer,
  5748. video_files: list[dict],
  5749. baseline_names: set[str],
  5750. claimed: set[str],
  5751. attempt: int,
  5752. logger: logging.Logger,
  5753. *,
  5754. quiet: bool = False,
  5755. require_unambiguous: bool = False,
  5756. plate_id: int | None = None,
  5757. ) -> bool:
  5758. """Download and attach the one video that belongs to this print.
  5759. A candidate is any file absent from the print-start baseline. More than one
  5760. can qualify when a previous print's video landed late, after this print's
  5761. baseline was taken — those are filtered out by name, because they are
  5762. already attached to another archive. Sorting the candidates instead would
  5763. mean sorting on mtime or on the filename timestamp, both of which come from
  5764. the printer's unsynced clock.
  5765. Returns True once a video is attached. The printer's copy is deleted only
  5766. after the attach succeeds on bytes whose length matched the listing.
  5767. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  5768. already seen this exact listing — the poll runs for many rounds and only the
  5769. rounds where something changed are worth an INFO line.
  5770. """
  5771. from backend.app.services.bambu_ftp import (
  5772. DownloadDeadlineExceeded,
  5773. delete_archived_timelapse,
  5774. download_file_bytes_async,
  5775. remote_file_settled,
  5776. )
  5777. speak = logger.debug if quiet else logger.info
  5778. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  5779. if not new_files:
  5780. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  5781. return False
  5782. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  5783. if not candidates:
  5784. speak(
  5785. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  5786. attempt,
  5787. len(new_files),
  5788. )
  5789. return False
  5790. if len(candidates) > 1:
  5791. if require_unambiguous:
  5792. # The baseline is not evidence -- it was taken off a card that could
  5793. # not be read -- so "new since the baseline" does not narrow these
  5794. # down at all. Taking the first would attach an arbitrary video to
  5795. # this print and then delete it from the printer.
  5796. logger.warning(
  5797. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  5798. "leaving all of them on the printer for manual selection",
  5799. attempt,
  5800. len(candidates),
  5801. ", ".join(str(f.get("name")) for f in candidates),
  5802. )
  5803. return False
  5804. logger.warning(
  5805. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  5806. "the rest stay on the printer for manual selection",
  5807. attempt,
  5808. len(candidates),
  5809. ", ".join(str(f.get("name")) for f in candidates),
  5810. )
  5811. target = candidates[0]
  5812. file_name = target.get("name")
  5813. remote_path = target.get("path") or f"/timelapse/{file_name}"
  5814. logger.info(
  5815. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  5816. attempt,
  5817. file_name,
  5818. archive_id,
  5819. )
  5820. # The listing always carries a size (`list_files` skips entries it can't
  5821. # parse), but read it explicitly: the delete below is destructive and must
  5822. # depend on a size we actually had, not on one we hoped was there.
  5823. expected_size = target.get("size")
  5824. try:
  5825. timelapse_data = await download_file_bytes_async(
  5826. printer.ip_address,
  5827. printer.access_code,
  5828. remote_path,
  5829. printer_model=printer.model,
  5830. expected_size=expected_size,
  5831. )
  5832. except DownloadDeadlineExceeded:
  5833. # Too slow for its size this round; the printer keeps its copy.
  5834. timelapse_data = None
  5835. if not timelapse_data:
  5836. # Short or failed transfer. The printer keeps its copy, so the next
  5837. # round can try again — which is exactly why the delete below is
  5838. # gated on a verified download.
  5839. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  5840. return False
  5841. # The length check above proves we got what the listing said, not that the
  5842. # printer had finished writing. A video still being written can be listed
  5843. # short, served short, and pass — so confirm it has stopped growing before
  5844. # committing to it and deleting the original (#2704).
  5845. if not await remote_file_settled(
  5846. printer.ip_address,
  5847. printer.access_code,
  5848. remote_path,
  5849. len(timelapse_data),
  5850. printer_model=printer.model,
  5851. ):
  5852. return False
  5853. # Write phase: attach in a fresh short-lived session.
  5854. async with async_session() as db:
  5855. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name, plate_id=plate_id)
  5856. if not success:
  5857. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  5858. return False
  5859. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  5860. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  5861. await delete_archived_timelapse(
  5862. printer.ip_address,
  5863. printer.access_code,
  5864. remote_path,
  5865. verified=expected_size is not None,
  5866. printer_model=printer.model,
  5867. printer_name=printer.name,
  5868. )
  5869. return True
  5870. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  5871. # module-level so tests can monkeypatch them down to ~0 without timing out.
  5872. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  5873. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  5874. # How long the *background* upgrade keeps waiting after the notification has
  5875. # already gone out (#2704 follow-up). The short bound above exists so a slow
  5876. # printer can't hold up the print-complete notification; this one exists so the
  5877. # archive still ends up with the better frame afterwards.
  5878. #
  5879. # Measured across 261 attaches in the support bundles, the video lands a median
  5880. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  5881. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  5882. # was 546s. Every other model was inside 26s. The long budget is therefore
  5883. # almost entirely for P1-series users; on everything else the short wait already
  5884. # wins and this task never runs.
  5885. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  5886. async def _capture_finish_photo_from_timelapse(
  5887. archive_id: int,
  5888. archive_dir: Path,
  5889. timeout: float | None = None,
  5890. rotation: int = 0,
  5891. ) -> tuple[str | None, bool]:
  5892. """Wait for the per-print timelapse to land on the archive and extract its
  5893. last frame as the finish photo (#1397).
  5894. Bambu firmware stops timelapse recording after the toolhead parks but
  5895. before the bed-drop end-gcode runs, so the last frame frames the finished
  5896. print correctly. A live camera grab at gcode_state=FINISH captures the
  5897. bed already lowered.
  5898. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  5899. ``archive.timelapse_path`` when the file lands. This function polls for
  5900. that field.
  5901. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  5902. the wait ran out with no video on the archive yet — i.e. the video may
  5903. still be coming and a later attempt could succeed. It is False when the
  5904. video landed (whether or not extraction worked), because in that case
  5905. waiting longer changes nothing. The caller uses that to decide between
  5906. falling back permanently and scheduling a background upgrade.
  5907. ``rotation`` is the printer's camera_rotation, applied to the extracted
  5908. still (#2708) so this source agrees with every other finish-photo source.
  5909. The archived video itself is the printer's own file and is left alone —
  5910. rotating it would mean re-encoding it.
  5911. """
  5912. import uuid
  5913. from backend.app.models.archive import PrintArchive
  5914. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  5915. logger = logging.getLogger(__name__)
  5916. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  5917. deadline = asyncio.get_event_loop().time() + budget
  5918. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  5919. while True:
  5920. async with async_session() as db:
  5921. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5922. archive = result.scalar_one_or_none()
  5923. timelapse_relpath = archive.timelapse_path if archive else None
  5924. if timelapse_relpath:
  5925. video_path = app_settings.base_dir / timelapse_relpath
  5926. if video_path.exists() and video_path.stat().st_size > 0:
  5927. photos_dir = archive_dir / "photos"
  5928. photos_dir.mkdir(parents=True, exist_ok=True)
  5929. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5930. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5931. output_path = photos_dir / filename
  5932. if await extract_video_last_frame(video_path, output_path):
  5933. await apply_camera_rotation_to_file(output_path, rotation, logger)
  5934. logger.info(
  5935. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  5936. video_path.name,
  5937. archive_id,
  5938. )
  5939. return filename, False
  5940. logger.warning(
  5941. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  5942. video_path.name,
  5943. archive_id,
  5944. )
  5945. return None, False
  5946. if asyncio.get_event_loop().time() >= deadline:
  5947. logger.info(
  5948. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  5949. archive_id,
  5950. budget,
  5951. )
  5952. return None, True
  5953. await asyncio.sleep(poll_interval)
  5954. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  5955. """Add the timelapse's last frame to an archive after the fact (#2704).
  5956. The print-complete notification waits only ~60s for the video, because
  5957. holding a notification for minutes is worse than sending it with a live
  5958. camera grab. On a P1-series printer the video often lands well after that,
  5959. so the archive used to be stuck with the live grab — which is taken at
  5960. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  5961. the worse photo of the two.
  5962. This keeps waiting in the background and, when the video arrives, extracts
  5963. the frame and puts it *first* in the archive's photo list, so opening the
  5964. gallery shows it. The live grab is deliberately kept: the notification that
  5965. already went out links to that exact file, and deleting it would leave a
  5966. broken image in Discord or Telegram.
  5967. """
  5968. logger = logging.getLogger(__name__)
  5969. filename, _ = await _capture_finish_photo_from_timelapse(
  5970. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  5971. )
  5972. if not filename:
  5973. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  5974. return
  5975. try:
  5976. async with async_session() as db:
  5977. from backend.app.models.archive import PrintArchive
  5978. archive = await db.get(PrintArchive, archive_id)
  5979. if archive is None:
  5980. return
  5981. photos = list(archive.photos or [])
  5982. if filename in photos:
  5983. return
  5984. # Front of the list: PhotoGalleryModal opens at index 0.
  5985. archive.photos = [filename, *photos]
  5986. await db.commit()
  5987. except Exception as e:
  5988. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  5989. return
  5990. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  5991. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  5992. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  5993. """Put the filament-attribution context back after a restart mid-print.
  5994. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  5995. both die with the process. The print keeps running, so at completion the
  5996. tracker would fall back to whatever the printer reports *now* — and AMS
  5997. filament backup makes "now" the substitute tray, charging the whole print
  5998. to the spool that only finished it.
  5999. The persisted row is only trusted when its print name still matches what
  6000. the printer says it is running: a row left behind by a completion we never
  6001. saw must not attach itself to the next print.
  6002. """
  6003. try:
  6004. from backend.app.api.routes.settings import get_setting
  6005. from backend.app.services.usage_tracker import (
  6006. clear_persisted_session,
  6007. get_persisted_print_name,
  6008. restore_session,
  6009. )
  6010. persisted_name = await get_persisted_print_name(db, printer_id)
  6011. current_name = (state.subtask_name or "").strip()
  6012. if persisted_name and current_name and persisted_name.strip() != current_name:
  6013. logger.info(
  6014. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  6015. printer_id,
  6016. persisted_name,
  6017. current_name,
  6018. )
  6019. await clear_persisted_session(db, printer_id)
  6020. # Fall through to seeding: the print on the printer is real, it just
  6021. # isn't the one the row described.
  6022. persisted_log = None
  6023. else:
  6024. # Spoolman users get the tray-change log back but no in-memory
  6025. # session — see ``on_print_start`` on why that dict is load-bearing
  6026. # for the remain%-sync guard.
  6027. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6028. persisted_log = await restore_session(
  6029. db,
  6030. printer_id,
  6031. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  6032. )
  6033. if persisted_log:
  6034. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  6035. # Anything this process already observed goes after the persisted
  6036. # history — the log is ordered by layer, and a fresh process can
  6037. # only have seen changes from later in the print.
  6038. for entry in state.tray_change_log or []:
  6039. if tuple(entry) not in restored:
  6040. restored.append(tuple(entry))
  6041. state.tray_change_log = restored
  6042. tray_now = state.tray_now
  6043. if 0 <= tray_now <= 254:
  6044. if not state.tray_change_log:
  6045. # No persisted history — a print that started before this build,
  6046. # or before the row existed. Seed with the tray feeding right
  6047. # now so the remainder of the print is at least attributable to
  6048. # the right spool.
  6049. state.tray_change_log = [(tray_now, state.layer_num)]
  6050. logger.info(
  6051. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  6052. printer_id,
  6053. tray_now,
  6054. state.layer_num,
  6055. )
  6056. # The tray handler updates ``last_loaded_tray`` on every push
  6057. # regardless of whether it logged a change, so re-align it to avoid
  6058. # a duplicate entry on the next push. Only ever with a real tray:
  6059. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  6060. # 255" fallback, and writing 255 into it would defeat that.
  6061. state.last_loaded_tray = tray_now
  6062. except Exception:
  6063. # Never let attribution recovery cost the caller its timelapse
  6064. # baseline — that capture has to happen before the printer uploads
  6065. # the in-flight MP4 and there is no second chance at it.
  6066. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  6067. async def on_print_running_observed(printer_id: int, data: dict):
  6068. """Restart-recovery for a print that started before Bambuddy came up.
  6069. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  6070. after Bambuddy startup (#1304 guard, prevents duplicate archive
  6071. creation). This hook restores the persisted archive into ``_active_prints``
  6072. and captures the timelapse baseline that normally hangs off print start.
  6073. Fires once per session, in lieu of on_print_start when restart-recovery
  6074. kicks in. The printer doesn't upload the timelapse until after PRINT
  6075. COMPLETE, so a baseline captured any time during the print is still
  6076. pre-upload.
  6077. """
  6078. logger = logging.getLogger(__name__)
  6079. async with async_session() as db:
  6080. from backend.app.models.printer import Printer
  6081. state = printer_manager.get_status(printer_id)
  6082. if state is not None:
  6083. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  6084. if authorization is True:
  6085. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  6086. await _restore_usage_tracking_session(printer_id, state, db, logger)
  6087. await _restore_printable_objects(printer_id, state, db, logger)
  6088. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6089. printer = result.scalar_one_or_none()
  6090. if not printer:
  6091. logger.warning(
  6092. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  6093. printer_id,
  6094. )
  6095. return
  6096. # Avoid double-capture: ownership reconciliation above must still run when
  6097. # a baseline already exists, but the camera work itself is one-shot.
  6098. if printer_id in _timelapse_baselines:
  6099. logger.debug(
  6100. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  6101. printer_id,
  6102. )
  6103. return
  6104. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  6105. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  6106. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  6107. against the printer's current MQTT state.
  6108. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  6109. COMPLETE events, typically a print finishing during an MQTT disconnect
  6110. window followed by a smart-plug power cycle):
  6111. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  6112. provably not running anymore — only branch that should fire under
  6113. normal disconnect-then-reconnect timing.
  6114. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  6115. firmware mints a fresh ``subtask_id`` for each print, including the
  6116. ghost replay it runs after a power cycle from a leftover SD file —
  6117. so a mismatch unambiguously means the in-DB archive is no longer
  6118. the print on the printer.
  6119. 3. Printer is running but ``subtask_name`` is empty. The printer
  6120. doesn't know what it's running; the archive's reference to it is
  6121. already broken.
  6122. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  6123. with matching subtask_id+subtask_name is left alone. The cost of a false
  6124. positive is a duplicate archive on the next real PRINT COMPLETE — the
  6125. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  6126. clears on synthesis, so the real completion creates a fresh row instead
  6127. of overwriting the synthesised one (#1679). The cost of a false negative
  6128. is the ghost-print loop in #1542.
  6129. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  6130. MQTT has connected but the first ``push_status`` response hasn't been
  6131. applied yet — ``PrinterState`` is sitting on its construction defaults.
  6132. The reconcile caller in ``on_printer_status_change`` is already gated
  6133. on a real ``state.state``, so in normal operation this branch is
  6134. unreachable; it's kept as belt-and-braces for future callers and for
  6135. the narrow window where a partial state update could arrive
  6136. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  6137. ``not stale`` on degenerate input is strictly conservative: a real
  6138. stale archive will still be caught by the next push_status arriving
  6139. with terminal state.
  6140. """
  6141. current_state = (state.state or "").upper()
  6142. if current_state in ("", "UNKNOWN"):
  6143. # No real push_status yet — PrinterState defaults are not evidence.
  6144. return False, ""
  6145. if current_state in ("IDLE", "FINISH", "FAILED"):
  6146. return True, f"printer state {current_state}"
  6147. # Below here the printer is in a running / pre-running state (RUNNING /
  6148. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  6149. current_subtask_id = (state.subtask_id or "").strip()
  6150. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  6151. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  6152. current_subtask_name = (state.subtask_name or "").strip()
  6153. if not current_subtask_name:
  6154. return True, "printer subtask_name empty"
  6155. return False, ""
  6156. async def prime_kprofile_table(printer_id: int) -> int:
  6157. """Read the printer's calibration table once per connection.
  6158. The AMS slot card shows a K value per slot (#2854). On the printers whose
  6159. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  6160. report ``cali_idx`` and nothing else -- that number can only come from
  6161. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  6162. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  6163. backup, or the printer answering a query BambuStudio made on the report
  6164. topic we share. A Bambuddy that nobody visited showed a card with no K
  6165. values at all.
  6166. Only the diameters actually fitted are asked for, which is one request on a
  6167. single-nozzle printer and two on a dual. Probing the four sizes blind is
  6168. what the backup does, and it is both wasteful and the thing that used to
  6169. blank the table.
  6170. Returns the number of nozzles whose table was read.
  6171. """
  6172. client = printer_manager.get_client(printer_id)
  6173. state = printer_manager.get_status(printer_id)
  6174. if client is None or state is None or not state.connected:
  6175. return 0
  6176. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  6177. # ask once, and both entries are empty until the first push_status lands.
  6178. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  6179. if not diameters:
  6180. logging.getLogger(__name__).debug(
  6181. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  6182. printer_id,
  6183. )
  6184. return 0
  6185. primed = 0
  6186. for diameter in diameters:
  6187. try:
  6188. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  6189. except Exception as exc: # noqa: BLE001
  6190. # A printer that won't answer costs the card its K values, nothing
  6191. # more — never the connection this runs on the back of.
  6192. logging.getLogger(__name__).warning(
  6193. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  6194. )
  6195. continue
  6196. primed += 1
  6197. logging.getLogger(__name__).info(
  6198. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  6199. )
  6200. return primed
  6201. def _sd_files_in_use(state) -> set[str]:
  6202. """Names of the SD-card files the printer may be printing right now (#3009).
  6203. The post-print cleanup works out what to delete from the finished archive,
  6204. not from the printer. When reconciliation closes an old archive because the
  6205. printer has moved on to a new job, and that job is the same file reprinted
  6206. from the printer's screen, the cleanup would delete the file mid-print.
  6207. Empty unless the printer is busy: on an ordinary completion the state is
  6208. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  6209. name, a path or a URL depending on firmware, and some report only the
  6210. plate's G-code, so the job name is matched as well, in the same spellings
  6211. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  6212. ignores case.
  6213. """
  6214. def _text(value) -> str:
  6215. return value.strip() if isinstance(value, str) else ""
  6216. if state is None:
  6217. return set()
  6218. current_state = _text(getattr(state, "state", None)).upper()
  6219. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  6220. return set()
  6221. in_use: set[str] = set()
  6222. gcode_file = _text(getattr(state, "gcode_file", None))
  6223. if gcode_file:
  6224. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  6225. # both legal in a file name, and raises on some inputs.
  6226. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  6227. if name:
  6228. in_use.add(name.lower())
  6229. subtask_name = _text(getattr(state, "subtask_name", None))
  6230. if subtask_name:
  6231. for name in (subtask_name, subtask_name.replace(" ", "_")):
  6232. for ext in (".3mf", ".gcode"):
  6233. in_use.add(f"{name}{ext}".lower())
  6234. return in_use
  6235. async def reconcile_stale_active_prints(printer_id: int) -> int:
  6236. """Synthesise ``on_print_complete`` for archives whose print can't be
  6237. running on the printer anymore.
  6238. Called once per MQTT (re)connection (from on_printer_status_change when
  6239. the connected edge flips False → True) and at Bambuddy startup (from
  6240. the FastAPI lifespan). Without this, a print that completes during a
  6241. disconnect window — followed by a smart-plug-driven power cycle — leaves
  6242. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  6243. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  6244. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  6245. power cycle until the operator notices (#1542 follow-up). Reconciliation
  6246. closes the loop by faking the missed PRINT COMPLETE — the existing
  6247. cleanup chain handles SD-file deletion, status updates, usage tracking,
  6248. and notifications.
  6249. Synthesised ``status="aborted"`` is the conservative label: we have no
  6250. proof the print finished successfully (and no progress evidence to
  6251. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  6252. fires later, overwrites the status with the correct value.
  6253. Returns the number of archives reconciled.
  6254. """
  6255. state = printer_manager.get_status(printer_id)
  6256. if not state:
  6257. return 0
  6258. # Don't reconcile while disconnected — we'd be making a decision against
  6259. # stale cached state. The connected → reconcile edge handles this.
  6260. if not state.connected:
  6261. return 0
  6262. from backend.app.models.archive import PrintArchive
  6263. reconciled = 0
  6264. async with async_session() as db:
  6265. result = await db.execute(
  6266. select(PrintArchive).where(
  6267. PrintArchive.printer_id == printer_id,
  6268. PrintArchive.status == "printing",
  6269. )
  6270. )
  6271. active = list(result.scalars().all())
  6272. if not active:
  6273. return 0
  6274. logger = logging.getLogger(__name__)
  6275. for archive in active:
  6276. is_stale, reason = _is_active_archive_stale(archive, state)
  6277. if not is_stale:
  6278. continue
  6279. logger.info(
  6280. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  6281. printer_id,
  6282. archive.id,
  6283. archive.filename,
  6284. reason,
  6285. )
  6286. # Synthesised payload: minimal fields the on_print_complete chain
  6287. # needs. `_reconciled` marker lets downstream code distinguish this
  6288. # from a real MQTT-driven completion if it ever needs to (e.g. for
  6289. # metrics / debug logging). raw_data is the live printer state so
  6290. # the usage tracker can compare end-of-print remain% against the
  6291. # captured start values.
  6292. try:
  6293. await on_print_complete(
  6294. printer_id,
  6295. {
  6296. "status": "aborted",
  6297. "filename": archive.filename,
  6298. "subtask_name": archive.print_name or "",
  6299. "subtask_id": archive.subtask_id or "",
  6300. "raw_data": state.raw_data or {},
  6301. "_reconciled": True,
  6302. },
  6303. )
  6304. reconciled += 1
  6305. except Exception as e:
  6306. # Catch-all: a reconciliation failure must not block the
  6307. # printer's normal status flow. The archive stays in
  6308. # ``status="printing"`` and the next reconnect retries.
  6309. logger.warning(
  6310. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  6311. archive.id,
  6312. e,
  6313. )
  6314. return reconciled
  6315. # #2547: clearance left between the nozzle and the top of the print when the
  6316. # plate is commanded back into camera framing. The nozzle is parked away from
  6317. # the part by then, so this is belt-and-braces against a max_z_height that
  6318. # under-reports (e.g. a slicer that excludes a final Z hop).
  6319. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  6320. # How far below the restored position to drop the plate again afterwards, so
  6321. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  6322. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  6323. # on machines with less headroom.
  6324. _PLATE_PARK_DROP_MM = 100.0
  6325. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  6326. # this axis, so it is a proven-safe speed for the full travel.
  6327. _PLATE_RESTORE_FEEDRATE = 600
  6328. # Time allowed for the plate to reach the restored position before the camera
  6329. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  6330. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  6331. # How long `_background_finish_photo` waits for this producer. Must cover the
  6332. # settle window plus a worst-case RTSP grab (15s), and stay below the
  6333. # notification path's own photo wait so a slow producer degrades to a
  6334. # photo-less notification rather than a missed one. The chamber light's
  6335. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  6336. # camera_light.MAX_DELAY_SECONDS stays below it.
  6337. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  6338. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  6339. """The ``_active_prints`` keys a finished print may be registered under.
  6340. Matching how they were registered in on_print_start. Shared by
  6341. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  6342. to find the same binding.
  6343. """
  6344. possible_keys = []
  6345. # Try subtask_name variations first (most reliable for matching)
  6346. if subtask_name:
  6347. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  6348. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  6349. possible_keys.append((printer_id, subtask_name))
  6350. # Try filename variations
  6351. if filename:
  6352. # Extract just the filename if it's a path
  6353. fname = filename.split("/")[-1] if "/" in filename else filename
  6354. if fname.endswith(".3mf"):
  6355. possible_keys.append((printer_id, fname))
  6356. elif fname.endswith(".gcode"):
  6357. base_name = fname.rsplit(".", 1)[0]
  6358. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  6359. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6360. possible_keys.append((printer_id, fname))
  6361. else:
  6362. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  6363. possible_keys.append((printer_id, f"{fname}.3mf"))
  6364. possible_keys.append((printer_id, fname))
  6365. # Also try full path versions
  6366. if filename.endswith(".3mf"):
  6367. possible_keys.append((printer_id, filename))
  6368. elif filename.endswith(".gcode"):
  6369. base_name = filename.rsplit(".", 1)[0]
  6370. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6371. possible_keys.append((printer_id, filename))
  6372. else:
  6373. possible_keys.append((printer_id, f"{filename}.3mf"))
  6374. possible_keys.append((printer_id, filename))
  6375. return possible_keys
  6376. def _archive_name_forms(archive) -> set[str]:
  6377. """The names an archive could be echoed back as, in normalised form (#3240).
  6378. Its print name, and its filename with and without the 3MF extension.
  6379. """
  6380. forms = set()
  6381. if archive.print_name:
  6382. forms.add(_normalise_subtask_name(archive.print_name))
  6383. if archive.filename:
  6384. forms.add(_normalise_subtask_name(archive.filename))
  6385. for suffix in (".gcode.3mf", ".3mf"):
  6386. if archive.filename.lower().endswith(suffix):
  6387. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  6388. forms.discard("")
  6389. return forms
  6390. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  6391. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  6392. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  6393. from the plate recorded when the job was dispatched. Neither is touched:
  6394. ``on_print_complete`` pops both, which is why the finish-photo producer
  6395. calls this before its first await, while they are still there.
  6396. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  6397. archive, or that it only knows by a name -- and on any error: the producer
  6398. calls this before the ``try`` that always releases the photo consumer, so
  6399. it must not raise.
  6400. """
  6401. try:
  6402. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  6403. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  6404. if archive_id is None:
  6405. return None, None
  6406. return archive_id, _print_plate_ids.get(archive_id)
  6407. except Exception:
  6408. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  6409. return None, None
  6410. async def _max_z_for_current_print(
  6411. printer_id: int,
  6412. data: dict,
  6413. logger,
  6414. archive_id: int | None,
  6415. plate_id: int | None = None,
  6416. ) -> float | None:
  6417. """Height of the print that just finished on ``printer_id``, or None (#2547).
  6418. This number becomes the target of a real Z move, so every step here refuses
  6419. rather than guesses. A height belonging to some *other* print is the one
  6420. failure that could drive the nozzle into the model: 20 mm carried onto a
  6421. 200 mm print would command the plate up through the part.
  6422. Three independent things therefore have to agree before a height is
  6423. returned:
  6424. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  6425. when it started (see ``_bound_print``), never one found by name. A name
  6426. is not an identity: every plate of a multi-plate file shares one, and a
  6427. reprint reuses its archive row, so the newest archive with the right
  6428. name can be another plate of the same file. Support bundles show the
  6429. old name lookup doing exactly that (archive 288 for a print bound to
  6430. 169, 313 layers against 125), stopped only by the layer check below.
  6431. No binding, no move.
  6432. 2. **Identity.** The bound archive's name still has to be the finished
  6433. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  6434. because the printer echoes spaces as underscores (#3240). Exact: not a
  6435. substring, and not the completion check's tolerance for a truncated
  6436. echo.
  6437. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  6438. match the layer count the printer itself reported over MQTT for the print
  6439. that just ended. These come from genuinely different sources, so a
  6440. mismatch means the row is not this print, whatever its name says.
  6441. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  6442. plate of a multi-plate file reuses the archive row without updating its
  6443. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  6444. ``on_print_complete`` may already have flipped the status by the time we
  6445. run.
  6446. """
  6447. subtask_name = (data.get("subtask_name") or "").strip()
  6448. if not subtask_name:
  6449. # Nothing to identify the print by — refuse rather than fall back to
  6450. # "whatever ran last on this printer".
  6451. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  6452. return None
  6453. if archive_id is None:
  6454. logger.info(
  6455. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  6456. printer_id,
  6457. subtask_name,
  6458. )
  6459. return None
  6460. try:
  6461. from backend.app.models.archive import PrintArchive
  6462. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  6463. async with async_session() as db:
  6464. result = await db.execute(
  6465. select(PrintArchive).where(
  6466. PrintArchive.id == archive_id,
  6467. PrintArchive.printer_id == printer_id,
  6468. PrintArchive.status.in_(("printing", "completed")),
  6469. PrintArchive.deleted_at.is_(None),
  6470. )
  6471. )
  6472. archive = result.scalar_one_or_none()
  6473. if archive is None or not archive.file_path:
  6474. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  6475. return None
  6476. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  6477. logger.warning(
  6478. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  6479. printer_id,
  6480. archive_id,
  6481. subtask_name,
  6482. )
  6483. return None
  6484. client = printer_manager.get_client(printer_id)
  6485. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  6486. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  6487. logger.warning(
  6488. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  6489. "— refusing to move the plate on a height that may not be this print's",
  6490. printer_id,
  6491. archive.id,
  6492. archive.total_layers,
  6493. reported_layers,
  6494. )
  6495. return None
  6496. # Stored relative to the data directory, like every other archive path
  6497. # (#3240: this read a `data_dir` setting that does not exist).
  6498. path = app_settings.base_dir / archive.file_path
  6499. plate = plate_id or archive.plate_id or 1
  6500. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  6501. except Exception as e:
  6502. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  6503. return None
  6504. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  6505. """Raise the plate back into camera framing before the finish photo (#2547).
  6506. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  6507. the time ``gcode_state`` reaches FINISH the finished print sits far below
  6508. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  6509. This commands an absolute ``G1 Z`` back to just above the last printed
  6510. layer.
  6511. Absolute, not relative, is the whole safety argument. ``max_z_height +
  6512. clearance`` is a height the toolhead was physically at seconds earlier, so
  6513. it is inside the travel limits by construction and leaves the nozzle above
  6514. the part. It is also unambiguous across model families: Z is the
  6515. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  6516. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  6517. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  6518. (#2579).
  6519. Returns True if the move was sent and waited out, False if it was skipped.
  6520. """
  6521. client = printer_manager.get_client(printer_id)
  6522. if client is None:
  6523. return False
  6524. # Re-read state immediately before commanding motion. If the queue has
  6525. # already started the next print, the printer is no longer ours to move.
  6526. state = getattr(client, "state", None)
  6527. if state is None or state.state != "FINISH":
  6528. logger.info(
  6529. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  6530. printer_id,
  6531. getattr(state, "state", "unknown"),
  6532. )
  6533. return False
  6534. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  6535. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  6536. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  6537. return False
  6538. logger.info(
  6539. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  6540. printer_id,
  6541. target_z,
  6542. max_z_height,
  6543. _PLATE_RESTORE_CLEARANCE_MM,
  6544. _PLATE_RESTORE_SETTLE_SECONDS,
  6545. )
  6546. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  6547. return True
  6548. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  6549. """Drop the plate again after the finish photo (#2547).
  6550. Without this the user walks up to a finished print sitting just under the
  6551. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  6552. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  6553. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  6554. print homes anyway.
  6555. """
  6556. client = printer_manager.get_client(printer_id)
  6557. state = getattr(client, "state", None) if client else None
  6558. if client is None or state is None or state.state != "FINISH":
  6559. return
  6560. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  6561. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  6562. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  6563. """True if a queue item is about to take this printer (#2547).
  6564. The scheduler dispatches the next job the moment a print completes, and a
  6565. plate move interleaved with a print start is not a race worth having. The
  6566. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  6567. this window; this closes the head of it.
  6568. """
  6569. try:
  6570. from backend.app.models.print_queue import PrintQueueItem
  6571. async with async_session() as db:
  6572. result = await db.execute(
  6573. select(PrintQueueItem.id)
  6574. .where(
  6575. PrintQueueItem.printer_id == printer_id,
  6576. PrintQueueItem.status.in_(("pending", "printing")),
  6577. )
  6578. .limit(1)
  6579. )
  6580. return result.scalar_one_or_none() is not None
  6581. except Exception as e:
  6582. # Fail closed: if we can't tell, don't move the plate.
  6583. logging.getLogger(__name__).debug(
  6584. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  6585. )
  6586. return True
  6587. async def on_finish_photo_moment(printer_id: int, data: dict):
  6588. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  6589. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  6590. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  6591. fallback for prints that skip stage 22 (cancel, external-spool-only,
  6592. HMS halt, firmware variants). Grabs one frame via the same
  6593. external-camera / RTSP path the post-completion fallback uses, stores
  6594. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  6595. ``_background_finish_photo`` consume the cached bytes when it runs.
  6596. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  6597. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  6598. set to Smooth (#1721). No force-on now means the user's explicit
  6599. timelapse=off in the slicer send dialog is respected.
  6600. """
  6601. logger = logging.getLogger(__name__)
  6602. trigger = data.get("trigger", "unknown")
  6603. timelapse_was_active = bool(data.get("timelapse_was_active"))
  6604. logger.info(
  6605. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  6606. printer_id,
  6607. trigger,
  6608. timelapse_was_active,
  6609. )
  6610. # If a timelapse is actively recording, skip the pre-capture — the
  6611. # post-completion path will extract the last frame from the recorded
  6612. # video, which still provides the best framing (toolhead parked,
  6613. # before bed drop) without the per-layer parking side effects.
  6614. if timelapse_was_active:
  6615. logger.info(
  6616. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  6617. printer_id,
  6618. )
  6619. return
  6620. # #1790: register the producer-done event BEFORE the first await so the
  6621. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  6622. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  6623. # The `finally` below guarantees `set()` runs on every exit, including
  6624. # early returns and exceptions, so the consumer's bounded wait can't hang.
  6625. producer_done = asyncio.Event()
  6626. _stage22_finish_in_flight[printer_id] = producer_done
  6627. # #3240: also before the first await. On the FINISH-state path
  6628. # `on_print_complete` is dispatched right behind us and pops both the
  6629. # print's archive binding and its plate; read here, they are still there.
  6630. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  6631. # #2547: set once the plate has actually been raised, and read by the
  6632. # `finally` below. Declared out here so a failure anywhere after the move —
  6633. # a camera timeout, a DB error — still lowers the plate again.
  6634. restore_max_z: float | None = None
  6635. try:
  6636. async with async_session() as db:
  6637. from backend.app.api.routes.settings import get_setting
  6638. from backend.app.models.printer import Printer
  6639. capture_setting = await get_setting(db, "capture_finish_photo")
  6640. if capture_setting is not None and capture_setting.lower() != "true":
  6641. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  6642. return
  6643. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6644. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  6645. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6646. printer = result.scalar_one_or_none()
  6647. if printer is None:
  6648. logger.warning(
  6649. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  6650. printer_id,
  6651. )
  6652. return
  6653. frame_bytes: bytes | None = None
  6654. # #2708: the banked frame arrives already rotated — it comes from
  6655. # `_capture_snapshot_for_notification`, which rotates before returning.
  6656. # Every other source below is a raw grab. Tracking which lets us store
  6657. # exactly one rotation in `_stage22_finish_frames` either way.
  6658. frame_already_rotated = False
  6659. # On the FINISH-state path the End G-code has already run, and two very
  6660. # different situations arrive here needing opposite answers.
  6661. #
  6662. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  6663. # snippet may have ejected the plate — the scene in front of the camera
  6664. # is no longer the finished print, and no amount of moving the plate
  6665. # brings it back. Use the banked in-print frame instead.
  6666. #
  6667. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  6668. # than the camera frames well, and the toolhead is parked out of the
  6669. # way. That is the *best* moment available on firmware that never emits
  6670. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  6671. # back. Preferring the bank here unconditionally, as this code used to,
  6672. # is what shipped a mid-print photo with the toolhead over the part.
  6673. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  6674. banked = _inprint_frame_bank.get(printer_id)
  6675. if banked:
  6676. frame_bytes = banked
  6677. frame_already_rotated = True
  6678. logger.info(
  6679. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  6680. "frame (%d bytes) instead of a post-swap live grab",
  6681. len(banked),
  6682. )
  6683. else:
  6684. logger.warning(
  6685. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  6686. "in-print bank is empty — falling back to a live grab, which may show a "
  6687. "swapped or empty plate",
  6688. printer_id,
  6689. )
  6690. # `restore_max_z` is set only once the plate is actually up, because the
  6691. # `finally` reads it to decide whether it owes a move back down.
  6692. #
  6693. # Never on a print whose End G-code Bambuddy injected, even when the bank
  6694. # came up empty above: that machine may have just ejected its plate, and
  6695. # driving Z into whatever a swap mechanism is doing is not a risk worth
  6696. # taking for a photo of a bed we already know may be bare.
  6697. if (
  6698. frame_bytes is None
  6699. and trigger == "finish_state"
  6700. and restore_plate_enabled
  6701. and not print_dispatch_context.end_gcode_injected(printer_id)
  6702. ):
  6703. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  6704. if wants_restore is None:
  6705. logger.info(
  6706. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  6707. printer_id,
  6708. )
  6709. elif await _plate_restore_is_blocked_by_queue(printer_id):
  6710. logger.info(
  6711. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  6712. printer_id,
  6713. )
  6714. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  6715. restore_max_z = wants_restore
  6716. # Chamber light for the live capture below (#1655). The banked frame
  6717. # above was taken without it, like every in-print bank.
  6718. async with camera_light(printer if frame_bytes is None else None):
  6719. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  6720. from backend.app.api.routes.camera import live_frame_for_capture
  6721. from backend.app.services.external_camera import capture_frame
  6722. # #2707: this used to collide with the live view and fail, which is
  6723. # how finish-photo notifications went out with no image attached.
  6724. # Leaving frame_bytes None keeps the rest of the fallback chain.
  6725. defer, buffered = live_frame_for_capture(printer_id)
  6726. if defer:
  6727. frame_bytes = buffered
  6728. else:
  6729. frame_bytes = await capture_frame(
  6730. printer.external_camera_url,
  6731. printer.external_camera_type or "mjpeg",
  6732. snapshot_url=printer.external_camera_snapshot_url,
  6733. )
  6734. if frame_bytes:
  6735. logger.info(
  6736. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  6737. len(frame_bytes),
  6738. )
  6739. elif frame_bytes is None:
  6740. from backend.app.api.routes.camera import get_buffered_frame
  6741. buffered = get_buffered_frame(printer_id)
  6742. if buffered:
  6743. frame_bytes = buffered
  6744. logger.info(
  6745. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  6746. len(frame_bytes),
  6747. )
  6748. else:
  6749. from backend.app.services.camera import capture_camera_frame_bytes
  6750. frame_bytes = await capture_camera_frame_bytes(
  6751. ip_address=printer.ip_address,
  6752. access_code=printer.access_code,
  6753. model=printer.model,
  6754. timeout=15,
  6755. )
  6756. if frame_bytes:
  6757. logger.info(
  6758. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  6759. len(frame_bytes),
  6760. )
  6761. if frame_bytes:
  6762. if not frame_already_rotated:
  6763. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  6764. _stage22_finish_frames[printer_id] = frame_bytes
  6765. else:
  6766. logger.warning(
  6767. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  6768. printer_id,
  6769. )
  6770. except Exception as e:
  6771. logger.warning(
  6772. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  6773. printer_id,
  6774. e,
  6775. )
  6776. finally:
  6777. # #2547: we raised the plate, so we own lowering it — including when the
  6778. # capture above failed or threw partway through.
  6779. if restore_max_z is not None:
  6780. try:
  6781. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  6782. except Exception as e:
  6783. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6784. # #1790: always unblock the consumer's bounded wait — whether we stored
  6785. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  6786. # dict entry by the consumer doesn't affect signalling.
  6787. producer_done.set()
  6788. def _subtask_name_from_filename(filename: str) -> str:
  6789. """Recover the subtask name a print command would have carried for *filename*.
  6790. The dispatcher derives the printer-facing subtask name from the archive's
  6791. file name, so stripping the extensions back off gives the value MQTT echoes
  6792. on completion. Only the two extensions Bambuddy actually stores are removed,
  6793. and in the order they nest (``.gcode.3mf``), so a model whose own name
  6794. contains a dot -- ``My.Model.3mf`` -- keeps it.
  6795. """
  6796. name = PurePosixPath(filename).name
  6797. for suffix in (".3mf", ".gcode"):
  6798. if name.lower().endswith(suffix):
  6799. name = name[: -len(suffix)]
  6800. return name
  6801. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  6802. """Whether the subtask name is the printed 3MF's own file name.
  6803. A print started from the printer's screen reports the same full name, with
  6804. its extension, as both subtask and file (#3009). A dispatched print reports
  6805. a bare subtask name; one that merely ends in ".3mf" can be a model named
  6806. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  6807. """
  6808. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  6809. return False
  6810. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  6811. # How the printer marks a subtask name it had to cut short. Observed on real
  6812. # hardware at ~100 characters, but the cut-off is not a fixed character count
  6813. # (a name with multibyte characters came back at 98), so match the marker
  6814. # rather than a length.
  6815. _SUBTASK_TRUNCATION_MARKER = "..."
  6816. def _normalise_subtask_name(name: str) -> str:
  6817. """Canonical form for comparing a dispatched name against MQTT's echo.
  6818. The printer does not echo the name back verbatim: it substitutes
  6819. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  6820. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  6821. The 3MF lookup in this module has always known that -- it builds
  6822. space-to-underscore variants of every candidate filename, and its
  6823. directory search normalises both sides before comparing. This exists so
  6824. the completion check reads the same rule from the same place instead of
  6825. growing its own, which is exactly how it came to disagree (#2829).
  6826. A space at either end is substituted too: ``Part .gcode.3mf`` is
  6827. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  6828. are dropped after the substitution so both sides agree (#3241).
  6829. """
  6830. return name.strip().replace(" ", "_").strip("_").casefold()
  6831. def _3mf_files_for_print(paths: list[str], search_term: str) -> list[str]:
  6832. """The 3MF files of the printer's folder listings that are this print's.
  6833. A file of the print's own name wins, in whichever folder. Only without one
  6834. is a file that merely contains the name taken, and then only when it is
  6835. the one such file: "Cube_large.3mf" is not "Cube"'s file, and of several
  6836. candidates none can be told apart. Paths keep the listings' order.
  6837. """
  6838. threemf = [path for path in paths if path.lower().endswith(".3mf")]
  6839. exact = [path for path in threemf if _subtask_names_match(_subtask_name_from_filename(path), search_term)]
  6840. if exact:
  6841. return exact
  6842. term = _normalise_subtask_name(search_term)
  6843. partial = [path for path in threemf if term in _normalise_subtask_name(PurePosixPath(path).name)]
  6844. if len(partial) > 1:
  6845. logging.getLogger(__name__).info(
  6846. "Several 3MF files contain %r and none is named for it: %s", search_term, partial
  6847. )
  6848. return []
  6849. return partial
  6850. def _subtask_names_match(expected: str, observed: str) -> bool:
  6851. """Whether two subtask names describe the same print.
  6852. Beyond the space/underscore substitution, the printer truncates long names
  6853. and marks the cut with ``...``. A truncated echo has to count as a match or
  6854. every print with a long name strands its queue item the same way.
  6855. """
  6856. expected_n = _normalise_subtask_name(expected)
  6857. observed_n = _normalise_subtask_name(observed)
  6858. if expected_n == observed_n:
  6859. return True
  6860. # Either side can be the truncated one: the printer truncates what it
  6861. # echoes, and an archive whose own filename was recorded from a previous
  6862. # truncated echo carries the marker too.
  6863. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  6864. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  6865. continue
  6866. # The full side has lost its edge underscores; a cut that lands right
  6867. # after one keeps it, so drop it here too (#3241). Nothing left before
  6868. # the marker is no evidence of anything, and must not match every name.
  6869. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  6870. if kept and full.startswith(kept):
  6871. return True
  6872. return False
  6873. async def _queue_item_dispatched_name(db, item) -> str:
  6874. """The subtask name *item* was dispatched under, or "" when unknowable.
  6875. A row with no archive, or an archive with no file name, is unverifiable
  6876. rather than wrong; every caller answers that with its permissive branch.
  6877. """
  6878. if item.archive_id is None:
  6879. return ""
  6880. from backend.app.models.archive import PrintArchive
  6881. archive = await db.get(PrintArchive, item.archive_id)
  6882. if archive is None or not archive.filename:
  6883. return ""
  6884. return _subtask_name_from_filename(archive.filename)
  6885. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  6886. """Whether this completion event is plausibly about *item*'s print.
  6887. The caller finds its queue row by printer and ``status='printing'`` alone,
  6888. which is all a completion event gives it -- there is no run identifier in
  6889. the MQTT payload to match on. That makes the lookup indiscriminate: any
  6890. completion delivered for this printer closes whichever row happens to be
  6891. printing, however unrelated. Comparing the subtask name against the archive
  6892. the row was dispatched with costs one primary-key load and rules that out.
  6893. Deliberately permissive: it answers False only on a positive disagreement
  6894. between two names we actually have. A row with no archive, an archive with
  6895. no file name, or an event with no subtask name is unverifiable rather than
  6896. wrong, and refusing those would strand the item in ``printing`` and wedge
  6897. the printer's queue -- a worse failure than the one being prevented.
  6898. """
  6899. observed = (data.get("subtask_name") or "").strip()
  6900. if not observed or item.archive_id is None:
  6901. return True
  6902. from backend.app.models.archive import PrintArchive
  6903. archive = await db.get(PrintArchive, item.archive_id)
  6904. if archive is None or not archive.filename:
  6905. return True
  6906. expected = _subtask_name_from_filename(archive.filename)
  6907. if not expected or _subtask_names_match(expected, observed):
  6908. return True
  6909. logging.getLogger(__name__).warning(
  6910. "Ignoring print completion for queue item %s: it was dispatched as %r "
  6911. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  6912. "printing rather than closing a run this event is not about.",
  6913. item.id,
  6914. expected,
  6915. archive.id,
  6916. archive.filename,
  6917. observed,
  6918. )
  6919. return False
  6920. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  6921. """Spend the 3MF download cache on a still-empty fallback archive.
  6922. ``on_print_complete`` drops the cache as its first act, which deletes the
  6923. file. If the cover endpoint (or anything else) pulled the 3MF while the
  6924. print ran and the archive never got one, this is the last moment those bytes
  6925. exist (#2957).
  6926. """
  6927. logger = logging.getLogger(__name__)
  6928. names = [
  6929. n
  6930. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  6931. if n
  6932. ]
  6933. for name in names:
  6934. try:
  6935. cached = get_cached_3mf(printer_id, name)
  6936. # The print has ended: its completion prices the archive, so no
  6937. # print-start estimate is scheduled to race it.
  6938. if cached and await try_recover_fallback_archive(printer_id, name, cached, price=False):
  6939. return
  6940. except Exception as e:
  6941. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  6942. async def _cleanup_sd_card_after_print(
  6943. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  6944. ) -> None:
  6945. """Delete a finished print's file from the printer's SD card."""
  6946. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  6947. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  6948. # auto-start files found in root on power cycle, causing ghost prints.
  6949. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  6950. try:
  6951. if subtask_name:
  6952. archive_filename: str | None = None
  6953. async with async_session() as db:
  6954. from backend.app.models.archive import PrintArchive
  6955. from backend.app.models.printer import Printer
  6956. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6957. printer = result.scalar_one_or_none()
  6958. if archive_id:
  6959. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  6960. archive_filename = archive_row.scalar_one_or_none()
  6961. if printer:
  6962. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  6963. from backend.app.utils.filename import derive_remote_filename
  6964. # Primary candidate: the exact path the dispatcher uploaded to
  6965. # (derived from archive.filename via the same rule as upload).
  6966. # Without it, a library row that ended up with a doubled
  6967. # .gcode.3mf (#1542) leaves the real file behind because the
  6968. # subtask_name + ext fallbacks below don't match what's on the
  6969. # SD card. Fallbacks remain for archive-less prints (subtask
  6970. # never resolved to an archive) and for older naming variants.
  6971. candidate_paths: list[str] = []
  6972. if archive_filename:
  6973. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  6974. for ext in (".3mf", ".gcode"):
  6975. fallback = f"/{subtask_name}{ext}"
  6976. if fallback not in candidate_paths:
  6977. candidate_paths.append(fallback)
  6978. # Three outcomes track across all candidates so the final log
  6979. # line reflects what actually happened. The A1 in #1721 always
  6980. # ends here with ``any_not_found=True`` and the others False
  6981. # — its firmware auto-cleans the SD card before our cleanup
  6982. # runs, every candidate FTP-DELE returns 550, and the old
  6983. # code burned 3 retries × 2 s × 3 candidates per print
  6984. # logging a misleading "may linger" WARNING on a successful
  6985. # print.
  6986. any_deleted = False
  6987. any_real_failure = False
  6988. any_not_found = False
  6989. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  6990. for remote_path in candidate_paths:
  6991. if PurePosixPath(remote_path).name.lower() in files_in_use:
  6992. logger.info(
  6993. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  6994. remote_path,
  6995. printer.name,
  6996. )
  6997. continue
  6998. # Retry only the FAILED case — 550 NOT_FOUND will never
  6999. # recover by waiting, so a "file isn't here" answer
  7000. # advances immediately to the next candidate without
  7001. # consuming the retry budget.
  7002. for attempt in range(1, 4):
  7003. try:
  7004. delete_result = await delete_file_async(
  7005. printer.ip_address,
  7006. printer.access_code,
  7007. remote_path,
  7008. printer_model=printer.model,
  7009. )
  7010. except Exception as e:
  7011. delete_result = DeleteResult.FAILED
  7012. logger.warning(
  7013. "SD card cleanup attempt %d/3 raised for %s: %s",
  7014. attempt,
  7015. remote_path,
  7016. e,
  7017. )
  7018. if delete_result == DeleteResult.DELETED:
  7019. any_deleted = True
  7020. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  7021. break
  7022. if delete_result == DeleteResult.NOT_FOUND:
  7023. any_not_found = True
  7024. break # 550 will not recover; try next candidate
  7025. # FAILED: real error — retry with backoff, then give up
  7026. if attempt < 3:
  7027. await asyncio.sleep(2)
  7028. else:
  7029. any_real_failure = True
  7030. logger.warning(
  7031. "SD card cleanup failed after 3 attempts for %s "
  7032. "(network/auth/transient error — file may linger on SD card)",
  7033. remote_path,
  7034. )
  7035. if not any_deleted and not any_real_failure and any_not_found:
  7036. # Every candidate said "not here." Either the printer
  7037. # firmware swept the SD card itself (common on A1) or the
  7038. # dispatcher's upload path doesn't match our candidate
  7039. # rule. Either way: nothing to clean up, no warning.
  7040. logger.debug(
  7041. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  7042. "(printer likely self-cleaned)",
  7043. printer.name,
  7044. )
  7045. except Exception as e:
  7046. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  7047. async def on_print_complete(printer_id: int, data: dict):
  7048. """Handle print completion - update the archive status."""
  7049. import time
  7050. logger = logging.getLogger(__name__)
  7051. start_time = time.time()
  7052. def log_timing(section: str):
  7053. elapsed = time.time() - start_time
  7054. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  7055. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  7056. # A kill-switch stop sends its provider notification immediately. Keep the
  7057. # task so the later notification path can await it and avoid a duplicate;
  7058. # if that immediate attempt failed, the regular completion path retries.
  7059. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  7060. # Last chance before the bytes go: if this print's archive is still an empty
  7061. # fallback and something downloaded the 3MF while it ran, fill the archive in
  7062. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  7063. # below deletes the file (#2957).
  7064. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  7065. # A pending cool-off retry has nothing left to recover for — the cache is
  7066. # about to be dropped and the print is over.
  7067. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  7068. if retry_task and not retry_task.done():
  7069. retry_task.cancel()
  7070. # Drop the 3MF download cache for this printer (#972). The print is over,
  7071. # nothing else legitimately needs the bytes; keeping them would only risk
  7072. # handing a stale file to the next print if it reuses the same name.
  7073. clear_3mf_cache(printer_id)
  7074. try:
  7075. ws_data = {
  7076. "status": data.get("status"),
  7077. "filename": data.get("filename"),
  7078. "subtask_name": data.get("subtask_name"),
  7079. "timelapse_was_active": data.get("timelapse_was_active"),
  7080. }
  7081. await ws_manager.send_print_complete(printer_id, ws_data)
  7082. log_timing("WebSocket send_print_complete")
  7083. except Exception as e:
  7084. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  7085. # Capture user info before clearing (needed for print log entry)
  7086. _print_user_info = printer_manager.get_current_print_user(printer_id)
  7087. # Clear current print user tracking (Issue #206)
  7088. printer_manager.clear_current_print_user(printer_id)
  7089. # If the user explicitly stopped this print from the queue UI the printer will
  7090. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  7091. # correct "print stopped" notification/email is sent instead of a failure alert.
  7092. _raw_status = data.get("status", "completed")
  7093. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  7094. logger.info(
  7095. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  7096. _raw_status,
  7097. printer_id,
  7098. )
  7099. data = {**data, "status": "cancelled"}
  7100. elif printer_id in _kill_switch_stopped and _raw_status in ("failed", "aborted"):
  7101. logger.info(
  7102. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (stopped by the printer kill switch)",
  7103. _raw_status,
  7104. printer_id,
  7105. )
  7106. data = {**data, "status": "cancelled", "_kill_switch": True}
  7107. _user_stopped_printers.discard(printer_id)
  7108. _kill_switch_stopped.discard(printer_id)
  7109. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  7110. # may have left material on the bed: a user can cancel ten hours into a
  7111. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  7112. # touchscreen-stop reports `aborted` rather than `cancelled` because
  7113. # `_user_stopped_printers` is only populated when the user stops via the
  7114. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  7115. # which auto-dispatched the next queued print onto a fouled bed two seconds
  7116. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  7117. # Auto Off power cycles and Bambuddy restarts.
  7118. try:
  7119. notify_live_activities.print_finished(printer_id, data)
  7120. except Exception:
  7121. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  7122. _final_status = data.get("status", "completed")
  7123. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  7124. printer_manager.set_awaiting_plate_clear(printer_id, True)
  7125. # MQTT relay - publish print complete
  7126. try:
  7127. printer_info = printer_manager.get_printer(printer_id)
  7128. if printer_info:
  7129. await mqtt_relay.on_print_complete(
  7130. printer_id,
  7131. printer_info.name,
  7132. printer_info.serial_number,
  7133. data.get("filename", ""),
  7134. data.get("subtask_name", ""),
  7135. data.get("status", "completed"),
  7136. )
  7137. except Exception:
  7138. pass # Don't fail print complete callback if MQTT fails
  7139. filename = data.get("filename", "")
  7140. subtask_name = data.get("subtask_name", "")
  7141. if not filename and not subtask_name:
  7142. logger.warning("Print complete without filename or subtask_name")
  7143. return
  7144. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  7145. # Build list of possible keys to try (matching how they were registered in on_print_start)
  7146. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  7147. # Find the archive for this print
  7148. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  7149. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  7150. archive_id = None
  7151. for key in possible_keys:
  7152. archive_id = _active_prints.pop(key, None)
  7153. if archive_id:
  7154. _owned_print_archive_ids.discard(archive_id)
  7155. logger.info("Found archive %s with key %s", archive_id, key)
  7156. # Also clean up any other keys pointing to this archive
  7157. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  7158. for k in keys_to_remove:
  7159. _active_prints.pop(k, None)
  7160. break
  7161. # The archive bound when the print started, before the name search below.
  7162. # Only this one may give the finish-photo plate restore a height (#3240):
  7163. # the search matches names by substring.
  7164. bound_archive_id = archive_id
  7165. if not archive_id:
  7166. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  7167. async with async_session() as db:
  7168. from backend.app.models.archive import PrintArchive
  7169. # Try matching by subtask_name (stored as print_name) first. The
  7170. # same name rule as the queue's completion check: a name inside
  7171. # another ("Clip" in "Cable Clip") is a different print, and the
  7172. # printer's underscores for spaces and truncation still match.
  7173. if subtask_name:
  7174. printing = await db.scalars(
  7175. select(PrintArchive)
  7176. .where(PrintArchive.printer_id == printer_id)
  7177. .where(PrintArchive.status == "printing")
  7178. .order_by(PrintArchive.created_at.desc())
  7179. )
  7180. # A print started from the printer's screen reports its file
  7181. # name, extensions included, as the subtask (#3009).
  7182. reported = {subtask_name, _subtask_name_from_filename(subtask_name)}
  7183. archive = next(
  7184. (
  7185. candidate
  7186. for candidate in printing
  7187. if any(
  7188. (candidate.print_name and _subtask_names_match(candidate.print_name, name))
  7189. or (
  7190. candidate.filename
  7191. and _subtask_names_match(_subtask_name_from_filename(candidate.filename), name)
  7192. )
  7193. for name in reported
  7194. )
  7195. ),
  7196. None,
  7197. )
  7198. if archive:
  7199. archive_id = archive.id
  7200. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  7201. # Also try by filename
  7202. if not archive_id and filename:
  7203. result = await db.execute(
  7204. select(PrintArchive)
  7205. .where(PrintArchive.printer_id == printer_id)
  7206. .where(PrintArchive.filename == filename)
  7207. .where(PrintArchive.status == "printing")
  7208. .order_by(PrintArchive.created_at.desc())
  7209. .limit(1)
  7210. )
  7211. archive = result.scalar_one_or_none()
  7212. if archive:
  7213. archive_id = archive.id
  7214. await _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger)
  7215. log_timing("SD card cleanup")
  7216. # Update queue item status early — must run before the archive_id early-return
  7217. # so queue items don't get stuck in "printing" when archive lookup fails.
  7218. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  7219. queue_item_id = None
  7220. billing_run_id: str | None = None
  7221. billing_user_id: int | None = None
  7222. billing_cost_center_id: int | None = None
  7223. billing_plate_id: int | None = None
  7224. queue_status = None
  7225. queue_auto_off = False
  7226. try:
  7227. from backend.app.core.database import run_with_retry
  7228. from backend.app.models.print_queue import PrintQueueItem
  7229. async def _update_queue_status(db):
  7230. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  7231. nonlocal queue_item_id, queue_status, queue_auto_off
  7232. result = await db.execute(
  7233. select(PrintQueueItem)
  7234. .where(PrintQueueItem.printer_id == printer_id)
  7235. .where(PrintQueueItem.status == "printing")
  7236. )
  7237. printing_items = list(result.scalars().all())
  7238. if len(printing_items) > 1:
  7239. logger.warning(
  7240. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  7241. printer_id,
  7242. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  7243. )
  7244. item = printing_items[0] if printing_items else None
  7245. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  7246. return
  7247. if item:
  7248. queue_status = data.get("status", "completed")
  7249. # MQTT sends "aborted" for cancelled prints; normalise to
  7250. # "cancelled" so it matches the queue schema Literal.
  7251. if queue_status == "aborted":
  7252. queue_status = "cancelled"
  7253. item.status = queue_status
  7254. item.completed_at = datetime.now(timezone.utc)
  7255. if queue_status == "failed" and not item.error_message:
  7256. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  7257. # Bump usage counters on the source library file so admins can
  7258. # sort by "last printed" and (eventually) auto-purge stale
  7259. # files — #1008.
  7260. await _bump_library_file_usage_if_completed(db, item, queue_status)
  7261. await db.commit()
  7262. queue_item_id = item.id
  7263. billing_run_id = item.billing_run_id
  7264. billing_user_id = item.created_by_id
  7265. billing_cost_center_id = item.cost_center_id
  7266. billing_plate_id = item.plate_id
  7267. queue_auto_off = item.auto_off_after
  7268. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  7269. await run_with_retry(_update_queue_status, label="queue status update")
  7270. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  7271. # their own sessions and have their own error handling — no retry needed.
  7272. if queue_item_id is not None:
  7273. # Batch orders (#342): this run may have been the last one an order
  7274. # owed. Re-evaluate here rather than lazily on read, so a finished
  7275. # order reports itself complete without someone opening the page.
  7276. try:
  7277. from backend.app.services.print_batch import refresh_batch_status_for_item
  7278. async with async_session() as db:
  7279. await refresh_batch_status_for_item(db, queue_item_id)
  7280. await db.commit()
  7281. except Exception as e:
  7282. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  7283. # MQTT relay - publish queue job completed
  7284. try:
  7285. printer_info = printer_manager.get_printer(printer_id)
  7286. await mqtt_relay.on_queue_job_completed(
  7287. job_id=queue_item_id,
  7288. filename=filename or subtask_name,
  7289. printer_id=printer_id,
  7290. printer_name=printer_info.name if printer_info else "Unknown",
  7291. status=queue_status,
  7292. )
  7293. except Exception:
  7294. pass # Don't fail if MQTT fails
  7295. # Check if queue is now empty and send notification
  7296. try:
  7297. from sqlalchemy import func as sa_func
  7298. async with async_session() as db:
  7299. count_result = await db.execute(
  7300. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  7301. )
  7302. pending_count = count_result.scalar() or 0
  7303. if pending_count == 0:
  7304. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  7305. completed_result = await db.execute(
  7306. select(sa_func.count(PrintQueueItem.id)).where(
  7307. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  7308. PrintQueueItem.completed_at >= today_start,
  7309. )
  7310. )
  7311. completed_count = completed_result.scalar() or 1
  7312. await notification_service.on_queue_completed(
  7313. completed_count=completed_count,
  7314. db=db,
  7315. )
  7316. except Exception:
  7317. pass # Don't fail if notification fails
  7318. # Handle auto_off_after - power off printer if the queue item opted
  7319. # in. Delegates to the smart-plug manager so the off honours each
  7320. # plug's configured strategy (time delay or temperature threshold),
  7321. # is cancelled if the printer starts printing again, and never cuts
  7322. # power on a loaded print (#1890). Previously an inline block here
  7323. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  7324. # timeout regardless of print state — cutting a touchscreen reprint.
  7325. if queue_auto_off:
  7326. try:
  7327. async with async_session() as db:
  7328. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  7329. except Exception as e:
  7330. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  7331. except Exception as e:
  7332. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  7333. log_timing("Queue item update")
  7334. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  7335. # Must run before archive_id early-return so it fires for all prints (including
  7336. # prints started from BambuStudio/touchscreen that have no archive).
  7337. if data.get("status") == "completed":
  7338. try:
  7339. from backend.app.api.routes.settings import get_setting
  7340. async with async_session() as db:
  7341. threshold_str = await get_setting(db, "bed_cooled_threshold")
  7342. threshold = float(threshold_str) if threshold_str else 35.0
  7343. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  7344. async with async_session() as db:
  7345. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  7346. if providers:
  7347. _bed_cool_waiters[printer_id] = {
  7348. "threshold": threshold,
  7349. "filename": filename or subtask_name or "",
  7350. "registered_at": time.time(),
  7351. }
  7352. logger.info(
  7353. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  7354. printer_id,
  7355. threshold,
  7356. )
  7357. else:
  7358. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  7359. except Exception as e:
  7360. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  7361. # Capture the slicer estimate before usage tracking runs. The tracker may
  7362. # update archive.cost with this run's measured cost; billing partial runs
  7363. # against that already-partial value would discount the charge twice.
  7364. billing_planned_grams: float | None = None
  7365. billing_base_cost: float | None = None
  7366. if archive_id:
  7367. try:
  7368. async with async_session() as db:
  7369. from backend.app.models.archive import PrintArchive
  7370. billing_archive = await db.get(PrintArchive, archive_id)
  7371. if billing_archive:
  7372. billing_path = (
  7373. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  7374. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7375. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  7376. billing_archive,
  7377. billing_path,
  7378. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  7379. )
  7380. except Exception as e:
  7381. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  7382. # --- Track filament consumption (must run before archive_id early-return so usage
  7383. # is recorded even when auto-archive is disabled) ---
  7384. usage_results: list[dict] = []
  7385. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  7386. stored_ams_mapping = data.get("ams_mapping")
  7387. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  7388. if not stored_ams_mapping and archive_id:
  7389. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  7390. # Always drain the plate_id register on completion — the session already
  7391. # consumed it at print-start injection; leaving it would leak into the next
  7392. # print on the same archive_id (rare but possible with reprints) (#1697).
  7393. # Capture the popped value so the completion notification can scope the
  7394. # archive-level (summed-across-plates per #1593) filament + time totals
  7395. # down to the single plate that was actually printed (#1785).
  7396. notify_plate_id: int | None = None
  7397. if archive_id:
  7398. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  7399. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  7400. try:
  7401. async with async_session() as db:
  7402. from backend.app.api.routes.settings import get_setting
  7403. _spoolman_on = await get_setting(db, "spoolman_enabled")
  7404. if not _spoolman_on or _spoolman_on.lower() != "true":
  7405. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  7406. async with async_session() as db:
  7407. usage_results = await usage_on_print_complete(
  7408. printer_id,
  7409. data,
  7410. printer_manager,
  7411. db,
  7412. archive_id=archive_id,
  7413. ams_mapping=stored_ams_mapping,
  7414. )
  7415. if usage_results:
  7416. await ws_manager.broadcast(
  7417. {
  7418. "type": "spool_usage_logged",
  7419. "printer_id": printer_id,
  7420. "usage": usage_results,
  7421. }
  7422. )
  7423. log_timing("Usage tracker")
  7424. except Exception as e:
  7425. logger.warning("Usage tracker on_print_complete failed: %s", e)
  7426. # Drop the print-start context unconditionally — the Spoolman branch above
  7427. # skips the internal tracker entirely, so nothing else would clear what
  7428. # print start captured, and a row surviving its print would be restored
  7429. # onto the next one after a restart.
  7430. try:
  7431. from backend.app.services.usage_tracker import discard_session
  7432. async with async_session() as db:
  7433. await discard_session(db, printer_id)
  7434. except Exception as e:
  7435. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  7436. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  7437. # A partial run's cost from the Spoolman spools it was charged to; the
  7438. # built-in inventory's comes in usage_results.
  7439. spoolman_run_cost: float | None = None
  7440. if archive_id:
  7441. if data.get("status") == "completed":
  7442. try:
  7443. await _report_spoolman_usage(printer_id, archive_id)
  7444. log_timing("Spoolman usage report")
  7445. except Exception as e:
  7446. logger.warning("Spoolman usage reporting failed: %s", e)
  7447. else:
  7448. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  7449. try:
  7450. async with async_session() as db:
  7451. spoolman_run_cost = await _cleanup_spoolman_tracking(
  7452. printer_id,
  7453. archive_id,
  7454. db,
  7455. last_layer_num=data.get("last_layer_num"),
  7456. last_progress=data.get("last_progress"),
  7457. )
  7458. except Exception as e:
  7459. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  7460. await _release_archived_spoolman_slots(printer_id)
  7461. log_timing("Filament usage tracking")
  7462. if not archive_id:
  7463. # The printer's own calibration run has no archive by design, so this
  7464. # arrives here every time one finishes. Returning before the no-archive
  7465. # notification keeps a calibration from being announced as a finished
  7466. # print. Everything above this point has already run — the plate-clear
  7467. # gate, the queue reconciliation, the SD-card cleanup — so only the
  7468. # notification is skipped.
  7469. if is_internal_printer_job(filename, subtask_name):
  7470. logger.info(
  7471. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  7472. filename,
  7473. subtask_name,
  7474. )
  7475. return
  7476. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  7477. # Still send print-complete/failed/stopped notifications even without an archive.
  7478. # Try to enrich with queue/library-file data so user-specific emails work too.
  7479. async def _notify_no_archive():
  7480. try:
  7481. async with async_session() as db:
  7482. from backend.app.models.library import LibraryFile
  7483. from backend.app.models.print_queue import PrintQueueItem
  7484. from backend.app.models.printer import Printer
  7485. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7486. printer_obj = result.scalar_one_or_none()
  7487. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  7488. # Only the queue item this completion itself closed (the
  7489. # reconciliation above, which checks the run belongs to it).
  7490. # A print started outside Bambuddy closed none, and must not
  7491. # borrow an earlier job's owner, email or times.
  7492. no_archive_data: dict | None = None
  7493. try:
  7494. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  7495. if queue_item:
  7496. no_archive_data = {"created_by_id": queue_item.created_by_id}
  7497. # How long it really ran, as the archive path reports it (#1198).
  7498. started = to_naive_utc(queue_item.started_at)
  7499. ended = to_naive_utc(queue_item.completed_at)
  7500. if started and ended and (ended - started).total_seconds() > 0:
  7501. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  7502. # Estimated time: the queue item caches it from its
  7503. # archive or library file; otherwise read the library
  7504. # file's metadata (LibraryFile has no column for it).
  7505. if queue_item.print_time_seconds:
  7506. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  7507. elif queue_item.library_file_id:
  7508. lib_result = await db.execute(
  7509. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  7510. )
  7511. lib_file = lib_result.scalar_one_or_none()
  7512. estimate = (
  7513. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  7514. )
  7515. if estimate:
  7516. no_archive_data["print_time_seconds"] = estimate
  7517. except Exception as lookup_err:
  7518. logger.debug(
  7519. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  7520. )
  7521. # Enrich with usage tracker results (captured in enclosing scope)
  7522. if usage_results:
  7523. if no_archive_data is None:
  7524. no_archive_data = {}
  7525. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7526. if total_from_usage > 0:
  7527. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7528. no_archive_data["usage_results"] = usage_results
  7529. # Try MQTT remaining_time for print duration when no queue/library data
  7530. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  7531. mqtt_remaining = data.get("remaining_time")
  7532. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  7533. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  7534. ps = data.get("status", "completed")
  7535. logger.info(
  7536. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  7537. )
  7538. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7539. await notification_service.on_print_complete(
  7540. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  7541. )
  7542. else:
  7543. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7544. # Send user-specific email if we have a created_by_id
  7545. if no_archive_data and no_archive_data.get("created_by_id"):
  7546. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7547. await _dispatch_user_print_email(
  7548. ps,
  7549. no_archive_data["created_by_id"],
  7550. p_name,
  7551. raw_filename,
  7552. db,
  7553. )
  7554. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  7555. except Exception as e:
  7556. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  7557. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  7558. return
  7559. log_timing("Archive lookup")
  7560. # Update archive status
  7561. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  7562. try:
  7563. async with async_session() as db:
  7564. service = ArchiveService(db)
  7565. status = data.get("status", "completed")
  7566. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  7567. if hms_errors:
  7568. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  7569. failure_reason = derive_failure_reason(status, hms_errors)
  7570. if data.get("_reconciled"):
  7571. # A reconciled completion closes out a stale archive at
  7572. # reconnect — it is not a user action, so don't mislabel it
  7573. # "userCancelled". It shares the stale-cleanup path's key
  7574. # (issue #2974) and records that the real end time is unknown,
  7575. # which is also why its logged duration is 0 (#2592).
  7576. failure_reason = "noStatusUpdate"
  7577. elif data.get("_kill_switch"):
  7578. # Not the user's cancel: the kill switch stopped a print that did
  7579. # not come from Bambuddy.
  7580. failure_reason = "killSwitch"
  7581. if failure_reason:
  7582. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  7583. elif status == "failed" and hms_errors:
  7584. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  7585. await service.update_archive_status(
  7586. archive_id,
  7587. status=status,
  7588. completed_at=(
  7589. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  7590. ),
  7591. failure_reason=failure_reason,
  7592. )
  7593. logger.info(
  7594. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  7595. )
  7596. await ws_manager.send_archive_updated(
  7597. {
  7598. "id": archive_id,
  7599. "status": status,
  7600. }
  7601. )
  7602. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  7603. # MQTT relay - publish archive updated
  7604. try:
  7605. await mqtt_relay.on_archive_updated(
  7606. archive_id=archive_id,
  7607. print_name=filename or subtask_name,
  7608. status=status,
  7609. )
  7610. except Exception:
  7611. pass # Don't fail if MQTT fails
  7612. except Exception as e:
  7613. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  7614. # Continue with other operations even if archive update fails
  7615. log_timing("Archive status update")
  7616. # Apply finance wallet charge or release reservations once. For all partial
  7617. # terminal states (failed, aborted at the printer display, or cancelled via
  7618. # Bambuddy) use this run's measured spool delta, falling back to the last
  7619. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  7620. # estimate and therefore cannot represent an interrupted run.
  7621. try:
  7622. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  7623. async with async_session() as db:
  7624. from backend.app.models.archive import PrintArchive
  7625. from backend.app.services.finance_billing import apply_print_charge_for_archive
  7626. archive = await db.get(PrintArchive, archive_id)
  7627. if archive and billing_run_id is None:
  7628. billing_run_id = getattr(archive, "billing_run_id", None)
  7629. if archive and archive.created_by_id is None and _print_user_info:
  7630. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  7631. await db.flush()
  7632. run_status = data.get("status", "completed")
  7633. last_progress = data.get("last_progress")
  7634. if last_progress is None:
  7635. last_progress = data.get("progress")
  7636. actual_run_grams = _compute_run_filament_grams(
  7637. run_status,
  7638. billing_planned_grams,
  7639. last_progress,
  7640. usage_results,
  7641. )
  7642. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  7643. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  7644. charged = await apply_print_charge_for_archive(
  7645. db,
  7646. archive_id,
  7647. charged_user_id=billing_user_id,
  7648. cost_center_id=(
  7649. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  7650. ),
  7651. print_queue_id=queue_item_id,
  7652. print_run_id=billing_run_id,
  7653. base_cost_override=billing_base_cost,
  7654. filament_usage=filament_usage,
  7655. )
  7656. await db.commit()
  7657. if charged:
  7658. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  7659. except Exception as e:
  7660. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  7661. printer_info = printer_manager.get_printer(printer_id)
  7662. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7663. billing_filename = filename or subtask_name or "Unknown"
  7664. billing_error = str(e)
  7665. try:
  7666. await ws_manager.broadcast(
  7667. {
  7668. "type": "billing_charge_failed",
  7669. "printer_id": printer_id,
  7670. "printer_name": billing_printer_name,
  7671. "filename": billing_filename,
  7672. "archive_id": archive_id,
  7673. }
  7674. )
  7675. except Exception as notification_error:
  7676. logger.error(
  7677. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  7678. archive_id,
  7679. notification_error,
  7680. )
  7681. async def _notify_billing_charge_failed() -> None:
  7682. try:
  7683. async with async_session() as notification_db:
  7684. await notification_service.on_billing_charge_failed(
  7685. printer_id,
  7686. billing_printer_name,
  7687. billing_filename,
  7688. archive_id,
  7689. billing_error,
  7690. notification_db,
  7691. )
  7692. except Exception as provider_error:
  7693. logger.error(
  7694. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  7695. archive_id,
  7696. provider_error,
  7697. exc_info=True,
  7698. )
  7699. spawn_background_task(
  7700. _notify_billing_charge_failed(),
  7701. name=f"billing-charge-failed-{archive_id}",
  7702. )
  7703. log_timing("Finance charge update")
  7704. # Write independent print log entry (separate table, never touches archives)
  7705. try:
  7706. async with async_session() as db:
  7707. from backend.app.models.archive import PrintArchive
  7708. from backend.app.services.print_log import record_archive_wear, write_log_entry
  7709. archive = await db.get(PrintArchive, archive_id)
  7710. if archive:
  7711. # Back-fill created_by_id on reprint (#730): reprint reuses the
  7712. # source archive row rather than creating a new one, so an
  7713. # archive that was auto-created from a printer-initiated
  7714. # print (created_by_id=NULL) would otherwise stay unattributed
  7715. # forever. When we have a print-session user AND the archive
  7716. # has no attribution yet, credit the current user. Never
  7717. # overwrite an existing attribution — the original uploader
  7718. # keeps ownership.
  7719. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  7720. if archive.created_by_id is None and _print_user_id is not None:
  7721. archive.created_by_id = _print_user_id
  7722. p_info = printer_manager.get_printer(printer_id)
  7723. # Per-run actuals — written to PrintLogEntry so stats reflect
  7724. # what THIS print actually used, not the source archive's
  7725. # first-run values (#1378). Helper handles the partial-print
  7726. # math (failed / cancelled / stopped get scaled to progress
  7727. # or to tracked spool deltas).
  7728. _run_status = data.get("status", "completed")
  7729. # #2614: scope the per-run estimate to the printed plate. For a
  7730. # multi-plate 3MF dispatched one plate at a time, the archive's
  7731. # filament/cost are the whole-file totals; the PrintLogEntry must
  7732. # reflect only this plate. No effect on single-plate archives (the
  7733. # plate estimate equals the whole-file value) or on the tracker
  7734. # path (measured spool deltas win in _compute_run_filament_grams).
  7735. _est_full_path = (
  7736. app_settings.base_dir / archive.file_path if archive.file_path else None
  7737. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7738. # The plate that printed, as billing reads it: a reprint of
  7739. # another plate must not log the archive's first plate.
  7740. _est_grams, _est_cost = _plate_scoped_run_estimate(
  7741. archive,
  7742. _est_full_path,
  7743. billing_plate_id if billing_plate_id is not None else notify_plate_id,
  7744. )
  7745. _run_grams = _compute_run_filament_grams(
  7746. _run_status,
  7747. _est_grams,
  7748. data.get("last_progress", data.get("progress")),
  7749. usage_results,
  7750. )
  7751. # Per-run cost — prefer usage_results sum. For partial prints
  7752. # we deliberately skip the topup-to-estimate logic in
  7753. # usage_tracker (which assumes the print completed); the raw
  7754. # tracked-spool sum is closer to what THIS run actually cost.
  7755. _run_cost: float | None = None
  7756. if usage_results:
  7757. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  7758. if _run_cost is None and _run_status != "completed":
  7759. _run_cost = spoolman_run_cost
  7760. if _run_cost is None and _run_status == "completed":
  7761. _run_cost = _est_cost
  7762. from backend.app.models.printer import Printer as _Printer
  7763. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  7764. run_entry = await write_log_entry(
  7765. db,
  7766. archive_id=archive.id,
  7767. # Captured by _update_queue_status above; None for
  7768. # printer-initiated prints with no queue row. Batch
  7769. # cost/energy roll-up joins on it (#342).
  7770. queue_item_id=queue_item_id,
  7771. status=_run_status,
  7772. print_name=archive.print_name,
  7773. printer_name=p_info.name if p_info else None,
  7774. printer_id=printer_id,
  7775. started_at=archive.started_at,
  7776. completed_at=archive.completed_at,
  7777. filament_type=archive.filament_type,
  7778. filament_color=archive.filament_color,
  7779. filament_used_grams=_run_grams,
  7780. cost=_run_cost,
  7781. wear_cost_per_hour=_wear_rate,
  7782. failure_reason=archive.failure_reason,
  7783. thumbnail_path=archive.thumbnail_path,
  7784. created_by_id=archive.created_by_id,
  7785. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  7786. # Reconciled completions have an unknown real end time —
  7787. # log 0 duration instead of the whole disconnect gap (#2592).
  7788. reconciled=bool(data.get("_reconciled")),
  7789. )
  7790. await record_archive_wear(db, archive, run_entry)
  7791. await db.commit()
  7792. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  7793. except Exception as e:
  7794. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  7795. log_timing("Print log entry")
  7796. # Run slow operations as background tasks to avoid blocking the event loop
  7797. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  7798. async def _background_energy_calculation():
  7799. """Calculate and save energy usage in background.
  7800. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  7801. backend restart no longer loses per-print energy data).
  7802. """
  7803. try:
  7804. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  7805. async with async_session() as db:
  7806. from backend.app.models.archive import PrintArchive
  7807. archive = await db.get(PrintArchive, archive_id)
  7808. if archive is None:
  7809. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  7810. return
  7811. starting_kwh = archive.energy_start_kwh
  7812. if starting_kwh is None:
  7813. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  7814. return
  7815. candidates = await energy_plug_candidates(db, printer_id)
  7816. if not candidates:
  7817. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  7818. return
  7819. # Same ordering as the start reading, so the delta below is
  7820. # against the counter that produced `starting_kwh` (#2859).
  7821. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  7822. if selected is None:
  7823. logger.warning(
  7824. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  7825. printer_id,
  7826. ", ".join(plug.name for plug in candidates),
  7827. )
  7828. return
  7829. plug, energy = selected
  7830. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  7831. energy_used = round(energy["total"] - starting_kwh, 4)
  7832. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  7833. if energy_used < 0:
  7834. logger.warning(
  7835. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  7836. archive_id,
  7837. starting_kwh,
  7838. energy["total"],
  7839. )
  7840. return
  7841. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  7842. # Each hour of the print at the price of that hour (#1251). If
  7843. # that fails, the last price known, as before, rather than no
  7844. # energy at all. Read first: the session may be unusable after.
  7845. last_price = await stored_price(db)
  7846. try:
  7847. energy_cost_value = round(
  7848. await print_energy_cost(
  7849. db,
  7850. plug_id=archive.energy_start_plug_id,
  7851. start_at=archive.energy_start_at,
  7852. start_kwh=starting_kwh,
  7853. start_price=archive.energy_start_price,
  7854. end_kwh=energy["total"],
  7855. end_plug_id=plug.id,
  7856. price_now=await current_price(db),
  7857. ),
  7858. 3,
  7859. )
  7860. except Exception as e:
  7861. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  7862. energy_cost_value = round(energy_used * last_price, 3)
  7863. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  7864. # reprint doesn't visually clobber the source archive's energy data
  7865. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  7866. from sqlalchemy import func
  7867. from backend.app.models.print_log import PrintLogEntry
  7868. existing_runs = await db.scalar(
  7869. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  7870. )
  7871. if (existing_runs or 0) <= 1:
  7872. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  7873. # we just wrote for THIS print. Either way it's the first run.
  7874. archive.energy_kwh = energy_used
  7875. archive.energy_cost = energy_cost_value
  7876. # Backfill the latest PrintLogEntry for this archive with energy
  7877. # (write_log_entry above ran before this background task completed,
  7878. # so energy fields are still NULL on that row).
  7879. latest_run = await db.execute(
  7880. select(PrintLogEntry)
  7881. .where(PrintLogEntry.archive_id == archive_id)
  7882. .order_by(PrintLogEntry.id.desc())
  7883. .limit(1)
  7884. )
  7885. run_row = latest_run.scalar_one_or_none()
  7886. if run_row is not None:
  7887. run_row.energy_kwh = energy_used
  7888. run_row.energy_cost = energy_cost_value
  7889. await db.commit()
  7890. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  7891. except Exception as e:
  7892. logger.warning("[ENERGY-BG] Failed: %s", e)
  7893. async def _background_finish_photo() -> str | None:
  7894. """Capture finish photo in background. Returns photo filename if captured."""
  7895. # #2547: set once this function has raised the plate itself (the
  7896. # timelapse path, where the moment producer returned without doing it).
  7897. # Declared out here so the `finally` can lower it again no matter where
  7898. # the capture below fails.
  7899. plate_restored_z: float | None = None
  7900. try:
  7901. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  7902. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  7903. # Read phase: settings + printer + archive in a short session, released
  7904. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  7905. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  7906. # tens of seconds; holding this session across it pinned one pooled
  7907. # connection idle-in-transaction per finishing print (issue #2572).
  7908. async with async_session() as db:
  7909. from backend.app.api.routes.settings import get_setting
  7910. from backend.app.models.archive import PrintArchive
  7911. from backend.app.models.printer import Printer
  7912. capture_enabled = await get_setting(db, "capture_finish_photo")
  7913. if capture_enabled is not None and capture_enabled.lower() != "true":
  7914. return None
  7915. if not archive_id:
  7916. return None
  7917. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  7918. archive = (
  7919. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7920. ).scalar_one_or_none()
  7921. if not printer or not archive:
  7922. return None
  7923. import uuid
  7924. from datetime import datetime
  7925. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  7926. if not archive.file_path:
  7927. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  7928. archive_dir = resolve_archive_dir(archive)
  7929. photo_filename = None
  7930. # Prefer the timelapse last-frame source when a timelapse was
  7931. # recording — it captures the moment after the toolhead parks
  7932. # but before the bed drops, which the live-camera grab below
  7933. # would miss (#1397). Skipped for external cameras (those have
  7934. # their own framing and don't see a Bambu timelapse). Only
  7935. # runs when the USER explicitly enabled timelapse for this
  7936. # print — #1721 removed Bambuddy's force-on at dispatch
  7937. # because it caused per-layer nozzle parking on Smooth-mode
  7938. # slicer profiles.
  7939. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  7940. printer.external_camera_enabled and printer.external_camera_url
  7941. )
  7942. timelapse_still_pending = False
  7943. if prefer_timelapse_source:
  7944. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  7945. archive_id=archive_id,
  7946. archive_dir=archive_dir,
  7947. rotation=getattr(printer, "camera_rotation", 0),
  7948. )
  7949. # #1721: replacement framing path — on_finish_photo_moment
  7950. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  7951. # parked, bed not yet dropped) and cached the JPEG bytes in
  7952. # _stage22_finish_frames. Consume them now so the saved photo
  7953. # has the better framing instead of the post-bed-drop angle
  7954. # the live-camera fallback below would give.
  7955. if not photo_filename:
  7956. # #1790: on the FINISH-state fallback path the producer
  7957. # task is dispatched back-to-back with this consumer, so
  7958. # a bare pop would race past with an empty result and
  7959. # the RTSP fallback below would collide with the
  7960. # producer's still-in-flight grab (single-client RTSP
  7961. # on Bambu printers). Wait for the producer to finish
  7962. # or give up before touching the cache.
  7963. #
  7964. # #2547: 20s was enough when the producer only ever grabbed a
  7965. # frame. It now also raises the plate first, which costs the
  7966. # settle window before the grab even starts — so the budget has
  7967. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  7968. # under the notification's own photo wait below.
  7969. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  7970. if in_flight is not None:
  7971. try:
  7972. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  7973. except TimeoutError:
  7974. logger.warning(
  7975. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  7976. printer_id,
  7977. )
  7978. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  7979. if cached_frame:
  7980. # Already rotated by the producer (#2708) — rotating again
  7981. # here would undo the fix on the banked-frame path, whose
  7982. # bytes reach the cache having been rotated once already.
  7983. photos_dir = archive_dir / "photos"
  7984. photos_dir.mkdir(parents=True, exist_ok=True)
  7985. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7986. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7987. photo_path = photos_dir / photo_filename
  7988. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  7989. logger.info(
  7990. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  7991. photo_filename,
  7992. len(cached_frame),
  7993. )
  7994. # #2547: the timelapse path reaches the live grab below whenever the
  7995. # video hasn't landed in time — the documented usual outcome on
  7996. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  7997. # returned early for those prints without raising the plate, so
  7998. # without this the photo that actually ships in the notification is
  7999. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  8000. # asked us to fix. The archive still gets the better video frame
  8001. # later; this is about the image the user is sent.
  8002. #
  8003. # Gated on `timelapse_was_active` precisely because that is the
  8004. # condition under which the producer skipped. On every other path it
  8005. # has already raised and lowered the plate, and repeating that here
  8006. # would be a second pointless round trip.
  8007. if (
  8008. not photo_filename
  8009. and data.get("timelapse_was_active")
  8010. and not print_dispatch_context.end_gcode_injected(printer_id)
  8011. ):
  8012. try:
  8013. async with async_session() as db:
  8014. from backend.app.api.routes.settings import get_setting
  8015. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  8016. if restore_setting is None or restore_setting.lower() == "true":
  8017. max_z = await _max_z_for_current_print(
  8018. printer_id, data, logger, bound_archive_id, notify_plate_id
  8019. )
  8020. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  8021. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  8022. plate_restored_z = max_z
  8023. except Exception as e:
  8024. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  8025. # Fallback chain: external camera → buffered live frame →
  8026. # fresh RTSP capture. Only runs if the timelapse path above
  8027. # didn't already produce a photo.
  8028. # Chamber light for the live capture below (#1655).
  8029. async with camera_light(printer if not photo_filename else None):
  8030. if not photo_filename:
  8031. if printer.external_camera_enabled and printer.external_camera_url:
  8032. logger.info("[PHOTO-BG] Using external camera")
  8033. from backend.app.api.routes.camera import live_frame_for_capture
  8034. from backend.app.services.external_camera import capture_frame
  8035. # #2707: the second half of the finish-photo failure — the
  8036. # pre-capture and this fallback both collided with the live
  8037. # view. None here continues down the fallback chain.
  8038. defer, buffered = live_frame_for_capture(printer_id)
  8039. if defer:
  8040. frame_data = buffered
  8041. else:
  8042. frame_data = await capture_frame(
  8043. printer.external_camera_url,
  8044. printer.external_camera_type or "mjpeg",
  8045. snapshot_url=printer.external_camera_snapshot_url,
  8046. )
  8047. if frame_data:
  8048. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  8049. photos_dir = archive_dir / "photos"
  8050. photos_dir.mkdir(parents=True, exist_ok=True)
  8051. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8052. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8053. photo_path = photos_dir / photo_filename
  8054. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  8055. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  8056. else:
  8057. # Check if camera stream is active - use buffered frame to avoid freeze
  8058. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  8059. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  8060. active_chamber_for_printer = [
  8061. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  8062. ]
  8063. buffered_frame = get_buffered_frame(printer_id)
  8064. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  8065. # Use frame from active stream
  8066. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  8067. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  8068. photos_dir = archive_dir / "photos"
  8069. photos_dir.mkdir(parents=True, exist_ok=True)
  8070. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8071. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8072. photo_path = photos_dir / photo_filename
  8073. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  8074. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  8075. else:
  8076. # No active stream - capture new frame
  8077. from backend.app.services.camera import capture_finish_photo
  8078. photo_filename = await capture_finish_photo(
  8079. printer_id=printer_id,
  8080. ip_address=printer.ip_address,
  8081. access_code=printer.access_code,
  8082. model=printer.model,
  8083. archive_dir=archive_dir,
  8084. rotation=getattr(printer, "camera_rotation", 0),
  8085. )
  8086. # Write phase: attach the photo in a fresh short-lived session.
  8087. if photo_filename:
  8088. async with async_session() as db:
  8089. from backend.app.models.archive import PrintArchive
  8090. arch = await db.get(PrintArchive, archive_id)
  8091. if arch is not None:
  8092. photos = arch.photos or []
  8093. photos.append(photo_filename)
  8094. arch.photos = photos
  8095. await db.commit()
  8096. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  8097. # The short wait above is bounded so a slow printer can't hold up
  8098. # the print-complete notification, which is what the caller is
  8099. # blocking on. When it ran out with the video still on its way,
  8100. # keep waiting off to the side and add the better frame to the
  8101. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  8102. # users, whose videos routinely take minutes to transfer, never get
  8103. # the pre-bed-drop framing this path exists to provide.
  8104. #
  8105. # Spawned here rather than at the point the wait gave up: both this
  8106. # function and the upgrade do a read-modify-write on `photos`, and
  8107. # the live-camera fallback above can take tens of seconds. Starting
  8108. # the upgrade before that write means the two can interleave and one
  8109. # silently drops the other's entry, leaving a JPEG on disk that the
  8110. # gallery never lists.
  8111. if timelapse_still_pending:
  8112. spawn_background_task(
  8113. _upgrade_finish_photo_from_timelapse(
  8114. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  8115. ),
  8116. name=f"finish-photo-upgrade-{archive_id}",
  8117. )
  8118. return photo_filename
  8119. except Exception as e:
  8120. logger.warning("[PHOTO-BG] Failed: %s", e)
  8121. return None
  8122. finally:
  8123. # #2547: we raised the plate, so we owe the move back down — even if
  8124. # the capture in between threw. Otherwise the user finds the print
  8125. # pinned under the nozzle.
  8126. if plate_restored_z is not None:
  8127. try:
  8128. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  8129. except Exception as e:
  8130. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  8131. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  8132. # Photo capture task - result will be used by notifications
  8133. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  8134. log_timing("Background tasks scheduled (energy, photo)")
  8135. # Also run smart plug, notifications, and maintenance as background tasks
  8136. print_status = data.get("status", "completed")
  8137. async def _background_smart_plug():
  8138. """Handle smart plug automation in background."""
  8139. try:
  8140. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  8141. async with async_session() as db:
  8142. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  8143. logger.info("[AUTO-OFF-BG] Completed")
  8144. except Exception as e:
  8145. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  8146. async def _background_notifications(finish_photo_filename: str | None = None):
  8147. """Send print complete notifications in background."""
  8148. try:
  8149. logger.info(
  8150. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  8151. )
  8152. async with async_session() as db:
  8153. from backend.app.models.archive import PrintArchive
  8154. from backend.app.models.printer import Printer
  8155. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8156. printer = result.scalar_one_or_none()
  8157. printer_name = printer.name if printer else f"Printer {printer_id}"
  8158. archive_data = None
  8159. if archive_id:
  8160. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8161. archive = archive_result.scalar_one_or_none()
  8162. if archive:
  8163. # Actual elapsed time from started_at/completed_at when both are
  8164. # populated (every terminal status sets completed_at after #1198).
  8165. # Falls back to None so the notification path can decide whether to
  8166. # render the slicer estimate as a last resort.
  8167. actual_time_seconds = None
  8168. if archive.started_at and archive.completed_at:
  8169. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  8170. if elapsed > 0:
  8171. actual_time_seconds = int(elapsed)
  8172. archive_data = {
  8173. "print_time_seconds": archive.print_time_seconds,
  8174. "actual_time_seconds": actual_time_seconds,
  8175. "actual_filament_grams": archive.filament_used_grams,
  8176. "failure_reason": archive.failure_reason,
  8177. "created_by_id": archive.created_by_id,
  8178. }
  8179. # Scale filament usage for partial prints
  8180. if print_status != "completed" and archive.filament_used_grams:
  8181. progress = data.get("progress") or 0
  8182. scale = _partial_progress_scale(progress)
  8183. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  8184. archive_data["progress"] = progress
  8185. # Pass per-slot data from archive.extra_data
  8186. if archive.extra_data and archive.extra_data.get("filament_slots"):
  8187. slots = archive.extra_data["filament_slots"]
  8188. if print_status != "completed":
  8189. scale = _partial_progress_scale(data.get("progress"))
  8190. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  8191. archive_data["filament_slots"] = slots
  8192. # Scope project-summed totals down to the plate that was
  8193. # actually printed — see _scope_notification_archive_data_to_plate
  8194. # for the why (#1785).
  8195. archive_data = _scope_notification_archive_data_to_plate(
  8196. archive_data,
  8197. archive.file_path,
  8198. notify_plate_id,
  8199. print_status,
  8200. data.get("progress"),
  8201. app_settings.base_dir,
  8202. )
  8203. # Enrich filament_grams from usage_results when archive has no 3MF data
  8204. if not archive_data.get("actual_filament_grams") and usage_results:
  8205. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8206. if total_from_usage > 0:
  8207. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8208. # Pass usage tracker results for AMS slot info in notifications
  8209. if usage_results:
  8210. archive_data["usage_results"] = usage_results
  8211. # Add finish photo URL and image bytes if available
  8212. if finish_photo_filename:
  8213. photo_url, photo_bytes = await _finish_photo_for_notification(
  8214. db, archive, archive_id, finish_photo_filename
  8215. )
  8216. if photo_url:
  8217. archive_data["finish_photo_url"] = photo_url
  8218. if photo_bytes:
  8219. archive_data["image_data"] = photo_bytes
  8220. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8221. await notification_service.on_print_complete(
  8222. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  8223. )
  8224. else:
  8225. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8226. # Post-print outcome confirmation (#1898). Runs in this
  8227. # background task so the finish photo fetched above rides
  8228. # along with the prompt.
  8229. if print_status == "completed" and archive_id:
  8230. await _dispatch_outcome_confirmation_safely(
  8231. db, printer_id, printer_name, data, archive_id, archive_data
  8232. )
  8233. # Send user-specific email notification
  8234. if archive_data:
  8235. created_by_id = archive_data.get("created_by_id")
  8236. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8237. await _dispatch_user_print_email(
  8238. print_status,
  8239. created_by_id,
  8240. printer_name,
  8241. raw_filename,
  8242. db,
  8243. image_data=archive_data.get("image_data"),
  8244. finish_photo_url=archive_data.get("finish_photo_url"),
  8245. )
  8246. logger.info("[NOTIFY-BG] Completed")
  8247. except Exception as e:
  8248. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  8249. async def _background_maintenance_check():
  8250. """Check for maintenance due in background."""
  8251. if print_status != "completed":
  8252. return
  8253. try:
  8254. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  8255. async with async_session() as db:
  8256. from backend.app.models.printer import Printer
  8257. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8258. printer = result.scalar_one_or_none()
  8259. printer_name = printer.name if printer else f"Printer {printer_id}"
  8260. await ensure_default_types(db)
  8261. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  8262. attention = [
  8263. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  8264. ]
  8265. items_needing_attention = [
  8266. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  8267. for item in attention
  8268. ]
  8269. if items_needing_attention:
  8270. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  8271. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  8272. # MQTT relay - publish maintenance alerts
  8273. for item in attention:
  8274. current_value, threshold, unit = maintenance_alert_values(item)
  8275. try:
  8276. await mqtt_relay.on_maintenance_alert(
  8277. printer_id=printer_id,
  8278. printer_name=printer_name,
  8279. maintenance_type=item.maintenance_type_name,
  8280. current_value=current_value,
  8281. threshold=threshold,
  8282. unit=unit,
  8283. )
  8284. except Exception:
  8285. pass # Don't fail if MQTT fails
  8286. else:
  8287. logger.info("[MAINT-BG] Completed (no items need attention)")
  8288. except Exception as e:
  8289. logger.warning("[MAINT-BG] Failed: %s", e)
  8290. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  8291. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  8292. # Notification task waits for photo capture to complete first (with timeout).
  8293. # When a timelapse was recording, photo sourcing polls the per-print
  8294. # timelapse for up to 60s (#1397) — extend the budget so the notification
  8295. # carries the correct bed-up photo instead of falling through to the
  8296. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  8297. #
  8298. # #2547: both budgets now have to cover a plate restore as well.
  8299. #
  8300. # Without timelapse, the wait is on the moment producer, which raises the
  8301. # plate before its grab — so this has to outlast that producer's own budget.
  8302. #
  8303. # With timelapse, the capture polls up to
  8304. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  8305. # falls back to a live grab, which is the case that raises the plate. At the
  8306. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  8307. # restore would have moved the plate for a photo nobody waited for.
  8308. photo_wait_timeout = (
  8309. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  8310. if data.get("timelapse_was_active")
  8311. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  8312. )
  8313. async def _photo_then_notify():
  8314. """Wait for photo capture, then send notification with photo URL."""
  8315. finish_photo = None
  8316. try:
  8317. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  8318. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  8319. except TimeoutError:
  8320. logger.warning(
  8321. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  8322. photo_wait_timeout,
  8323. )
  8324. except Exception as e:
  8325. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  8326. try:
  8327. await _background_notifications(finish_photo)
  8328. except Exception as e:
  8329. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  8330. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  8331. # Stitch external camera layer timelapse if session was active
  8332. print_status = data.get("status", "completed")
  8333. async def _background_layer_timelapse():
  8334. """Stitch layer timelapse and attach to archive."""
  8335. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  8336. try:
  8337. if print_status == "completed":
  8338. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  8339. timelapse_path = await tl_complete(printer_id)
  8340. if timelapse_path and archive_id:
  8341. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  8342. async with async_session() as db:
  8343. service = ArchiveService(db)
  8344. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  8345. await service.attach_timelapse(
  8346. archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=notify_plate_id
  8347. )
  8348. # Clean up the temp file
  8349. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  8350. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  8351. elif timelapse_path:
  8352. # Timelapse created but no archive - just clean up
  8353. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  8354. else:
  8355. # Print failed or cancelled - cancel timelapse session
  8356. cancel_session(printer_id)
  8357. logger.info(
  8358. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  8359. )
  8360. except Exception as e:
  8361. logger.warning("[LAYER-TL] Failed: %s", e)
  8362. # A completed print's session left _active_sessions when its stitch
  8363. # began: the one there now belongs to the next print, which may have
  8364. # started during the stitch, and must not lose its frames.
  8365. if print_status != "completed":
  8366. try:
  8367. cancel_session(printer_id)
  8368. except Exception:
  8369. pass # Best-effort timelapse session cancellation on error
  8370. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  8371. log_timing("All background tasks scheduled")
  8372. # Auto-scan for timelapse if recording was active during the print
  8373. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  8374. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  8375. # Schedule timelapse scan as background task with retries
  8376. # The printer needs time to encode the video after print completion
  8377. baseline = _timelapse_baselines.pop(printer_id, None)
  8378. spawn_background_task(
  8379. _scan_for_timelapse_with_retries(archive_id, baseline, plate_id=notify_plate_id),
  8380. name=f"scan-timelapse-{archive_id}",
  8381. )
  8382. log_timing("Timelapse scan scheduled")
  8383. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  8384. # AMS sensor history recording
  8385. _ams_history_task: asyncio.Task | None = None
  8386. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  8387. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  8388. def _retention_days(stored: str | None, default: int) -> int:
  8389. """A history retention setting as days to keep: at least 1, the default
  8390. when unset or unreadable. A stored 0 or less (the API took one before it
  8391. had a minimum) would put the cutoff at now and delete all history."""
  8392. try:
  8393. return max(1, int(stored)) if stored is not None else default
  8394. except (TypeError, ValueError):
  8395. return default
  8396. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  8397. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  8398. _ams_alarm_cooldown: dict[str, datetime] = {}
  8399. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  8400. # (printer_id, ams_id) already reported as sending the drop index and no
  8401. # percentage. Logged once each so a supported printer that turns out to do this
  8402. # shows up in a support bundle rather than as a user wondering where the
  8403. # humidity reading went -- see the note at the read site below (#3140).
  8404. _ams_index_only_logged: set[tuple[int, int]] = set()
  8405. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  8406. """Temperature at which the AMS alarm fires, falling back to the display band.
  8407. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  8408. when a notification was sent as well, which is why a room above it made the
  8409. alarm fire once an hour for as long as the weather lasted -- and the only way
  8410. to stop that was to raise the display band and lose the colour that says the
  8411. unit is warm (#2905).
  8412. Unset resolves to the fair threshold, so an install that never sets one is
  8413. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  8414. so that arrives here as a string and is handled by the same branch as any
  8415. other unparseable value -- there is no separate sentinel to keep in sync.
  8416. A non-positive value is refused rather than honoured: zero would alarm
  8417. permanently, and it is far more likely to be a cleared field than a
  8418. deliberate choice.
  8419. """
  8420. if raw_alarm_value is None:
  8421. return fair_threshold
  8422. try:
  8423. value = float(raw_alarm_value)
  8424. except (TypeError, ValueError):
  8425. return fair_threshold
  8426. if not math.isfinite(value) or value <= 0:
  8427. return fair_threshold
  8428. return value
  8429. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  8430. # through a cycle and the cool-down after it (#1802). Stored in the settings
  8431. # table rather than alongside _ams_alarm_cooldown above, because a restart
  8432. # partway through a cool-down would otherwise resume alarming about heat the
  8433. # user asked for — the same internal-timestamp-row pattern as
  8434. # support.py's debug_logging_enabled_at.
  8435. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  8436. # Upper bound on that suppression. The latch normally clears as soon as the unit
  8437. # reads at or below the threshold; see utils.ams_drying for why this cap only
  8438. # matters when it never does.
  8439. AMS_DRYING_GRACE_MINUTES = 120
  8440. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  8441. """Read the persisted per-AMS drying latch, dropping entries out of window.
  8442. Anything older than the grace cap would expire on its next visit anyway, so
  8443. discarding it here costs nothing and stops rows for deleted printers from
  8444. accumulating.
  8445. Stamps ahead of now get two defences, because a box whose clock jumps
  8446. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  8447. ones are discarded outright, and the rest are clamped to now. Without the
  8448. clamp the cap would measure from a moment that has not happened yet and hold
  8449. the alarm quiet for the skew on top of the cap. One unnecessary notification
  8450. after a clock jump is a far better failure than an alarm silently disabled
  8451. for hours.
  8452. """
  8453. from backend.app.models.settings import Settings
  8454. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8455. setting = result.scalar_one_or_none()
  8456. if not setting or not setting.value:
  8457. return {}
  8458. try:
  8459. raw = json.loads(setting.value)
  8460. except (ValueError, TypeError):
  8461. return {} # Corrupted row → no latch, alarms behave as they did before
  8462. if not isinstance(raw, dict):
  8463. return {}
  8464. now = datetime.now(timezone.utc)
  8465. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  8466. latch: dict[str, datetime] = {}
  8467. for key, value in raw.items():
  8468. try:
  8469. stamp = datetime.fromisoformat(str(value))
  8470. except (ValueError, TypeError):
  8471. continue
  8472. if stamp.tzinfo is None:
  8473. stamp = stamp.replace(tzinfo=timezone.utc)
  8474. if not (now - window <= stamp <= now + window):
  8475. continue
  8476. # Nothing may sit in the future: suppression is measured as now minus
  8477. # the stamp, so a stamp ahead of now would extend it by the skew on top
  8478. # of the cap. Clamping the survivors keeps the cap an actual cap.
  8479. latch[str(key)] = min(stamp, now)
  8480. return latch
  8481. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  8482. """Persist the latch, writing only when it actually changed.
  8483. Adds the session change but does not commit — the caller's own commit
  8484. carries it, so the latch lands in the same transaction as the sensor rows
  8485. that produced it.
  8486. """
  8487. from backend.app.models.settings import Settings
  8488. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  8489. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8490. setting = result.scalar_one_or_none()
  8491. if setting is None:
  8492. # Don't create the row on installs that never dry anything.
  8493. if payload != "{}":
  8494. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  8495. elif setting.value != payload:
  8496. setting.value = payload
  8497. def _ams_has_filament(ams_data: dict) -> bool:
  8498. """True if this AMS unit has at least one tray slot holding filament.
  8499. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  8500. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  8501. still report sensor readings, but those readings are ambient and not
  8502. actionable: no filament to dry, no humidity to push down. #1619 — gate
  8503. humidity/temperature alarms on this check so empty units don't generate
  8504. hourly noise. Sensor history still records regardless so the UI charts
  8505. stay continuous.
  8506. Fallback path inspects the `tray` array's `tray_type` fields for setups
  8507. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  8508. """
  8509. bits = ams_data.get("tray_exist_bits")
  8510. if isinstance(bits, str) and bits.strip():
  8511. try:
  8512. return int(bits, 16) > 0
  8513. except ValueError:
  8514. pass
  8515. trays = ams_data.get("tray")
  8516. if isinstance(trays, list):
  8517. return any(
  8518. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  8519. )
  8520. return False
  8521. async def record_ams_history():
  8522. """Background task to record AMS humidity and temperature data."""
  8523. logger = logging.getLogger(__name__)
  8524. # Wait a short time for MQTT connections to establish on startup
  8525. await asyncio.sleep(10)
  8526. while True:
  8527. try:
  8528. from backend.app.models.ams_history import AMSSensorHistory
  8529. from backend.app.models.printer import Printer
  8530. from backend.app.models.settings import Settings
  8531. async with async_session() as db:
  8532. # Get all active printers
  8533. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8534. printers = result.scalars().all()
  8535. # Get alarm thresholds from settings
  8536. humidity_threshold = 60.0 # Default: fair threshold
  8537. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  8538. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  8539. setting = result.scalar_one_or_none()
  8540. if setting:
  8541. try:
  8542. humidity_threshold = float(setting.value)
  8543. except (ValueError, TypeError):
  8544. pass # Keep default threshold if stored value is invalid
  8545. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  8546. setting = result.scalar_one_or_none()
  8547. if setting:
  8548. try:
  8549. temp_fair_threshold = float(setting.value)
  8550. except (ValueError, TypeError):
  8551. pass # Keep default threshold if stored value is invalid
  8552. # The alarm gets its own threshold, seeded from the resolved fair
  8553. # value so an install that has never set one behaves exactly as
  8554. # it did before (#2905). ams_temp_fair decides when the card turns
  8555. # amber; 35 C is a reasonable place to change a colour and not a
  8556. # reasonable place to page someone. A room above it makes the
  8557. # alarm fire once an hour for as long as the weather lasts, and
  8558. # the only way to stop it was to raise the display band and lose
  8559. # the colour that says the unit is warm.
  8560. #
  8561. # An unset value is stored as the literal "None", which the except
  8562. # below swallows the same way it swallows garbage -- so the
  8563. # fallback costs nothing and needs no sentinel of its own.
  8564. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  8565. setting = result.scalar_one_or_none()
  8566. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  8567. temp_fair_threshold, setting.value if setting else None
  8568. )
  8569. # Per-filament humidity threshold overrides (#1605) — resolved
  8570. # per-AMS below from the loaded tray types. Reuses the same
  8571. # resolver as the auto-drying scheduler so behavior stays in
  8572. # lockstep across both consumers.
  8573. from backend.app.services.print_scheduler import PrintScheduler
  8574. per_type_humidity_thresholds: dict[str, int] = {}
  8575. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  8576. setting = result.scalar_one_or_none()
  8577. if setting and setting.value:
  8578. try:
  8579. raw = json.loads(setting.value)
  8580. if isinstance(raw, dict):
  8581. for k, v in raw.items():
  8582. try:
  8583. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  8584. v
  8585. )
  8586. except (TypeError, ValueError):
  8587. continue
  8588. except (ValueError, TypeError):
  8589. pass # Invalid JSON → no overrides, fall through to global threshold
  8590. # Per-AMS drying latch (#1802), loaded once per pass and written
  8591. # back below only if a unit changed it.
  8592. drying_latch = await _load_ams_drying_latch(db)
  8593. drying_latch_before = dict(drying_latch)
  8594. recorded_count = 0
  8595. for printer in printers:
  8596. # Get current state from printer manager
  8597. state = printer_manager.get_status(printer.id)
  8598. if not state or not state.connected or not state.raw_data:
  8599. continue # Skip disconnected printers - don't use stale data
  8600. raw_data = state.raw_data
  8601. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  8602. continue
  8603. # Record data for each AMS unit
  8604. for ams_data in raw_data["ams"]:
  8605. ams_id = int(ams_data.get("id", 0))
  8606. # Percentage only. The 1-5 index is inverted, so
  8607. # charting it as a percentage drew the wettest units as
  8608. # the driest (#3140); a unit that reports no percentage
  8609. # leaves a gap in the chart instead. See
  8610. # utils/ams_humidity.
  8611. humidity = ams_humidity_percent(ams_data)
  8612. # No supported printer is known to send the index
  8613. # alone -- the report came from unsupported firmware,
  8614. # and no install has been seen using the old fallback.
  8615. # "Known" is doing work there, so say so once per unit:
  8616. # the alternative is a silent blank card.
  8617. if humidity is None and ams_data.get("humidity") is not None:
  8618. unit_key = (printer.id, ams_id)
  8619. if unit_key not in _ams_index_only_logged:
  8620. _ams_index_only_logged.add(unit_key)
  8621. logger.info(
  8622. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  8623. "percentage. The index is inverted and is not shown as a percentage "
  8624. "(#3140), so this unit has no humidity reading, chart or alarm. "
  8625. "Please report this with the printer and AMS firmware versions.",
  8626. printer.name,
  8627. ams_id,
  8628. )
  8629. # Get temperature
  8630. temperature = None
  8631. temp_str = ams_data.get("temp")
  8632. if temp_str is not None:
  8633. try:
  8634. temperature = float(temp_str)
  8635. except (ValueError, TypeError):
  8636. pass # Skip unparseable temperature value
  8637. # Skip if no data
  8638. if humidity is None and temperature is None:
  8639. continue
  8640. # Record the data point
  8641. history = AMSSensorHistory(
  8642. printer_id=printer.id,
  8643. ams_id=ams_id,
  8644. humidity=humidity,
  8645. # Both columns hold the same reading now that the
  8646. # index can no longer reach ``humidity``. Writing it
  8647. # through the same value also stops a genuine 0%
  8648. # from being stored as NULL, which the old truthiness
  8649. # test did.
  8650. humidity_raw=humidity,
  8651. temperature=temperature,
  8652. )
  8653. db.add(history)
  8654. recorded_count += 1
  8655. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  8656. is_ams_ht = ams_id >= 128
  8657. if is_ams_ht:
  8658. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  8659. else:
  8660. ams_label = f"AMS-{chr(65 + ams_id)}"
  8661. # Skip alarm dispatch for empty AMS units — humidity /
  8662. # temperature readings are ambient with no filament to
  8663. # protect, and the hourly notification just becomes
  8664. # noise. Sensor history was already recorded above so
  8665. # the UI charts stay continuous (#1619). Per-AMS check
  8666. # so a multi-AMS setup with one loaded + one empty
  8667. # still alarms on the loaded unit.
  8668. if not _ams_has_filament(ams_data):
  8669. continue
  8670. # Resolve per-filament humidity threshold for this AMS
  8671. # unit (#1605). Falls back to the global ams_humidity_fair
  8672. # when no per-type overrides are configured.
  8673. trays = ams_data.get("tray", []) or []
  8674. effective_humidity_threshold = float(
  8675. PrintScheduler.resolve_humidity_threshold(
  8676. trays, per_type_humidity_thresholds, int(humidity_threshold)
  8677. )
  8678. )
  8679. # Check humidity alarm (only if above threshold)
  8680. if humidity is not None and humidity > effective_humidity_threshold:
  8681. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  8682. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8683. now = datetime.now(timezone.utc)
  8684. if (
  8685. last_alarm is None
  8686. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8687. ):
  8688. _ams_alarm_cooldown[cooldown_key] = now
  8689. logger.info(
  8690. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  8691. )
  8692. try:
  8693. # Call different notification method based on AMS type
  8694. if is_ams_ht:
  8695. await notification_service.on_ams_ht_humidity_high(
  8696. printer.id,
  8697. printer.name,
  8698. ams_label,
  8699. humidity,
  8700. effective_humidity_threshold,
  8701. db,
  8702. )
  8703. else:
  8704. await notification_service.on_ams_humidity_high(
  8705. printer.id,
  8706. printer.name,
  8707. ams_label,
  8708. humidity,
  8709. effective_humidity_threshold,
  8710. db,
  8711. )
  8712. except Exception as e:
  8713. logger.warning("Failed to send humidity alarm: %s", e)
  8714. # A drying cycle heats the unit far past ams_temp_fair on
  8715. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  8716. # AMS-HT, against a 35 C default — so the alarm fired
  8717. # once an hour for the whole cycle and kept firing while
  8718. # the unit cooled back down (#1802). Latch on the
  8719. # firmware's own drying state and hold until the reading
  8720. # returns to normal. Humidity is deliberately left alone:
  8721. # it falls during drying, which is the whole point.
  8722. latch_key = f"{printer.id}:{ams_id}"
  8723. # The latch releases at `threshold`, so it takes the alarm
  8724. # number too. Handing it the display band would strand the
  8725. # latch on any unit that settles back above it -- a room
  8726. # where the AMS rests at 37.7 C never returns under a 35 C
  8727. # band, so the latch could only expire on the grace cap
  8728. # rather than releasing when the unit had actually cooled.
  8729. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  8730. drying_active=is_drying_active(ams_data),
  8731. temperature=temperature,
  8732. threshold=temp_alarm_threshold,
  8733. latched_at=drying_latch.get(latch_key),
  8734. now=datetime.now(timezone.utc),
  8735. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  8736. )
  8737. if new_latch is None:
  8738. drying_latch.pop(latch_key, None)
  8739. else:
  8740. drying_latch[latch_key] = new_latch
  8741. # Check temperature alarm (only if above threshold)
  8742. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  8743. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  8744. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8745. now = datetime.now(timezone.utc)
  8746. if (
  8747. last_alarm is None
  8748. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8749. ):
  8750. _ams_alarm_cooldown[cooldown_key] = now
  8751. logger.info(
  8752. f"Sending temperature alarm for {printer.name} {ams_label}: "
  8753. f"{temperature}°C > {temp_alarm_threshold}°C"
  8754. )
  8755. try:
  8756. # Call different notification method based on AMS type
  8757. if is_ams_ht:
  8758. # The reported threshold has to be the one
  8759. # that fired, or the message says "> 35 °C"
  8760. # while firing at 45.
  8761. await notification_service.on_ams_ht_temperature_high(
  8762. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8763. )
  8764. else:
  8765. await notification_service.on_ams_temperature_high(
  8766. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8767. )
  8768. except Exception as e:
  8769. logger.warning("Failed to send temperature alarm: %s", e)
  8770. if drying_latch != drying_latch_before:
  8771. await _save_ams_drying_latch(db, drying_latch)
  8772. await db.commit()
  8773. if recorded_count > 0:
  8774. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  8775. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  8776. global _ams_cleanup_counter
  8777. _ams_cleanup_counter += 1
  8778. if _ams_cleanup_counter >= 288:
  8779. _ams_cleanup_counter = 0
  8780. # Get retention days from settings
  8781. from backend.app.models.settings import Settings
  8782. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  8783. setting = result.scalar_one_or_none()
  8784. retention_days = _retention_days(setting.value if setting else None, AMS_HISTORY_RETENTION_DAYS)
  8785. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8786. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  8787. await db.commit()
  8788. if result.rowcount > 0:
  8789. logger.info(
  8790. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  8791. )
  8792. # Wait until next recording interval
  8793. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  8794. except asyncio.CancelledError:
  8795. break
  8796. except Exception as e:
  8797. logger.warning("AMS history recording failed: %s", e)
  8798. await asyncio.sleep(60) # Wait a bit before retrying
  8799. def start_ams_history_recording():
  8800. """Start the AMS history recording background task."""
  8801. global _ams_history_task
  8802. if _ams_history_task is None:
  8803. _ams_history_task = asyncio.create_task(record_ams_history())
  8804. logging.getLogger(__name__).info("AMS history recording started")
  8805. def stop_ams_history_recording():
  8806. """Stop the AMS history recording background task."""
  8807. global _ams_history_task
  8808. if _ams_history_task:
  8809. _ams_history_task.cancel()
  8810. _ams_history_task = None
  8811. logging.getLogger(__name__).info("AMS history recording stopped")
  8812. # Printer sensor history recording (nozzle / bed / chamber)
  8813. _printer_sensor_history_task: asyncio.Task | None = None
  8814. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  8815. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  8816. _printer_sensor_cleanup_counter = 0
  8817. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  8818. # MQTT parser writes, so we don't need to handle per-model field aliases here
  8819. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  8820. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  8821. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  8822. _SENSOR_TARGET_KEYS = {
  8823. "nozzle": "nozzle_target",
  8824. "nozzle_2": "nozzle_2_target",
  8825. "bed": "bed_target",
  8826. "chamber": "chamber_target",
  8827. }
  8828. async def record_printer_sensor_history():
  8829. """Background task to record nozzle / bed / chamber readings.
  8830. Pulls from `state.temperatures` (already normalised across all printer
  8831. models by the MQTT parser) rather than re-parsing raw_data, so we get
  8832. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  8833. """
  8834. logger = logging.getLogger(__name__)
  8835. await asyncio.sleep(10)
  8836. while True:
  8837. try:
  8838. from backend.app.models.printer import Printer
  8839. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  8840. from backend.app.models.settings import Settings
  8841. async with async_session() as db:
  8842. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8843. printers = result.scalars().all()
  8844. recorded_count = 0
  8845. for printer in printers:
  8846. state = printer_manager.get_status(printer.id)
  8847. if not state or not state.connected:
  8848. continue
  8849. temps = getattr(state, "temperatures", None) or {}
  8850. if not isinstance(temps, dict):
  8851. continue
  8852. for kind in _SENSOR_KINDS:
  8853. if kind not in temps:
  8854. continue
  8855. try:
  8856. value = float(temps[kind])
  8857. except (ValueError, TypeError):
  8858. continue
  8859. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  8860. target_val: float | None = None
  8861. if target_raw is not None:
  8862. try:
  8863. target_val = float(target_raw)
  8864. except (ValueError, TypeError):
  8865. target_val = None
  8866. db.add(
  8867. PrinterSensorHistory(
  8868. printer_id=printer.id,
  8869. sensor_kind=kind,
  8870. value=value,
  8871. target=target_val,
  8872. )
  8873. )
  8874. recorded_count += 1
  8875. await db.commit()
  8876. if recorded_count > 0:
  8877. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  8878. # Periodic cleanup — once every ~24h at this interval.
  8879. global _printer_sensor_cleanup_counter
  8880. _printer_sensor_cleanup_counter += 1
  8881. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  8882. if _printer_sensor_cleanup_counter >= cleanup_every:
  8883. _printer_sensor_cleanup_counter = 0
  8884. result = await db.execute(
  8885. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  8886. )
  8887. setting = result.scalar_one_or_none()
  8888. retention_days = _retention_days(
  8889. setting.value if setting else None, PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  8890. )
  8891. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8892. cleanup = await db.execute(
  8893. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  8894. )
  8895. await db.commit()
  8896. if cleanup.rowcount > 0:
  8897. logger.info(
  8898. "Cleaned up %s old printer sensor history entries (older than %s days)",
  8899. cleanup.rowcount,
  8900. retention_days,
  8901. )
  8902. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  8903. except asyncio.CancelledError:
  8904. break
  8905. except Exception as e:
  8906. logger.warning("Printer sensor history recording failed: %s", e)
  8907. await asyncio.sleep(60)
  8908. def start_printer_sensor_history_recording():
  8909. global _printer_sensor_history_task
  8910. if _printer_sensor_history_task is None:
  8911. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  8912. logging.getLogger(__name__).info("Printer sensor history recording started")
  8913. def stop_printer_sensor_history_recording():
  8914. global _printer_sensor_history_task
  8915. if _printer_sensor_history_task:
  8916. _printer_sensor_history_task.cancel()
  8917. _printer_sensor_history_task = None
  8918. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  8919. # Printer runtime tracking
  8920. _runtime_tracking_task: asyncio.Task | None = None
  8921. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  8922. async def track_printer_runtime():
  8923. """Background task to track printer active runtime (RUNNING state only).
  8924. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  8925. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  8926. which track mechanical wear. Pause time has no motion and no wear, so
  8927. counting it inflates maintenance warnings (#1521).
  8928. """
  8929. logger = logging.getLogger(__name__)
  8930. # Wait for MQTT connections to establish on startup
  8931. await asyncio.sleep(15)
  8932. while True:
  8933. try:
  8934. from backend.app.models.printer import Printer
  8935. # Fetch printer IDs in a short-lived read-only session
  8936. async with async_session() as db:
  8937. result = await db.execute(
  8938. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  8939. Printer.is_active.is_(True)
  8940. )
  8941. )
  8942. printer_rows = result.all()
  8943. now = datetime.now(timezone.utc)
  8944. updated_count = 0
  8945. # Update each printer in its own short session to minimise write-lock
  8946. # hold time and avoid blocking critical commits like queue status
  8947. # updates (#897).
  8948. for pid, pname, runtime_secs, last_update in printer_rows:
  8949. state = printer_manager.get_status(pid)
  8950. if not state:
  8951. logger.debug("[%s] Runtime tracking: no state available", pname)
  8952. continue
  8953. if not state.connected:
  8954. logger.debug("[%s] Runtime tracking: not connected", pname)
  8955. continue
  8956. needs_commit = False
  8957. new_runtime = runtime_secs
  8958. new_last_update = last_update
  8959. if state.state == "RUNNING":
  8960. if last_update:
  8961. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  8962. elapsed = (now - lu).total_seconds()
  8963. if elapsed > 0:
  8964. new_runtime = runtime_secs + int(elapsed)
  8965. updated_count += 1
  8966. needs_commit = True
  8967. logger.debug(
  8968. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  8969. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  8970. )
  8971. else:
  8972. needs_commit = True
  8973. logger.debug("[%s] Runtime tracking: first active detection", pname)
  8974. new_last_update = now
  8975. else:
  8976. if last_update is not None:
  8977. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  8978. new_last_update = None
  8979. needs_commit = True
  8980. if needs_commit:
  8981. try:
  8982. async with async_session() as db:
  8983. result = await db.execute(select(Printer).where(Printer.id == pid))
  8984. printer = result.scalar_one_or_none()
  8985. if printer:
  8986. printer.runtime_seconds = new_runtime
  8987. printer.last_runtime_update = new_last_update
  8988. await db.commit()
  8989. except Exception as e:
  8990. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  8991. if updated_count > 0:
  8992. logger.debug("Updated runtime for %s printer(s)", updated_count)
  8993. except asyncio.CancelledError:
  8994. logger.info("Runtime tracking cancelled")
  8995. break
  8996. except Exception as e:
  8997. logger.warning("Runtime tracking failed: %s", e)
  8998. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  8999. def start_runtime_tracking():
  9000. """Start the printer runtime tracking background task."""
  9001. global _runtime_tracking_task
  9002. if _runtime_tracking_task is None:
  9003. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  9004. logging.getLogger(__name__).info("Printer runtime tracking started")
  9005. def stop_runtime_tracking():
  9006. """Stop the printer runtime tracking background task."""
  9007. global _runtime_tracking_task
  9008. if _runtime_tracking_task:
  9009. _runtime_tracking_task.cancel()
  9010. _runtime_tracking_task = None
  9011. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  9012. # SpoolBuddy device watchdog
  9013. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  9014. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  9015. async def _spoolbuddy_watchdog_loop():
  9016. """Periodic check for SpoolBuddy devices that have gone offline."""
  9017. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  9018. while True:
  9019. try:
  9020. await spoolbuddy_watchdog()
  9021. except asyncio.CancelledError:
  9022. break
  9023. except Exception as e:
  9024. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  9025. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  9026. def start_spoolbuddy_watchdog():
  9027. global _spoolbuddy_watchdog_task
  9028. if _spoolbuddy_watchdog_task is None:
  9029. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  9030. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  9031. def stop_spoolbuddy_watchdog():
  9032. global _spoolbuddy_watchdog_task
  9033. if _spoolbuddy_watchdog_task:
  9034. _spoolbuddy_watchdog_task.cancel()
  9035. _spoolbuddy_watchdog_task = None
  9036. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  9037. # Dead-MQTT-session recovery
  9038. #
  9039. # check_staleness() covers the "connected but silent" half-broken session. It
  9040. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  9041. # is the only thing left watching at that point. When paho stops making
  9042. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  9043. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  9044. # offline with the UI open the whole time, recovered only when something
  9045. # happened to nudge it.
  9046. #
  9047. # This loop is that backstop. It only touches printers that had a working
  9048. # session and lost it, and only when the MQTT port still answers — a printer
  9049. # that is simply switched off is left to paho, since rebuilding a client
  9050. # against an unreachable host achieves nothing and would fill the log every
  9051. # night.
  9052. _connection_watchdog_task: asyncio.Task | None = None
  9053. CONNECTION_WATCHDOG_INTERVAL = 60
  9054. # How long a printer must have been silent before we stop trusting paho.
  9055. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  9056. # so a session that is recovering on its own is never interrupted.
  9057. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  9058. # Per-printer floor between rebuild attempts.
  9059. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  9060. _connection_watchdog_last_attempt: dict[int, float] = {}
  9061. async def _recover_dead_printer_sessions() -> int:
  9062. """Rebuild MQTT clients that have been offline too long to still be trying.
  9063. Returns the number of printers a rebuild was attempted for (for tests and
  9064. for the caller's logging). Never raises: one unreachable printer must not
  9065. stop the sweep for the rest of the farm.
  9066. """
  9067. logger = logging.getLogger(__name__)
  9068. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  9069. now = time.monotonic()
  9070. recovered = 0
  9071. for printer_id, client in list(printer_manager._clients.items()):
  9072. try:
  9073. if client.state.connected:
  9074. _connection_watchdog_last_attempt.pop(printer_id, None)
  9075. continue
  9076. # Time since the last inbound message is the age of the last known
  9077. # good session — no extra bookkeeping needed, and it is the same
  9078. # clock is_stale() reads. 0 means this client has never had one:
  9079. # that is the initial-connect path, where paho retrying is the
  9080. # correct and only behaviour, so leave it be.
  9081. last_msg = client._last_message_time
  9082. if not last_msg:
  9083. continue
  9084. offline_for = time.time() - last_msg
  9085. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  9086. continue
  9087. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  9088. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  9089. continue
  9090. if not await check_port(client.ip_address, PORT_MQTT):
  9091. # Switched off, unplugged, or off the network. Paho's retry is
  9092. # the right handler; say so at debug level and move on.
  9093. logger.debug(
  9094. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  9095. "— leaving the reconnect to paho",
  9096. printer_id,
  9097. offline_for,
  9098. )
  9099. _connection_watchdog_last_attempt[printer_id] = now
  9100. continue
  9101. _connection_watchdog_last_attempt[printer_id] = now
  9102. recovered += 1
  9103. logger.warning(
  9104. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  9105. "rebuilding the client with a fresh session (last connect error: %s)",
  9106. printer_id,
  9107. offline_for,
  9108. PORT_MQTT,
  9109. client.last_connect_error or "none recorded",
  9110. )
  9111. # Async context, so this takes the hard-reset path: fresh client_id,
  9112. # paho's QoS 1 queue dropped. That matters — a project_file left
  9113. # unacked on the dead session would otherwise replay into the new
  9114. # one and trip 0500_4003 on the printer (#1136).
  9115. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  9116. except Exception as e:
  9117. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  9118. return recovered
  9119. async def _connection_watchdog_loop():
  9120. logger = logging.getLogger(__name__)
  9121. # Let the initial connects settle before judging anyone offline.
  9122. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  9123. while True:
  9124. try:
  9125. await _recover_dead_printer_sessions()
  9126. except asyncio.CancelledError:
  9127. break
  9128. except Exception as e:
  9129. logger.warning("Connection watchdog sweep failed: %s", e)
  9130. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  9131. def start_connection_watchdog():
  9132. global _connection_watchdog_task
  9133. if _connection_watchdog_task is None:
  9134. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  9135. logging.getLogger(__name__).info("Printer connection watchdog started")
  9136. def stop_connection_watchdog():
  9137. global _connection_watchdog_task
  9138. if _connection_watchdog_task:
  9139. _connection_watchdog_task.cancel()
  9140. _connection_watchdog_task = None
  9141. _connection_watchdog_last_attempt.clear()
  9142. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  9143. # Camera stream orphan cleanup
  9144. _camera_cleanup_task: asyncio.Task | None = None
  9145. CAMERA_CLEANUP_INTERVAL = 60
  9146. # Every this many camera cleanups (about an hour), the timelapse janitor too:
  9147. # kept frames of a failed stitch go after a day, not at the next restart.
  9148. TIMELAPSE_CLEANUP_EVERY = 60
  9149. async def _camera_cleanup_loop():
  9150. """Periodically clean up orphaned ffmpeg processes and timelapse leftovers."""
  9151. from backend.app.api.routes.camera import cleanup_orphaned_streams
  9152. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9153. rounds = 0
  9154. while True:
  9155. try:
  9156. rounds += 1
  9157. await cleanup_orphaned_streams()
  9158. except asyncio.CancelledError:
  9159. break
  9160. except Exception as e:
  9161. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  9162. try:
  9163. if rounds % TIMELAPSE_CLEANUP_EVERY == 0:
  9164. await asyncio.to_thread(cleanup_orphaned_timelapse_sessions)
  9165. except asyncio.CancelledError:
  9166. break
  9167. except Exception as e:
  9168. logging.getLogger(__name__).warning("Timelapse frames cleanup failed: %s", e)
  9169. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  9170. def start_camera_cleanup():
  9171. global _camera_cleanup_task
  9172. if _camera_cleanup_task is None:
  9173. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  9174. logging.getLogger(__name__).info("Camera stream cleanup started")
  9175. def stop_camera_cleanup():
  9176. global _camera_cleanup_task
  9177. if _camera_cleanup_task:
  9178. _camera_cleanup_task.cancel()
  9179. _camera_cleanup_task = None
  9180. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  9181. # ---------------------------------------------------------------------------
  9182. # Expected-print TTL eviction
  9183. # ---------------------------------------------------------------------------
  9184. def _evict_stale_expected_prints() -> None:
  9185. """Remove entries from _expected_prints / _expected_print_creators that are
  9186. older than _EXPECTED_PRINT_TTL_SECONDS.
  9187. This prevents unbounded growth when a print is registered (via
  9188. register_expected_print) but on_print_start never fires — e.g. because the
  9189. printer disconnects, the app restarts, or the print is started directly from
  9190. the printer panel without going through the queue.
  9191. """
  9192. # Use monotonic time so the TTL is unaffected by system clock adjustments
  9193. # (e.g. NTP sync, DST changes).
  9194. # A print that ended without its archive being found at completion leaves
  9195. # its id here; only running prints are owned.
  9196. _owned_print_archive_ids.intersection_update(_active_prints.values())
  9197. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  9198. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  9199. if not stale_keys:
  9200. return
  9201. evicted_archive_ids: set[int] = set()
  9202. for key in stale_keys:
  9203. archive_id = _expected_prints.pop(key, None)
  9204. if archive_id is not None:
  9205. evicted_archive_ids.add(archive_id)
  9206. _expected_print_creators.pop(key, None)
  9207. _expected_print_registered_at.pop(key, None)
  9208. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  9209. # that have no remaining live keys in _expected_prints (all variants
  9210. # were just evicted) and are not printing right now. Print start pops
  9211. # only the names the printer reported, so the "<base>.gcode" variant
  9212. # outlives it; without the printing check its eviction two hours after
  9213. # dispatch threw away a running print's plate, AMS mapping and cost
  9214. # centre, which completion still reads (#3275).
  9215. live_archive_ids = set(_expected_prints.values()) | set(_active_prints.values())
  9216. for archive_id in evicted_archive_ids:
  9217. if archive_id not in live_archive_ids:
  9218. _print_ams_mappings.pop(archive_id, None)
  9219. _print_cost_center_ids.pop(archive_id, None)
  9220. _print_plate_ids.pop(archive_id, None)
  9221. logging.getLogger(__name__).info(
  9222. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  9223. )
  9224. async def _expected_prints_cleanup_loop() -> None:
  9225. """Background task: periodically evict stale expected-print entries."""
  9226. while True:
  9227. try:
  9228. _evict_stale_expected_prints()
  9229. except asyncio.CancelledError:
  9230. raise
  9231. except Exception as e:
  9232. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  9233. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  9234. def start_expected_prints_cleanup() -> None:
  9235. global _expected_prints_cleanup_task
  9236. if _expected_prints_cleanup_task is None:
  9237. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  9238. logging.getLogger(__name__).info("Expected prints cleanup started")
  9239. def stop_expected_prints_cleanup() -> None:
  9240. global _expected_prints_cleanup_task
  9241. if _expected_prints_cleanup_task:
  9242. _expected_prints_cleanup_task.cancel()
  9243. _expected_prints_cleanup_task = None
  9244. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  9245. # ---------------------------------------------------------------------------
  9246. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  9247. # ---------------------------------------------------------------------------
  9248. _auth_cleanup_task: asyncio.Task | None = None
  9249. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  9250. async def _run_auth_cleanup() -> None:
  9251. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  9252. from backend.app.core.database import async_session
  9253. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  9254. from backend.app.models.user_totp import UserTOTP
  9255. now = datetime.now(timezone.utc)
  9256. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  9257. try:
  9258. async with async_session() as db:
  9259. stale_cutoff = now - timedelta(hours=1)
  9260. result = await db.execute(
  9261. select(UserTOTP).where(
  9262. UserTOTP.is_enabled.is_(False),
  9263. UserTOTP.created_at < stale_cutoff,
  9264. )
  9265. )
  9266. stale_records = result.scalars().all()
  9267. if stale_records:
  9268. for rec in stale_records:
  9269. await db.delete(rec)
  9270. await db.commit()
  9271. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  9272. except Exception as e:
  9273. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  9274. # Remove expired revoked-JTI entries (they are no longer needed once the
  9275. # original token's exp has passed — the token would be rejected by JWT
  9276. # signature verification regardless).
  9277. try:
  9278. async with async_session() as db:
  9279. await db.execute(
  9280. delete(AuthEphemeralToken).where(
  9281. AuthEphemeralToken.token_type == "revoked_jti",
  9282. AuthEphemeralToken.expires_at < now,
  9283. )
  9284. )
  9285. await db.commit()
  9286. except Exception as e:
  9287. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  9288. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  9289. # Events outside this window can never affect rate-limit decisions — they only
  9290. # consume DB space. Use the same window constant as the rate limiter so the
  9291. # two are always in sync.
  9292. try:
  9293. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  9294. async with async_session() as db:
  9295. await db.execute(
  9296. delete(AuthRateLimitEvent).where(
  9297. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  9298. )
  9299. )
  9300. await db.commit()
  9301. except Exception as e:
  9302. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  9303. async def _auth_cleanup_loop() -> None:
  9304. """Periodic background task: run auth cleanup every hour."""
  9305. while True:
  9306. try:
  9307. await _run_auth_cleanup()
  9308. except asyncio.CancelledError:
  9309. break
  9310. except Exception as e:
  9311. logging.warning("Auth cleanup loop error: %s", e)
  9312. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  9313. def start_auth_cleanup() -> None:
  9314. global _auth_cleanup_task
  9315. if _auth_cleanup_task is None:
  9316. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  9317. logging.getLogger(__name__).info("Auth periodic cleanup started")
  9318. def stop_auth_cleanup() -> None:
  9319. global _auth_cleanup_task
  9320. if _auth_cleanup_task:
  9321. _auth_cleanup_task.cancel()
  9322. _auth_cleanup_task = None
  9323. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  9324. @asynccontextmanager
  9325. async def lifespan(app: FastAPI):
  9326. # Startup
  9327. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  9328. # anything else can spawn tasks that might trip it.
  9329. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  9330. install_proactor_reset_filter()
  9331. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  9332. # what turned descriptor exhaustion into a corrupted database (#2883).
  9333. from backend.app.core.fd_limit import raise_open_file_limit
  9334. raise_open_file_limit()
  9335. # Before init_db, so the warning is near the top of the log rather than
  9336. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  9337. warn_if_running_on_uvloop()
  9338. await init_db()
  9339. # Browser download tokens expire after five minutes. Remove abandoned
  9340. # prepared ZIPs at startup as well as before each new preparation so a
  9341. # quiet appliance cannot retain an unusable bundle indefinitely.
  9342. try:
  9343. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  9344. await prune_stale_printer_file_bundles()
  9345. except Exception as exc:
  9346. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  9347. # After migrations, so the is_env_managed column exists. Never raises --
  9348. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  9349. # startup (see apply_env_oidc_provider).
  9350. from backend.app.core.oidc_env import apply_env_oidc_provider
  9351. async with async_session() as oidc_db:
  9352. await apply_env_oidc_provider(oidc_db)
  9353. # Close out batches that finished before `completed` was a reachable status
  9354. # (#342). Without this the Batches tab opens on every batch created since
  9355. # the feature shipped, all still marked active. Never blocks startup.
  9356. try:
  9357. from backend.app.services.print_batch import backfill_batch_statuses
  9358. async with async_session() as batch_db:
  9359. await backfill_batch_statuses(batch_db)
  9360. except Exception as exc:
  9361. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  9362. # Register an app-scoped httpx client for Bambu Cloud services so
  9363. # per-request BambuCloudService instances reuse the same connection pool
  9364. # (important for routes like /cloud/filament-info that chain many
  9365. # get_setting_detail calls). The shared client stores no region/token
  9366. # state, so the per-request ownership pattern that fixed the region-bleed
  9367. # bug is preserved.
  9368. import httpx as _httpx
  9369. from backend.app.services.bambu_cloud import set_shared_http_client
  9370. from backend.app.services.model_providers.makerworld.service import (
  9371. set_shared_http_client as set_shared_makerworld_http_client,
  9372. )
  9373. from backend.app.services.orca_cloud import (
  9374. set_shared_http_client as set_shared_orca_http_client,
  9375. )
  9376. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  9377. set_shared_http_client(_shared_cloud_http_client)
  9378. # Reuse the same connection pool for MakerWorld — different host, same
  9379. # keep-alive pool saves a TLS handshake per request.
  9380. set_shared_makerworld_http_client(_shared_cloud_http_client)
  9381. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  9382. # each spun up (and never closed) its own client, leaking sockets.
  9383. set_shared_orca_http_client(_shared_cloud_http_client)
  9384. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  9385. # This can happen when a print was cancelled mid-print on versions before this fix.
  9386. try:
  9387. async with async_session() as db:
  9388. from backend.app.models.print_queue import PrintQueueItem
  9389. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  9390. aborted_items = result.scalars().all()
  9391. if aborted_items:
  9392. for item in aborted_items:
  9393. item.status = "cancelled"
  9394. await db.commit()
  9395. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  9396. except Exception as e:
  9397. logging.warning("Failed to fix aborted queue items: %s", e)
  9398. # Restore debug logging state from previous session
  9399. await init_debug_logging()
  9400. # Set up printer manager callbacks
  9401. loop = asyncio.get_event_loop()
  9402. printer_manager.set_event_loop(loop)
  9403. printer_manager.set_status_change_callback(on_printer_status_change)
  9404. printer_manager.set_print_start_callback(on_print_start)
  9405. printer_manager.set_print_complete_callback(on_print_complete)
  9406. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  9407. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  9408. printer_manager.set_ams_change_callback(on_ams_change)
  9409. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  9410. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  9411. await printer_manager.load_awaiting_plate_clear_from_db()
  9412. # Layer change callback for external camera timelapse
  9413. async def on_layer_change(printer_id: int, layer_num: int):
  9414. """Capture timelapse frame on layer change + first layer notification."""
  9415. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  9416. await tl_layer_change(printer_id, layer_num)
  9417. # #1867: bank a recent in-print frame so the finish-photo path has a
  9418. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  9419. # #2547 added `on_print_progress` as a second driver — this one alone
  9420. # stops firing once the final layer begins.
  9421. await _maybe_bank_inprint_frame(printer_id, layer_num)
  9422. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  9423. # Gate on actual printing state — Bambu firmware ticks layer_num during
  9424. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  9425. # nozzle clean), so a bare layer_num check can fire minutes before the
  9426. # first real extrusion. We require gcode_state == RUNNING and
  9427. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  9428. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  9429. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  9430. # edge fires later; _first_layer_notified stays clear until we actually send
  9431. # so a deferred re-evaluation can win. See issue #1837.
  9432. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  9433. client = printer_manager.get_client(printer_id)
  9434. state = client.state if client else None
  9435. if not state or state.state != "RUNNING":
  9436. return
  9437. if state.mc_print_sub_stage not in (None, 0):
  9438. return
  9439. _first_layer_notified[printer_id] = True
  9440. try:
  9441. async with async_session() as db:
  9442. from backend.app.models.printer import Printer
  9443. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9444. printer = result.scalar_one_or_none()
  9445. if not printer:
  9446. return
  9447. printer_name = printer.name
  9448. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  9449. total_layers = state.total_layers if state else 0
  9450. image_data = await _capture_snapshot_for_notification(
  9451. printer_id, printer, logging.getLogger(__name__)
  9452. )
  9453. await notification_service.on_first_layer_complete(
  9454. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  9455. )
  9456. except Exception as e:
  9457. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  9458. printer_manager.set_layer_change_callback(on_layer_change)
  9459. async def on_print_progress(printer_id: int, percent: int):
  9460. """#2547: keep the in-print frame bank fresh through the final layer.
  9461. `on_layer_change` stops the moment the last layer starts, which on the
  9462. H2C capture that closed #2547 left the bank stale for the three minutes
  9463. that layer took. Progress is the only field that keeps advancing there,
  9464. and it freezes before the End G-code runs — so banking on it stays
  9465. inside the print and never sees a swapped plate.
  9466. """
  9467. client = printer_manager.get_client(printer_id)
  9468. state = client.state if client else None
  9469. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  9470. printer_manager.set_print_progress_callback(on_print_progress)
  9471. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  9472. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  9473. waiter = _bed_cool_waiters.get(printer_id)
  9474. if not waiter:
  9475. return
  9476. threshold = waiter["threshold"]
  9477. if bed_temp > threshold:
  9478. return
  9479. # Bed is at or below threshold — fire notification and remove waiter
  9480. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  9481. if not waiter_info:
  9482. return # Another callback already handled it
  9483. bed_cool_logger = logging.getLogger(__name__)
  9484. bed_cool_logger.info(
  9485. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  9486. bed_temp,
  9487. printer_id,
  9488. threshold,
  9489. )
  9490. try:
  9491. printer_info = printer_manager.get_printer(printer_id)
  9492. p_name = printer_info.name if printer_info else "Unknown"
  9493. async with async_session() as db:
  9494. await notification_service.on_bed_cooled(
  9495. printer_id=printer_id,
  9496. printer_name=p_name,
  9497. bed_temp=bed_temp,
  9498. threshold=threshold,
  9499. filename=waiter_info["filename"],
  9500. db=db,
  9501. )
  9502. except Exception as e:
  9503. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  9504. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  9505. async def on_drying_complete(printer_id: int, ams_id: int):
  9506. """Smart-plug auto-off-after-drying trigger (#1349).
  9507. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  9508. manager walks all plugs linked to this printer and turns off only
  9509. the ones with ``auto_off_after_drying`` enabled, after their
  9510. per-plug delay. Multiple AMS units finishing close together (e.g. a
  9511. dual-AMS dry that ends within the same MQTT push) call this once
  9512. per unit — the manager's ``_cancel_pending_off`` collapses
  9513. repeated scheduling on the same plug to one timer, so duplicate
  9514. fires are safe.
  9515. """
  9516. try:
  9517. async with async_session() as db:
  9518. await smart_plug_manager.on_drying_complete(printer_id, db)
  9519. except Exception as e:
  9520. logging.getLogger(__name__).warning(
  9521. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  9522. printer_id,
  9523. ams_id,
  9524. e,
  9525. )
  9526. printer_manager.set_drying_complete_callback(on_drying_complete)
  9527. async def on_drying_cycle_end(printer_id: int, cycle):
  9528. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  9529. from backend.app.services.spool_drying import record_drying_cycle
  9530. try:
  9531. async with async_session() as db:
  9532. await record_drying_cycle(db, printer_id, cycle)
  9533. except Exception as e:
  9534. logging.getLogger(__name__).warning(
  9535. "Failed to record drying for printer %d (AMS %d): %s",
  9536. printer_id,
  9537. cycle.ams_id,
  9538. e,
  9539. )
  9540. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  9541. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  9542. """Surface the read-back result of a spool assignment to the UI (#2582).
  9543. The MQTT client confirms (or fails to confirm) that the tray telemetry
  9544. echoed back the filament id we pushed. We relay that as a websocket
  9545. event so the frontend can toast "loaded" / "assignment didn't take"
  9546. instead of the historic silent fire-and-forget, which made the
  9547. AMS→Studio hand-off feel random to users.
  9548. """
  9549. try:
  9550. from backend.app.services.spool_assignment_notifications import (
  9551. _slot_label_from_global_tray,
  9552. )
  9553. if ams_id == 255:
  9554. global_id = 254 + tray_id
  9555. elif ams_id >= 128:
  9556. global_id = ams_id
  9557. else:
  9558. global_id = ams_id * 4 + tray_id
  9559. slot_label = _slot_label_from_global_tray(global_id)
  9560. printer_info = printer_manager.get_printer(printer_id)
  9561. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  9562. await ws_manager.broadcast(
  9563. {
  9564. "type": "spool_assignment_verified",
  9565. "printer_id": printer_id,
  9566. "printer_name": printer_name,
  9567. "ams_id": ams_id,
  9568. "tray_id": tray_id,
  9569. "slot": slot_label,
  9570. "verified": verified,
  9571. # Present on success: False means the filament setting landed
  9572. # but the K-profile (cali_idx) did not — the reporter's exact
  9573. # "loaded but no flow profile" symptom.
  9574. "kprofile_applied": detail.get("kprofile_applied", True),
  9575. # Present on failure: whether any tray telemetry was seen in
  9576. # the window (distinguishes "printer silent" from "printer
  9577. # stored something else").
  9578. "saw_tray": detail.get("saw_tray", False),
  9579. }
  9580. )
  9581. except Exception as e:
  9582. logging.getLogger(__name__).warning(
  9583. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  9584. printer_id,
  9585. ams_id,
  9586. tray_id,
  9587. e,
  9588. )
  9589. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  9590. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  9591. """Persist a mid-print tray change for completion-time attribution.
  9592. AMS filament backup switches trays without telling the slicer, so the
  9593. tray-change log is the only record of which spool fed which layers.
  9594. Keeping it only in memory meant a restart mid-print charged everything
  9595. to the tray that finished the job.
  9596. """
  9597. try:
  9598. from backend.app.services.usage_tracker import record_tray_change
  9599. async with async_session() as db:
  9600. await record_tray_change(db, printer_id, tray_global, layer_num)
  9601. except Exception as e:
  9602. logging.getLogger(__name__).warning(
  9603. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  9604. printer_id,
  9605. tray_global,
  9606. layer_num,
  9607. e,
  9608. )
  9609. printer_manager.set_tray_change_callback(on_tray_change)
  9610. # Initialize MQTT relay from settings
  9611. async with async_session() as db:
  9612. from backend.app.api.routes.settings import get_setting
  9613. mqtt_settings = {
  9614. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  9615. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  9616. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  9617. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  9618. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  9619. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  9620. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  9621. }
  9622. await mqtt_relay.configure(mqtt_settings)
  9623. # Restore MQTT smart plug subscriptions
  9624. if mqtt_settings.get("mqtt_enabled"):
  9625. from backend.app.models.smart_plug import SmartPlug
  9626. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  9627. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  9628. mqtt_plugs = result.scalars().all()
  9629. restored = 0
  9630. for plug in mqtt_plugs:
  9631. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  9632. restored += 1
  9633. if restored:
  9634. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  9635. # Connect to all active printers
  9636. async with async_session() as db:
  9637. await init_printer_connections(db)
  9638. # Auto-connect to Spoolman if enabled
  9639. async with async_session() as db:
  9640. from backend.app.api.routes.settings import get_setting
  9641. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  9642. spoolman_url = await get_setting(db, "spoolman_url")
  9643. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  9644. try:
  9645. client = await init_spoolman_client(spoolman_url)
  9646. if await client.health_check():
  9647. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  9648. # Ensure the 'tag' extra field exists for RFID/UUID storage
  9649. field_ok = await client.ensure_tag_extra_field()
  9650. if not field_ok:
  9651. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  9652. # Register the BambuStudio slicer-preset fields used by the
  9653. # spool-edit / assign flow. Spoolman rejects PATCHes with
  9654. # unknown extra keys, so these must exist before any update
  9655. # that touches them.
  9656. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  9657. if not await client.ensure_extra_field(field_name):
  9658. logging.warning(
  9659. "Spoolman extra field %r registration failed — "
  9660. "spool slicer-preset edits will return 502",
  9661. field_name,
  9662. )
  9663. else:
  9664. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  9665. except Exception as e:
  9666. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  9667. # Start the print scheduler
  9668. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  9669. # Start the smart plug scheduler for time-based on/off
  9670. smart_plug_manager.start_scheduler()
  9671. # Start the Home Assistant sensor poller (#1148)
  9672. ha_sensor_manager.start()
  9673. location_ha_sensor_manager.start()
  9674. # Resume any pending auto-offs that were interrupted by restart
  9675. await smart_plug_manager.resume_pending_auto_offs()
  9676. # Start the notification digest scheduler
  9677. notification_service.start_digest_scheduler()
  9678. notify_live_activities.start()
  9679. notify_widgets.start()
  9680. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  9681. # provider in reactions/both mode; the notification routes resync them.
  9682. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  9683. # until the next provider save, not the whole startup.
  9684. try:
  9685. await telegram_reaction_poller.start()
  9686. except Exception as e:
  9687. logging.warning("Telegram reaction poller did not start: %s", e)
  9688. # Start the GitHub backup scheduler
  9689. await github_backup_service.start_scheduler()
  9690. # Start the local backup scheduler
  9691. await local_backup_service.start_scheduler()
  9692. await obico_detection_service.start()
  9693. # Start the library trash sweeper (#1008)
  9694. await library_trash_service.start_scheduler()
  9695. # Start the archive auto-purge sweeper (#1008 follow-up)
  9696. await archive_purge_service.start_scheduler()
  9697. # Start AMS history recording
  9698. start_ams_history_recording()
  9699. # Start printer sensor (nozzle / bed / chamber) history recording
  9700. start_printer_sensor_history_recording()
  9701. # Start printer runtime tracking
  9702. start_runtime_tracking()
  9703. # Start SpoolBuddy device watchdog
  9704. start_spoolbuddy_watchdog()
  9705. # Start camera stream orphan cleanup
  9706. start_camera_cleanup()
  9707. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  9708. start_connection_watchdog()
  9709. # One-shot sweep for timelapse session directories orphaned by a crash
  9710. # or restart that happened mid-print (in-memory session tracking can't
  9711. # survive that, and nothing else reaps the leftover frames/output file)
  9712. try:
  9713. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9714. removed = cleanup_orphaned_timelapse_sessions()
  9715. if removed:
  9716. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  9717. except Exception as e:
  9718. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  9719. # Start expected-print TTL eviction (prevents memory leak when prints are
  9720. # registered but on_print_start never fires)
  9721. start_expected_prints_cleanup()
  9722. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  9723. start_auth_cleanup()
  9724. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  9725. from backend.app.services import announcements as announcements_service
  9726. announcements_service.start()
  9727. from backend.app.services.printer_media import start_printer_download_cleanup
  9728. start_printer_download_cleanup()
  9729. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  9730. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  9731. from backend.app.services.loop_watchdog import start_loop_watchdog
  9732. start_loop_watchdog()
  9733. # Initialize virtual printer manager and sync from DB
  9734. from backend.app.services.virtual_printer import virtual_printer_manager
  9735. virtual_printer_manager.set_session_factory(async_session)
  9736. virtual_printer_manager.set_printer_manager(printer_manager)
  9737. try:
  9738. await virtual_printer_manager.sync_from_db()
  9739. logging.info("Virtual printer manager synced from database")
  9740. except Exception as e:
  9741. logging.warning("Failed to sync virtual printers: %s", e)
  9742. yield
  9743. # Shutdown
  9744. print_scheduler.stop()
  9745. smart_plug_manager.stop_scheduler()
  9746. ha_sensor_manager.stop()
  9747. location_ha_sensor_manager.stop()
  9748. notification_service.stop_digest_scheduler()
  9749. await notify_live_activities.close()
  9750. await notify_widgets.close()
  9751. await telegram_reaction_poller.aclose()
  9752. github_backup_service.stop_scheduler()
  9753. local_backup_service.stop_scheduler()
  9754. library_trash_service.stop_scheduler()
  9755. archive_purge_service.stop_scheduler()
  9756. obico_detection_service.stop()
  9757. stop_ams_history_recording()
  9758. stop_printer_sensor_history_recording()
  9759. stop_runtime_tracking()
  9760. stop_spoolbuddy_watchdog()
  9761. stop_camera_cleanup()
  9762. stop_connection_watchdog()
  9763. from backend.app.services.loop_watchdog import stop_loop_watchdog
  9764. stop_loop_watchdog()
  9765. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  9766. # cleanly rather than waiting on a queue that nothing will ever fill.
  9767. try:
  9768. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  9769. await shutdown_all_broadcasters()
  9770. except Exception as e:
  9771. logging.warning("Failed to shut down camera broadcasters: %s", e)
  9772. stop_expected_prints_cleanup()
  9773. stop_auth_cleanup()
  9774. from backend.app.services import announcements as announcements_service
  9775. announcements_service.stop()
  9776. from backend.app.services.printer_media import stop_printer_download_cleanup
  9777. await stop_printer_download_cleanup()
  9778. printer_manager.disconnect_all()
  9779. slot_unlink_grace.reset()
  9780. await close_spoolman_client()
  9781. # Stop all virtual printer services
  9782. await virtual_printer_manager.stop_all()
  9783. await mqtt_smart_plug_service.disconnect(timeout=2)
  9784. await mqtt_relay.disconnect(timeout=2)
  9785. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  9786. set_shared_http_client(None)
  9787. set_shared_makerworld_http_client(None)
  9788. set_shared_orca_http_client(None)
  9789. await _shared_cloud_http_client.aclose()
  9790. # Checkpoint WAL (SQLite only) and close all database connections
  9791. from backend.app.core.db_dialect import is_sqlite
  9792. if is_sqlite():
  9793. try:
  9794. async with engine.begin() as conn:
  9795. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  9796. logging.info("WAL checkpoint completed")
  9797. except Exception as e:
  9798. logging.warning("WAL checkpoint failed: %s", e)
  9799. await engine.dispose()
  9800. app = FastAPI(
  9801. title=app_settings.app_name,
  9802. description="Archive and manage Bambu Lab 3MF files",
  9803. version=APP_VERSION,
  9804. lifespan=lifespan,
  9805. )
  9806. # Added first so it sits innermost, next to the routes: a refused header's value
  9807. # (often a stored token) masked in every JSON body. See core.response_redaction.
  9808. app.add_middleware(RefusedHeaderResponseMask)
  9809. def _json_safe(value):
  9810. """The validation errors with every non-finite number written as text."""
  9811. if isinstance(value, float) and not math.isfinite(value):
  9812. return str(value)
  9813. if isinstance(value, dict):
  9814. return {key: _json_safe(item) for key, item in value.items()}
  9815. if isinstance(value, list | tuple):
  9816. return [_json_safe(item) for item in value]
  9817. return value
  9818. @app.exception_handler(RequestValidationError)
  9819. async def _validation_error(_request, exc: RequestValidationError) -> JSONResponse:
  9820. """FastAPI's own 422, except that it survives a non-finite number.
  9821. A body may carry ``Infinity`` or ``NaN`` (Python's JSON reader accepts
  9822. them), and the default handler echoes the input back in its errors,
  9823. which JSON cannot hold: the request ended in an error instead of a 422.
  9824. """
  9825. return JSONResponse(status_code=422, content={"detail": _json_safe(jsonable_encoder(exc.errors()))})
  9826. # =============================================================================
  9827. # Authentication Middleware - Secures ALL API routes by default
  9828. # =============================================================================
  9829. # Public routes that don't require authentication even when auth is enabled
  9830. PUBLIC_API_ROUTES = {
  9831. # Auth routes needed before/during login
  9832. "/api/v1/auth/status",
  9833. "/api/v1/auth/login",
  9834. "/api/v1/auth/setup", # Needed for initial setup and recovery
  9835. # Advanced auth status needed for login page
  9836. "/api/v1/auth/advanced-auth/status",
  9837. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  9838. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  9839. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  9840. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  9841. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  9842. # OIDC routes that must be reachable without a JWT
  9843. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  9844. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  9845. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  9846. # Connected apps: the app's server swaps a code for the user's identity,
  9847. # authenticated by its client secret rather than a login token.
  9848. "/api/v1/connect/token",
  9849. # Version check for updates (no sensitive data)
  9850. "/api/v1/updates/version",
  9851. # Metrics endpoint handles its own prometheus_token authentication
  9852. "/api/v1/metrics",
  9853. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  9854. # this BEFORE a JWT is available to pick up the firstboot wizard's
  9855. # hostname / timezone / locale and the chrony NTP-gate state. The
  9856. # response contains user-set defaults and a public sync flag — no
  9857. # secrets. Without this entry the global auth middleware returns 401
  9858. # before the route handler runs, regardless of the route's own
  9859. # "no auth required" intent.
  9860. "/api/v1/system/appliance",
  9861. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  9862. # authenticates with a long-lived ``camwall``-scoped token in the query
  9863. # string — exactly like the camera streams two lists below, and for the same
  9864. # reason (no header to put a JWT in). "Public" here only means the middleware
  9865. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  9866. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  9867. # plain ``camera_stream`` token does NOT open this door.
  9868. "/api/v1/camwall/printers",
  9869. # Overlay branding: the route enforces overlay-scoped token authentication.
  9870. "/api/v1/overlay-branding/logo",
  9871. }
  9872. # Route prefixes that are public (for routes with dynamic segments)
  9873. PUBLIC_API_PREFIXES = [
  9874. # WebSocket connections handle their own auth
  9875. "/api/v1/ws",
  9876. # OIDC authorize redirects — include provider_id in path
  9877. "/api/v1/auth/oidc/authorize/",
  9878. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  9879. # a phone with no session, so no header can carry a JWT — the single-use
  9880. # capability token in the path IS the credential (same reasoning as the
  9881. # /dl/ slicer downloads below). The route grants nothing beyond writing
  9882. # good/reject on the one archive the token was minted for.
  9883. "/api/v1/archives/confirm/",
  9884. ]
  9885. # Route patterns that are public (read-only display data)
  9886. # These are checked with "in path" - needed because browsers load images/videos
  9887. # via <img src> and <video src> which don't include Authorization headers
  9888. PUBLIC_API_PATTERNS = [
  9889. # Thumbnails
  9890. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  9891. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  9892. # Images and media
  9893. "/photos/", # /archives/{id}/photos/{filename}
  9894. "/project-image/", # /archives/{id}/project-image/{path}
  9895. "/qrcode", # /archives/{id}/qrcode
  9896. "/timelapse", # /archives/{id}/timelapse (video)
  9897. "/cover", # /printers/{id}/cover
  9898. "/icon", # /external-links/{id}/icon
  9899. # Camera (streams loaded via <img> tag)
  9900. "/camera/stream", # /printers/{id}/camera/stream
  9901. "/camera/snapshot", # /printers/{id}/camera/snapshot
  9902. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  9903. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  9904. # string (same reasoning as the camera streams above — no header to carry a
  9905. # JWT). "Public" only means the middleware steps aside; the route still runs
  9906. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  9907. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  9908. "/overlay-status", # /printers/{id}/overlay-status
  9909. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  9910. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  9911. # download token in the URL path instead.
  9912. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  9913. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  9914. # and these patterns match by substring. Without its own entry the middleware
  9915. # 401s the slicer's header-less request before the route's token check runs,
  9916. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  9917. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  9918. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  9919. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  9920. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  9921. ]
  9922. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  9923. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  9924. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  9925. Format: comma-separated list of ``scheme://host[:port]`` origins.
  9926. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  9927. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  9928. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  9929. Invalid entries are dropped with a warning rather than failing startup, so
  9930. a typo in one origin doesn't take the whole deployment down.
  9931. """
  9932. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  9933. if not raw:
  9934. return ()
  9935. valid: list[str] = []
  9936. for item in raw.split(","):
  9937. candidate = item.strip()
  9938. if not candidate:
  9939. continue
  9940. try:
  9941. parsed = urlparse(candidate)
  9942. except ValueError as e:
  9943. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  9944. continue
  9945. if parsed.scheme not in ("http", "https"):
  9946. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  9947. continue
  9948. if not parsed.netloc:
  9949. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  9950. continue
  9951. if parsed.path and parsed.path != "/":
  9952. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  9953. continue
  9954. if parsed.query or parsed.fragment:
  9955. _security_headers_logger.warning(
  9956. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  9957. )
  9958. continue
  9959. if "*" in parsed.netloc:
  9960. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  9961. continue
  9962. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  9963. if valid:
  9964. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  9965. return tuple(valid)
  9966. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  9967. def _frame_ancestors(default_value: str) -> str:
  9968. """Compose the ``frame-ancestors`` CSP directive (#1191).
  9969. ``default_value`` is the strict directive used when the operator has not
  9970. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  9971. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  9972. Settings URL builder's preview). When trusted origins
  9973. are configured, ``'self'`` is always included so same-origin embedding never
  9974. breaks even if an operator forgets to add their own origin to the list.
  9975. """
  9976. if _TRUSTED_FRAME_ORIGINS:
  9977. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  9978. return f"frame-ancestors {default_value};"
  9979. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  9980. # patterns are anchored on the exact emitted name so the relaxed policies
  9981. # below can never apply to any other asset.
  9982. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  9983. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  9984. # -> /assets/pdf.worker.min-<hash>.js
  9985. # Vite also emits a one-line chunk under the second name that only exports the
  9986. # worker's URL. The page imports it as a module, and a module script is run
  9987. # under the importing document's policy, never its own response's, so it
  9988. # matching as well changes nothing.
  9989. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  9990. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  9991. @app.middleware("http")
  9992. async def security_headers_middleware(request, call_next):
  9993. """Add standard HTTP security headers to every response."""
  9994. # Per-request nonce stamped into `script-src` (#1460). On its own this
  9995. # changes nothing for Bambuddy's own pages — index.html has no inline
  9996. # scripts since the SW registration moved to /sw-register.js. The reason
  9997. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  9998. # script injected into the HTML on the edge, with a fresh hash on every
  9999. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  10000. # it clones the same nonce onto its injected <script>, and the inline
  10001. # script passes the policy without us needing 'unsafe-inline'. See
  10002. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  10003. csp_nonce = secrets.token_urlsafe(16)
  10004. # Routes that render their own HTML need it too, or their inline script is
  10005. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  10006. # one that does: it submits its own form so a verdict still costs one tap.
  10007. request.state.csp_nonce = csp_nonce
  10008. response = await call_next(request)
  10009. response.headers["X-Content-Type-Options"] = "nosniff"
  10010. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  10011. # browsers honour CSP frame-ancestors instead, and the legacy
  10012. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  10013. # When operators have explicitly allowlisted trusted frame origins (#1191
  10014. # — typically Home Assistant on a different port), drop X-Frame-Options
  10015. # and let the CSP-side frame-ancestors directive govern embedding.
  10016. if not _TRUSTED_FRAME_ORIGINS:
  10017. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  10018. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  10019. # Content-Security-Policy for the React SPA.
  10020. # Notes:
  10021. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  10022. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  10023. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  10024. # - media-src blob:: timelapse video player uses Blob URLs.
  10025. # - font-src data:: some icon fonts are embedded as data URIs.
  10026. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  10027. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  10028. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  10029. # default CSP would render a blank page.
  10030. response.headers["Content-Security-Policy"] = (
  10031. "default-src 'self'; "
  10032. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  10033. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  10034. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  10035. "connect-src 'self'; "
  10036. "font-src 'self' data: https://fonts.gstatic.com; "
  10037. "worker-src 'self' blob:; "
  10038. "object-src 'none'; "
  10039. "base-uri 'self'; " + _frame_ancestors("'none'")
  10040. )
  10041. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  10042. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  10043. # its emscripten/embind glue generates invoker functions with `new
  10044. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  10045. # worker is governed by the policy delivered with the WORKER SCRIPT's
  10046. # own response — not the document's — so relaxing it here confines
  10047. # eval to that DOM-less worker context. The document policy below
  10048. # stays nonce-strict, and this response header has no effect when the
  10049. # file is merely fetched (a fetch's CSP is enforced against the
  10050. # requesting document, not the resource's own headers).
  10051. response.headers["Content-Security-Policy"] = (
  10052. "default-src 'self'; "
  10053. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  10054. "connect-src 'self'; "
  10055. "object-src 'none'; "
  10056. "base-uri 'self'; " + _frame_ancestors("'none'")
  10057. )
  10058. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  10059. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  10060. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  10061. # rule as the STEP worker above: the policy that governs a dedicated
  10062. # worker is the one delivered with its own script, so the wasm compile
  10063. # has to be permitted here rather than on the document. Unlike the STEP
  10064. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  10065. response.headers["Content-Security-Policy"] = (
  10066. "default-src 'self'; "
  10067. "script-src 'self' 'wasm-unsafe-eval'; "
  10068. "connect-src 'self'; "
  10069. "object-src 'none'; "
  10070. "base-uri 'self'; " + _frame_ancestors("'none'")
  10071. )
  10072. else:
  10073. # The streaming overlay is embedded same-origin by the URL builder's
  10074. # preview in Settings (#1422), so this branch allows 'self'.
  10075. # Embedding from anywhere else is still refused: 'self'
  10076. # only permits a framer on this origin, which is Bambuddy's own UI, so
  10077. # a clickjacking page on another host is blocked exactly as before.
  10078. # (The overlay draws status over a camera feed and its only interactive
  10079. # element is the logo link, so there is nothing to bait a click into
  10080. # even from a same-origin framer.) Cross-origin embedding of the
  10081. # overlay — Home Assistant on another port — remains what
  10082. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  10083. # allowlist in.
  10084. #
  10085. # The connected-app consent page (/connect/authorize) gets the same
  10086. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  10087. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  10088. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  10089. # requires every ancestor to be this origin, so a foreign page -- a
  10090. # sidebar link's site included -- still cannot frame the consent
  10091. # screen to bait a click.
  10092. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  10093. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  10094. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  10095. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  10096. # the policy served with their own script, so each gets it in its own
  10097. # branch above and the document policy stays as strict as it was.
  10098. response.headers["Content-Security-Policy"] = (
  10099. "default-src 'self'; "
  10100. f"script-src 'self' 'nonce-{csp_nonce}'; "
  10101. "style-src 'self' 'unsafe-inline'; "
  10102. "img-src 'self' data: blob:; "
  10103. "media-src 'self' blob:; "
  10104. "connect-src 'self' ws: wss:; "
  10105. "font-src 'self' data:; "
  10106. "object-src 'none'; "
  10107. "base-uri 'self'; "
  10108. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  10109. )
  10110. if request.url.scheme == "https":
  10111. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  10112. return response
  10113. @app.middleware("http")
  10114. async def auth_middleware(request, call_next):
  10115. """Enforce authentication on all API routes when auth is enabled.
  10116. This middleware provides defense-in-depth by checking auth at the API gateway level,
  10117. regardless of whether individual routes have auth dependencies.
  10118. """
  10119. from starlette.responses import JSONResponse
  10120. path = request.url.path
  10121. # Only apply to API routes
  10122. if not path.startswith("/api/"):
  10123. return await call_next(request)
  10124. # Allow public routes
  10125. if path in PUBLIC_API_ROUTES:
  10126. return await call_next(request)
  10127. # Allow public prefixes
  10128. for prefix in PUBLIC_API_PREFIXES:
  10129. if path.startswith(prefix):
  10130. return await call_next(request)
  10131. # Allow public patterns (read-only display data like thumbnails)
  10132. for pattern in PUBLIC_API_PATTERNS:
  10133. if pattern in path:
  10134. return await call_next(request)
  10135. # Check if auth is enabled. Fail CLOSED on any exception during the
  10136. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  10137. # an attacker who could force a DB exception (e.g. file-descriptor
  10138. # exhaustion via login flood) bypass auth on every protected endpoint.
  10139. # Only the probe is guarded: the request itself runs outside the try, so an
  10140. # error in a route surfaces as the 500 it is rather than as an auth outage.
  10141. try:
  10142. async with async_session() as db:
  10143. from backend.app.core.auth import is_auth_enabled
  10144. auth_enabled = await is_auth_enabled(db)
  10145. except Exception:
  10146. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  10147. return JSONResponse(
  10148. status_code=503,
  10149. content={"detail": "Authentication service temporarily unavailable"},
  10150. )
  10151. if not auth_enabled:
  10152. # Auth disabled, allow all requests
  10153. return await call_next(request)
  10154. # Auth is enabled - require valid token
  10155. auth_header = request.headers.get("Authorization")
  10156. x_api_key = request.headers.get("X-API-Key")
  10157. # Check for API key auth first
  10158. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  10159. # API key authentication - let the request through to be validated by route handler
  10160. # API keys are validated per-route since they have different permission levels
  10161. return await call_next(request)
  10162. # Check for JWT auth
  10163. if not auth_header or not auth_header.startswith("Bearer "):
  10164. return JSONResponse(
  10165. status_code=401,
  10166. content={"detail": "Authentication required"},
  10167. headers={"WWW-Authenticate": "Bearer"},
  10168. )
  10169. # Validate JWT token
  10170. import jwt
  10171. try:
  10172. from backend.app.core.auth import (
  10173. ALGORITHM,
  10174. SECRET_KEY,
  10175. _is_token_fresh,
  10176. get_user_by_username,
  10177. is_jti_revoked,
  10178. )
  10179. token = auth_header.replace("Bearer ", "")
  10180. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  10181. username = payload.get("sub")
  10182. if not username:
  10183. raise ValueError("No username in token")
  10184. jti = payload.get("jti")
  10185. if not jti:
  10186. raise ValueError("No jti in token")
  10187. iat = payload.get("iat")
  10188. # Verify user exists, is active, and token is still fresh (L-R8-A).
  10189. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  10190. # this session so the gateway adds a single pooled checkout, not two (#2572).
  10191. async with async_session() as db:
  10192. if await is_jti_revoked(jti, db):
  10193. return JSONResponse(
  10194. status_code=401,
  10195. content={"detail": "Token has been revoked"},
  10196. headers={"WWW-Authenticate": "Bearer"},
  10197. )
  10198. user = await get_user_by_username(db, username)
  10199. if not user or not user.is_active:
  10200. return JSONResponse(
  10201. status_code=401,
  10202. content={"detail": "User not found or inactive"},
  10203. headers={"WWW-Authenticate": "Bearer"},
  10204. )
  10205. if not _is_token_fresh(iat, user):
  10206. return JSONResponse(
  10207. status_code=401,
  10208. content={"detail": "Token no longer valid"},
  10209. headers={"WWW-Authenticate": "Bearer"},
  10210. )
  10211. except jwt.ExpiredSignatureError:
  10212. return JSONResponse(
  10213. status_code=401,
  10214. content={"detail": "Token has expired"},
  10215. headers={"WWW-Authenticate": "Bearer"},
  10216. )
  10217. except (jwt.InvalidTokenError, ValueError):
  10218. return JSONResponse(
  10219. status_code=401,
  10220. content={"detail": "Invalid token"},
  10221. headers={"WWW-Authenticate": "Bearer"},
  10222. )
  10223. except Exception:
  10224. # Not a bad token but a failure checking it (database, pool): refuse,
  10225. # as for the probe above, rather than answer 401 -- the frontend reads
  10226. # a 401 from /auth/me as final and signs the user out.
  10227. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  10228. return JSONResponse(
  10229. status_code=503,
  10230. content={"detail": "Authentication service temporarily unavailable"},
  10231. )
  10232. return await call_next(request)
  10233. @app.middleware("http")
  10234. async def trace_id_middleware(request, call_next):
  10235. """Stamp every HTTP request with a trace ID and echo it back.
  10236. Decorated AFTER auth_middleware on purpose: Starlette stacks
  10237. @app.middleware decorators LIFO, so the last-decorated runs first
  10238. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  10239. which means auth-middleware log lines (and every line emitted on the
  10240. way down to and back from the route handler) all carry the same
  10241. trace ID. If we put it before auth, auth's logs would be stamped
  10242. with the *previous* request's ID — useless for correlation.
  10243. Honours an inbound ``X-Trace-Id`` header so callers running their
  10244. own tracing can correlate their span IDs with our log lines, but
  10245. only if the value passes the whitelist gate in
  10246. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  10247. rejected (too long, contains control chars, etc.) silently triggers
  10248. a freshly minted server-side ID rather than failing the request.
  10249. The minted (or echoed) ID is set on a ContextVar so that every log
  10250. record emitted during the request — application logs *and* uvicorn's
  10251. access log — carries it via TraceIDFilter, and is also written to
  10252. the ``X-Trace-Id`` response header so clients can pin a server-side
  10253. log search to the exact request they made.
  10254. """
  10255. from backend.app.core.trace import (
  10256. generate_trace_id,
  10257. normalise_inbound_trace_id,
  10258. trace_id_var,
  10259. )
  10260. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  10261. trace_id = inbound if inbound is not None else generate_trace_id()
  10262. token = trace_id_var.set(trace_id)
  10263. try:
  10264. response = await call_next(request)
  10265. finally:
  10266. # Reset the ContextVar so a record emitted in a totally
  10267. # unrelated background task that just happens to inherit this
  10268. # context doesn't keep referencing this request's ID forever.
  10269. # In practice ContextVar.reset is best-effort under asyncio
  10270. # task-spawn semantics, but the cost is one attribute write so
  10271. # we may as well do it.
  10272. trace_id_var.reset(token)
  10273. response.headers["X-Trace-Id"] = trace_id
  10274. return response
  10275. # API routes
  10276. app.include_router(auth.router, prefix=app_settings.api_prefix)
  10277. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  10278. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  10279. app.include_router(users.router, prefix=app_settings.api_prefix)
  10280. app.include_router(groups.router, prefix=app_settings.api_prefix)
  10281. app.include_router(printers.router, prefix=app_settings.api_prefix)
  10282. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  10283. app.include_router(archives.router, prefix=app_settings.api_prefix)
  10284. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  10285. app.include_router(finance.router, prefix=app_settings.api_prefix)
  10286. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  10287. app.include_router(labels.router, prefix=app_settings.api_prefix)
  10288. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  10289. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  10290. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  10291. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  10292. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  10293. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  10294. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  10295. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  10296. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  10297. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  10298. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  10299. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  10300. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  10301. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  10302. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  10303. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  10304. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  10305. app.include_router(updates.router, prefix=app_settings.api_prefix)
  10306. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  10307. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  10308. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  10309. app.include_router(camera.router, prefix=app_settings.api_prefix)
  10310. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  10311. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  10312. app.include_router(projects.router, prefix=app_settings.api_prefix)
  10313. app.include_router(library.router, prefix=app_settings.api_prefix)
  10314. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  10315. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  10316. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  10317. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  10318. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  10319. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  10320. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  10321. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  10322. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  10323. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  10324. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  10325. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  10326. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  10327. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  10328. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  10329. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  10330. app.include_router(system.router, prefix=app_settings.api_prefix)
  10331. app.include_router(support.router, prefix=app_settings.api_prefix)
  10332. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  10333. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  10334. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  10335. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  10336. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  10337. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  10338. app.include_router(obico.router, prefix=app_settings.api_prefix)
  10339. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  10340. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  10341. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  10342. # Serve static files (React build)
  10343. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  10344. # Compressed, and cached for good where Vite hashed the name (#3175).
  10345. app.mount(
  10346. "/assets",
  10347. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  10348. name="assets",
  10349. )
  10350. if (app_settings.static_dir / "img").exists():
  10351. app.mount(
  10352. "/img",
  10353. StaticFiles(directory=app_settings.static_dir / "img"),
  10354. name="img",
  10355. )
  10356. if (app_settings.static_dir / "icons").exists():
  10357. app.mount(
  10358. "/icons",
  10359. StaticFiles(directory=app_settings.static_dir / "icons"),
  10360. name="icons",
  10361. )
  10362. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  10363. # falls through to the SPA catch-all and returns index.html, which the
  10364. # browser's font sanitizer rejects ("downloadable font: rejected by
  10365. # sanitizer").
  10366. if (app_settings.static_dir / "fonts").exists():
  10367. app.mount(
  10368. "/fonts",
  10369. StaticFiles(directory=app_settings.static_dir / "fonts"),
  10370. name="fonts",
  10371. )
  10372. @app.get("/")
  10373. async def serve_frontend():
  10374. """Serve the React frontend."""
  10375. index_file = app_settings.static_dir / "index.html"
  10376. if index_file.exists():
  10377. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10378. return {
  10379. "message": "Bambuddy API",
  10380. "docs": "/docs",
  10381. "frontend": "Build and place React app in /static directory",
  10382. }
  10383. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  10384. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  10385. # forever, but the HTML wrapping it is the only file that knows which hash
  10386. # is current. Without explicit cache-control headers Chromium decides
  10387. # heuristically (typically 10% of the time since Last-Modified) and on
  10388. # long-running kiosks happily serves stale HTML across browser restarts.
  10389. # That stale HTML references an old bundle hash, the old bundle is also
  10390. # in the disk cache, and the user ends up running pre-update JS forever
  10391. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  10392. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  10393. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  10394. @app.get("/health")
  10395. async def health_check():
  10396. """Health check endpoint."""
  10397. return {"status": "healthy"}
  10398. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  10399. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  10400. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  10401. # in deployment debugging.
  10402. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  10403. async def serve_manifest():
  10404. """Serve PWA manifest."""
  10405. manifest_file = app_settings.static_dir / "manifest.json"
  10406. if manifest_file.exists():
  10407. return FileResponse(manifest_file, media_type="application/manifest+json")
  10408. return {"error": "Manifest not found"}
  10409. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  10410. async def serve_service_worker():
  10411. """Serve service worker."""
  10412. sw_file = app_settings.static_dir / "sw.js"
  10413. if sw_file.exists():
  10414. return FileResponse(
  10415. sw_file,
  10416. media_type="application/javascript",
  10417. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  10418. )
  10419. return {"error": "Service worker not found"}
  10420. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  10421. async def serve_sw_register():
  10422. """Serve the service-worker registration bootstrap script.
  10423. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  10424. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  10425. """
  10426. reg_file = app_settings.static_dir / "sw-register.js"
  10427. if reg_file.exists():
  10428. return FileResponse(reg_file, media_type="application/javascript")
  10429. return {"error": "sw-register.js not found"}
  10430. # ── GCode viewer static files ────────────────────────────────────────────────
  10431. # Catch-all route for React Router (must be last)
  10432. @app.get("/{full_path:path}")
  10433. async def serve_spa(full_path: str):
  10434. """Serve React app for client-side routing."""
  10435. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  10436. if full_path.startswith("api/"):
  10437. from fastapi import HTTPException
  10438. raise HTTPException(status_code=404, detail="Not found")
  10439. index_file = app_settings.static_dir / "index.html"
  10440. if index_file.exists():
  10441. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10442. return {"error": "Frontend not built"}