main.py 555 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480
  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.responses import FileResponse
  17. from fastapi.staticfiles import StaticFiles
  18. from sqlalchemy import delete, inspect as sa_inspect, or_, select, text, update
  19. from sqlalchemy.exc import IntegrityError
  20. from sqlalchemy.orm.exc import StaleDataError
  21. from backend.app.api.routes import (
  22. ams_history,
  23. announcements,
  24. api_keys,
  25. archive_purge,
  26. archives,
  27. auth,
  28. bug_report,
  29. camera,
  30. camwall,
  31. cloud,
  32. connected_apps,
  33. discovery,
  34. external_links,
  35. filaments,
  36. finance,
  37. firmware,
  38. github_backup,
  39. groups,
  40. ha_sensors,
  41. inventory,
  42. kprofiles,
  43. labels,
  44. library,
  45. library_tags,
  46. library_trash,
  47. library_variants,
  48. local_backup,
  49. local_presets,
  50. location_ha_sensors,
  51. maintenance,
  52. makerworld,
  53. manyfold,
  54. metrics,
  55. mfa,
  56. notification_templates,
  57. notifications,
  58. obico,
  59. orca_cloud,
  60. overlay_branding,
  61. pending_uploads,
  62. pipeline_runs,
  63. print_log,
  64. print_queue,
  65. printer_locations,
  66. printer_sensor_history,
  67. printers,
  68. projects,
  69. scheduled_dryings,
  70. settings as settings_routes,
  71. slice_jobs,
  72. slicer_pipelines,
  73. slicer_presets,
  74. smart_plugs,
  75. sponsor_prompt,
  76. spoolbuddy,
  77. spoolman,
  78. spoolman_inventory,
  79. support,
  80. system,
  81. updates,
  82. user_notifications,
  83. users,
  84. virtual_printers,
  85. webhook,
  86. websocket,
  87. )
  88. from backend.app.api.routes.maintenance import (
  89. _get_printer_maintenance_internal,
  90. ensure_default_types,
  91. maintenance_alert_values,
  92. )
  93. from backend.app.api.routes.support import init_debug_logging
  94. from backend.app.core.config import APP_VERSION, settings as app_settings
  95. from backend.app.core.database import async_session, engine, init_db
  96. from backend.app.core.static_assets import AssetStaticFiles
  97. from backend.app.core.tasks import spawn_background_task
  98. from backend.app.core.websocket import ws_manager
  99. from backend.app.services import kprofile_drift, print_dispatch_context, slot_unlink_grace
  100. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  101. from backend.app.services.archive_cost_estimate import (
  102. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  103. )
  104. from backend.app.services.archive_purge import archive_purge_service
  105. from backend.app.services.bambu_ftp import (
  106. FileNotOnPrinterError,
  107. cache_3mf_download,
  108. clear_3mf_cache,
  109. download_file_async,
  110. download_file_try_paths_async,
  111. ftps_handshake_blocked,
  112. get_cached_3mf,
  113. get_ftp_retry_settings,
  114. normalize_3mf_name,
  115. with_ftp_retry,
  116. )
  117. from backend.app.services.bambu_mqtt import PrinterState
  118. from backend.app.services.camera_light import camera_light
  119. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  120. from backend.app.services.github_backup import github_backup_service
  121. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  122. from backend.app.services.library_trash import library_trash_service
  123. from backend.app.services.local_backup import local_backup_service
  124. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  125. from backend.app.services.mqtt_relay import mqtt_relay
  126. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  127. from backend.app.services.notification_service import notification_service
  128. from backend.app.services.notify_live_activities import notify_live_activities
  129. from backend.app.services.notify_widgets import notify_widgets
  130. from backend.app.services.obico_detection import obico_detection_service
  131. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  132. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  133. from backend.app.services.print_scheduler import scheduler as print_scheduler
  134. from backend.app.services.print_storage import (
  135. REASON_FTP_TRANSFER_FAILED,
  136. REASON_FTPS_COOLOFF,
  137. external_storage_present,
  138. ftp_probe_paths,
  139. print_file_reachable_over_ftp,
  140. )
  141. from backend.app.services.printer_manager import (
  142. init_printer_connections,
  143. parse_plate_id,
  144. printer_manager,
  145. printer_state_to_dict,
  146. resolve_plate_id,
  147. )
  148. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  149. from backend.app.services.slot_nozzle import (
  150. nozzle_diameter_for_extruder,
  151. nozzle_flow_for_extruder,
  152. resolve_slot_nozzle,
  153. )
  154. from backend.app.services.smart_plug_manager import smart_plug_manager
  155. from backend.app.services.spool_assignment_notifications import (
  156. notify_missing_spool_assignments_on_print_start,
  157. )
  158. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  159. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  160. from backend.app.services.spoolman_tracking import (
  161. cleanup_tracking as _cleanup_spoolman_tracking,
  162. report_usage as _report_spoolman_usage,
  163. store_print_data as _store_spoolman_print_data,
  164. )
  165. from backend.app.services.telegram_reactions import telegram_reaction_poller
  166. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  167. from backend.app.utils.ams_humidity import ams_humidity_percent
  168. from backend.app.utils.filament_types import printer_filament_type
  169. from backend.app.utils.fts_routing import extruder_for_inlet
  170. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  171. from backend.app.utils.print_jobs import is_internal_printer_job
  172. # =============================================================================
  173. # Dependency Check - runs before other imports to give helpful error messages
  174. # =============================================================================
  175. def _start_error_server(missing_packages: list):
  176. """Start a minimal HTTP server to display dependency errors in browser."""
  177. import os
  178. import signal
  179. from http.server import BaseHTTPRequestHandler, HTTPServer
  180. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  181. html = f"""<!DOCTYPE html>
  182. <html>
  183. <head>
  184. <title>Bambuddy - Setup Required</title>
  185. <style>
  186. body {{
  187. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  188. background: #0f172a; color: #e2e8f0;
  189. display: flex; justify-content: center; align-items: center;
  190. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  191. }}
  192. .container {{
  193. background: #1e293b; border-radius: 12px; padding: 40px;
  194. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  195. }}
  196. h1 {{ color: #f87171; margin-bottom: 10px; }}
  197. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  198. .packages {{
  199. background: #0f172a; border-radius: 8px; padding: 20px;
  200. margin: 20px 0; text-align: left;
  201. }}
  202. .packages ul {{ margin: 0; padding-left: 20px; }}
  203. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  204. .command {{
  205. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  206. margin: 15px 0; font-family: monospace; color: #4ade80;
  207. text-align: left; overflow-x: auto;
  208. }}
  209. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  210. </style>
  211. </head>
  212. <body>
  213. <div class="container">
  214. <h1>Setup Required</h1>
  215. <h2>Missing Python packages</h2>
  216. <div class="packages"><ul>{packages_html}</ul></div>
  217. <p>To fix, run this command on your server:</p>
  218. <div class="command">pip install -r requirements.lock</div>
  219. <p>Or if using a virtual environment:</p>
  220. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  221. <p class="note">After installing, restart Bambuddy:<br>
  222. <code>sudo systemctl restart bambuddy</code></p>
  223. </div>
  224. </body>
  225. </html>"""
  226. class ErrorHandler(BaseHTTPRequestHandler):
  227. def do_GET(self):
  228. self.send_response(503)
  229. self.send_header("Content-type", "text/html")
  230. self.end_headers()
  231. self.wfile.write(html.encode())
  232. def log_message(self, format, *args):
  233. print(f"[Error Server] {args[0]}")
  234. port = int(os.environ.get("PORT", 8000))
  235. print(f"\nStarting error server on http://0.0.0.0:{port}")
  236. print("Visit this URL in your browser to see the error details.\n")
  237. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  238. def shutdown(signum, frame):
  239. print("\nShutting down error server...")
  240. raise SystemExit(0)
  241. signal.signal(signal.SIGTERM, shutdown)
  242. signal.signal(signal.SIGINT, shutdown)
  243. server.serve_forever()
  244. def check_dependencies():
  245. """Check that all required packages are installed."""
  246. missing = []
  247. # Map of import name -> package name (for pip install)
  248. required = {
  249. "jwt": "PyJWT",
  250. "fastapi": "fastapi",
  251. "uvicorn": "uvicorn",
  252. "sqlalchemy": "sqlalchemy",
  253. "aiosqlite": "aiosqlite",
  254. "pydantic": "pydantic",
  255. "paho.mqtt": "paho-mqtt",
  256. }
  257. for module, package in required.items():
  258. try:
  259. __import__(module)
  260. except ImportError:
  261. missing.append(package)
  262. if missing:
  263. print("\n" + "=" * 60)
  264. print("ERROR: Missing required Python packages!")
  265. print("=" * 60)
  266. print(f"\nMissing packages: {', '.join(missing)}")
  267. print("\nTo fix, run:")
  268. print(" pip install -r requirements.lock")
  269. print("\nOr if using a virtual environment:")
  270. print(" ./venv/bin/pip install -r requirements.lock")
  271. print("=" * 60 + "\n")
  272. _start_error_server(missing)
  273. check_dependencies()
  274. # =============================================================================
  275. # Import settings first for logging configuration
  276. # Configure logging based on settings
  277. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  278. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  279. log_level = getattr(logging, log_level_str, logging.INFO)
  280. # Trace ID column ([-] when no request scope is active — startup, MQTT
  281. # callbacks, scheduled tasks not chained from a request — so the column
  282. # stays visually aligned and missing values are obvious in grep). See
  283. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  284. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  285. # Create root logger
  286. root_logger = logging.getLogger()
  287. root_logger.setLevel(log_level)
  288. # Trace-ID injection: this filter populates record.trace_id from the
  289. # per-request ContextVar so the format string above can reference it.
  290. # Attached to each HANDLER (not the root logger) because Python's
  291. # logging semantics only invoke a logger's filters on records that
  292. # *originated* at that logger — records propagated up from child
  293. # loggers (every named logger in the app) never trigger root's filter.
  294. # Putting it on the handlers means every record any handler emits gets
  295. # trace_id injected just before the formatter runs, regardless of which
  296. # logger created the record. Without this, the formatter raises
  297. # KeyError on every child-logger record and the record is silently
  298. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  299. # partially" bug we hit. See backend/app/core/trace.py for the
  300. # ContextVar the filter reads.
  301. from backend.app.core.trace import TraceIDFilter
  302. _trace_id_filter = TraceIDFilter()
  303. # Console handler - always enabled
  304. console_handler = logging.StreamHandler()
  305. console_handler.setLevel(log_level)
  306. console_handler.setFormatter(logging.Formatter(log_format))
  307. console_handler.addFilter(_trace_id_filter)
  308. root_logger.addHandler(console_handler)
  309. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  310. """Send uvicorn's own loggers to bambuddy.log as well.
  311. Both ship with propagate=False, so the root handler never sees them.
  312. uvicorn.access is the record of which endpoint changed server state;
  313. uvicorn.error is where an unhandled route error is logged with its
  314. traceback ("Exception in ASGI application").
  315. """
  316. for name in ("uvicorn.access", "uvicorn.error"):
  317. logging.getLogger(name).addHandler(handler)
  318. # File handler - only in production or if explicitly enabled
  319. if app_settings.log_to_file:
  320. log_file = app_settings.log_dir / "bambuddy.log"
  321. file_handler = RotatingFileHandler(
  322. log_file,
  323. maxBytes=app_settings.log_max_bytes,
  324. backupCount=app_settings.log_backup_count,
  325. encoding="utf-8",
  326. )
  327. file_handler.setLevel(log_level)
  328. file_handler.setFormatter(logging.Formatter(log_format))
  329. file_handler.addFilter(_trace_id_filter)
  330. root_logger.addHandler(file_handler)
  331. logging.info("Logging to file: %s", log_file)
  332. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  333. # access logger with propagate=False by default, so without this attach
  334. # there is no on-disk record of which endpoint triggered a server-state
  335. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  336. # for exactly this reason. Filtered to write methods only
  337. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  338. # frontend don't churn the rotation window faster than it's useful.
  339. from backend.app.core.logging_filters import (
  340. CancelledPoolNoiseFilter,
  341. WriteRequestsOnlyFilter,
  342. )
  343. _attach_file_handler_to_uvicorn(file_handler)
  344. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  345. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  346. # Uvicorn's access logger has propagate=False (its own default), so the
  347. # root-attached TraceIDFilter never sees these records. Attach a
  348. # second instance directly so HTTP access lines carry the same trace
  349. # ID column as the application logs they correlate with.
  350. uvicorn_access_logger.addFilter(TraceIDFilter())
  351. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  352. # BaseHTTPMiddleware cancelling the inner task scope on client
  353. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  354. # underlying transaction leak; this filter only suppresses the residual
  355. # log records that pre-existing pools still emit during their cleanup.
  356. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  357. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  358. # handler (console included), whether or not file logging is on.
  359. from backend.app.core.logging_filters import QueryTokenRedactFilter # noqa: E402
  360. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  361. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  362. # Reduce noise from third-party libraries in production
  363. if not app_settings.debug:
  364. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  365. logging.getLogger("httpcore").setLevel(logging.WARNING)
  366. logging.getLogger("httpx").setLevel(logging.WARNING)
  367. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  368. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  369. # Track active prints: {(printer_id, filename): archive_id}
  370. _active_prints: dict[tuple[int, str], int] = {}
  371. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  372. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  373. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  374. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  375. # instead of running its own grab-now chain when present, so the finish photo
  376. # captures the better-framed pre-bed-drop moment without us having to force
  377. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  378. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  379. #
  380. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  381. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  382. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  383. # bank and the others are not — so the consumer can't tell them apart and
  384. # must not rotate again.
  385. _stage22_finish_frames: dict[int, bytes] = {}
  386. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  387. # `finally` block (whether it captured a frame or not). The consumer in
  388. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  389. # so the FINISH-state fallback path — where moment and completion are dispatched
  390. # back-to-back — doesn't race past the producer with an empty pop, and the
  391. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  392. # grab (Bambu printers allow only one RTSP client at a time).
  393. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  394. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  395. # layer-change and on print-progress advances (#2547) while the model is still
  396. # printing, then consumed by the FINISH-state finish-photo path when the
  397. # dispatcher recorded that it injected End G-code into this print. Bambu
  398. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  399. # plate-swap) has run, so a live grab there would capture the swapped/empty
  400. # plate.
  401. #
  402. # The load-bearing property: both drivers are print telemetry that stops before
  403. # the End G-code executes — no further layer_num increases, and mc_percent
  404. # freezes — so the last banked frame is always the finished print before the
  405. # swap. Anything added as a third driver must hold that same property.
  406. _inprint_frame_bank: dict[int, bytes] = {}
  407. # Monotonic timestamp of the last banked frame per printer — throttles banking
  408. # so tall prints don't add a camera grab on every layer.
  409. _inprint_frame_bank_ts: dict[int, float] = {}
  410. # Minimum seconds between banked frames, except the final object layer which
  411. # always refreshes for the best framing.
  412. _INPRINT_BANK_MIN_INTERVAL = 25.0
  413. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  414. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  415. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  416. # the first connected status update for that connection; transitions back
  417. # to False whenever we observe `state.connected = False` so the next
  418. # reconnect re-arms reconciliation. Keyed by printer_id.
  419. _printer_reconciled_since_connect: dict[int, bool] = {}
  420. # Same edge, same keying, for priming the printer's calibration table exactly
  421. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  422. # is otherwise filled only when someone opens the Profiles page or Configure
  423. # Slot, when a GitHub backup runs, or when the printer happens to answer
  424. # somebody else's query on the report topic. Until then the AMS slot card has
  425. # no K value to show on the printers whose trays carry none of their own
  426. # (#2854 — H2-series report cali_idx and nothing more).
  427. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  428. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  429. # {(printer_id, filename): archive_id}
  430. _expected_prints: dict[tuple[int, str], int] = {}
  431. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  432. # Used by usage tracker to map 3MF slots to physical AMS trays
  433. _print_ams_mappings: dict[int, list[int]] = {}
  434. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  435. _print_cost_center_ids: dict[int, int] = {}
  436. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  437. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  438. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  439. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  440. # for the queue path. Cleared on print completion or TTL eviction.
  441. _print_plate_ids: dict[int, int] = {}
  442. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  443. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  444. _last_progress_milestone: dict[int, int] = {}
  445. # Track whether first layer complete notification has been sent for current print
  446. _first_layer_notified: dict[int, bool] = {}
  447. # Track whether we already sent a kill-switch stop for the current unauthorized print
  448. _unauthorized_print_kill_sent: set[int] = set()
  449. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  450. # lookup briefly so an unknown active print does not query the database on
  451. # every status frame. A short TTL keeps settings changes responsive.
  452. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  453. _kill_switch_setting_cache: tuple[bool, float] | None = None
  454. # Provider notification started when the kill switch stops a print. The later
  455. # MQTT print-complete callback awaits this task and only sends its regular
  456. # provider notification when the immediate attempt failed.
  457. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  458. # HMS faults already notified, with when each was last seen:
  459. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  460. # fault that flickers beside a held notice was forgotten on every gap and
  461. # notified on every return (#3226). The window is long because the measured
  462. # gaps reach 64 s.
  463. _notified_hms_errors: dict[int, dict[str, float]] = {}
  464. _HMS_CLEAR_GRACE_SECONDS = 600.0
  465. # The print state each printer was last seen in, and the faults recorded before
  466. # it last changed, which are forgotten as soon as they are gone (see
  467. # _take_new_hms_faults).
  468. _hms_print_state: dict[int, str] = {}
  469. _hms_forget_when_gone: dict[int, set[str]] = {}
  470. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  471. # Used for snapshot-diff detection at print completion
  472. _timelapse_baselines: dict[int, set[str]] = {}
  473. # Track printers waiting for bed to cool after print completion.
  474. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  475. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  476. _bed_cool_waiters: dict[int, dict] = {}
  477. # Track printers where the user explicitly stopped the print from the queue UI.
  478. # When on_print_complete fires with status "failed" for these printers we treat it
  479. # as "cancelled" (stopped by user) so the correct notification email is sent.
  480. _user_stopped_printers: set[int] = set()
  481. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  482. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  483. # holds the previous observation so we only fire on the True → False edge (a
  484. # False → False repeat doesn't notify; an initial False at startup doesn't
  485. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  486. # holds the per-printer pending asyncio task that fires the notification
  487. # after a debounce window — cancelled if the printer reconnects before the
  488. # window elapses, so transient MQTT blips don't flood the user.
  489. _printer_last_connected: dict[int, bool] = {}
  490. # Printers whose relay offline event went out, so the reconnect publishes the
  491. # matching online event and a blip shorter than the debounce publishes neither.
  492. _printer_offline_published: set[int] = set()
  493. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  494. # Debounce: a printer must stay offline this long before we notify. Sized
  495. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  496. # so a single stale-trigger cooldown isn't enough to fire — only a real
  497. # offline that survives one reconnect attempt notifies.
  498. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  499. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  500. # when status="failed" to label the print's failure_reason in archives.
  501. #
  502. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  503. # which is wrong on two counts:
  504. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  505. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  506. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  507. # the public wiki) as part of its user-cancel sequence. Matching on the module
  508. # alone caused user-cancellations to be archived as "Layer shift" failures.
  509. # We now match by full short code only — anything not in this map leaves
  510. # failure_reason=None rather than guessing.
  511. # Values are the canonical camelCase failure-reason keys, NOT display labels
  512. # (issue #2974). The vocabulary is enforced on writes by
  513. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  514. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  515. # Statistics breakdown. Storing a label here instead put a second spelling of
  516. # the same cause into one column: the Failure Analysis widget groups on the raw
  517. # value, so a print the backend classified and an identical one a user
  518. # classified counted as two different reasons, and the label form could never
  519. # be translated because there was no key for ``t()`` to resolve.
  520. _HMS_FAILURE_REASONS: dict[str, str] = {
  521. # Layer shift / step loss
  522. "0300_4057": "layerShift",
  523. "0300_4068": "layerShift",
  524. "0300_800C": "layerShift",
  525. # Filament runout (printer-side & per-AMS-slot)
  526. "0300_8004": "filamentRunout",
  527. "0700_8011": "filamentRunout",
  528. "0701_8011": "filamentRunout",
  529. "0702_8011": "filamentRunout",
  530. "0703_8011": "filamentRunout",
  531. "0704_8011": "filamentRunout",
  532. "0705_8011": "filamentRunout",
  533. "0706_8011": "filamentRunout",
  534. "0707_8011": "filamentRunout",
  535. "07FF_8011": "filamentRunout",
  536. # Clogged nozzle / extruder
  537. "0300_4006": "cloggedNozzle",
  538. "0300_8016": "cloggedNozzle",
  539. "0300_801C": "cloggedNozzle",
  540. "0700_8003": "cloggedNozzle",
  541. "0700_8007": "cloggedNozzle",
  542. "0700_8013": "cloggedNozzle",
  543. "0701_8003": "cloggedNozzle",
  544. "0701_8007": "cloggedNozzle",
  545. "0701_8013": "cloggedNozzle",
  546. "0702_8003": "cloggedNozzle",
  547. # AI print monitoring — spaghetti / the model coming off the plate.
  548. # `spaghettiDetached` is a key the archive editor already offers for this
  549. # failure mode, not a new one, so a derived reason opens the dropdown on
  550. # that option rather than blank — and survives the next save, which clears
  551. # any value the editor does not recognise.
  552. #
  553. # A module-0x0C row is safe here despite the warning above: that warning is
  554. # about matching on the module alone, and 0C00_8042 is a full short code
  555. # with a documented meaning ("The AI print monitor has detected a spaghetti
  556. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  557. # cannot collide.
  558. #
  559. # 0300_8003's own text ends "before continuing your print", but on an X2D
  560. # it arrives with the print already paused, offering only
  561. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  562. #
  563. # Two neighbours are left out on purpose, so this does not get re-derived:
  564. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  565. # reads as a warning about a print that is still running, not a halt.
  566. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  567. # the waste chute. That is not the print failing.
  568. #
  569. # That line is drawn from the text, not from `severity`, because severity
  570. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  571. # module/error word with no level in it, and bambu_mqtt.py gives every
  572. # print_error entry a flat severity=3. Matching on the short code alone is
  573. # the right shape for derive_failure_reason, not an omission.
  574. "0300_8003": "spaghettiDetached",
  575. "0C00_8042": "spaghettiDetached",
  576. }
  577. def _hms_short_code(attr: int, code: int | str) -> str:
  578. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  579. if isinstance(code, str):
  580. code_int = int(code.replace("0x", ""), 16) if code else 0
  581. else:
  582. code_int = int(code or 0)
  583. attr_int = int(attr or 0)
  584. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  585. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  586. """Derive the failure_reason key for an archived print.
  587. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  588. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  589. no HMS code matches (don't guess — null is honest). The keys are the
  590. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  591. translated at render time.
  592. """
  593. if status in ("aborted", "cancelled"):
  594. return "userCancelled"
  595. if status != "failed":
  596. return None
  597. for err in hms_errors or []:
  598. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  599. if short_code in _HMS_FAILURE_REASONS:
  600. return _HMS_FAILURE_REASONS[short_code]
  601. return None
  602. # Track created_by_id for expected prints so the user email can be sent even when
  603. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  604. # {(printer_id, filename): created_by_id}
  605. _expected_print_creators: dict[tuple[int, str], int] = {}
  606. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  607. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  608. # updates for the same printer in quick succession (~30 ms apart, observed in
  609. # the wild on H2D + dual AMS).
  610. #
  611. # Without this serialisation, two concurrent on_ams_change callbacks each read
  612. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  613. # the second commit hits
  614. # IntegrityError: duplicate key value violates unique constraint
  615. # "spool_assignment_printer_id_ams_id_tray_id_key"
  616. # SQLite's WAL serial-write semantics had been silently swallowing the race
  617. # until optional Postgres support landed (asyncpg allows true concurrent
  618. # transactions and surfaces the constraint violation).
  619. #
  620. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  621. # assign) are inside the lock. The Spoolman sync block further down stays
  622. # concurrent because it's network-bound and idempotent.
  623. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  624. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  625. """Return the per-printer assignment lock, creating it on first use."""
  626. lock = _ams_assignment_locks.get(printer_id)
  627. if lock is None:
  628. lock = asyncio.Lock()
  629. _ams_assignment_locks[printer_id] = lock
  630. return lock
  631. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  632. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  633. # tag tuple changes for the slot. Cleared when the slot is reported empty
  634. # so remove + reinsert reliably re-prompts the UI.
  635. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  636. async def _broadcast_unknown_tag(
  637. *,
  638. printer_id: int,
  639. ams_id: int,
  640. tray_id: int,
  641. tag_uid: str,
  642. tray_uuid: str,
  643. tray_type: str | None = None,
  644. tray_color: str | None = None,
  645. tray_sub_brands: str | None = None,
  646. tray_count: int | None = None,
  647. ) -> None:
  648. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  649. _logger = logging.getLogger(__name__)
  650. slot_key = (ams_id, tray_id)
  651. tag_key = (tag_uid or "", tray_uuid or "")
  652. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  653. if per_printer.get(slot_key) == tag_key:
  654. _logger.debug(
  655. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  656. printer_id,
  657. ams_id,
  658. tray_id,
  659. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  660. )
  661. return
  662. _logger.info(
  663. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  664. printer_id,
  665. ams_id,
  666. tray_id,
  667. tray_type,
  668. tray_color,
  669. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  670. )
  671. # Broadcast first; only commit the dedup if the WS write succeeds.
  672. # If broadcast raises, the next MQTT push retries instead of being
  673. # permanently silenced by a poisoned dedup entry.
  674. await ws_manager.broadcast(
  675. {
  676. "type": "unknown_tag",
  677. "printer_id": printer_id,
  678. "ams_id": ams_id,
  679. "tray_id": tray_id,
  680. "tag_uid": tag_uid,
  681. "tray_uuid": tray_uuid,
  682. "tray_type": tray_type,
  683. "tray_color": tray_color,
  684. "tray_sub_brands": tray_sub_brands,
  685. "tray_count": tray_count,
  686. }
  687. )
  688. per_printer[slot_key] = tag_key
  689. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  690. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  691. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  692. if per_printer is None:
  693. return
  694. per_printer.pop((ams_id, tray_id), None)
  695. # TTL for expected-print entries: evict registrations older than this to prevent
  696. # unbounded growth when a print is registered but never starts (e.g. printer
  697. # disconnect, app restart, print started from the printer panel).
  698. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  699. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  700. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  701. # Cleanup loop interval
  702. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  703. _expected_prints_cleanup_task: asyncio.Task | None = None
  704. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  705. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  706. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  707. possible_keys: list[tuple[int, str]] = []
  708. filename = (state.gcode_file or state.current_print or "").strip()
  709. subtask_name = (state.subtask_name or "").strip()
  710. if subtask_name:
  711. possible_keys.append((printer_id, subtask_name))
  712. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  713. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  714. if filename:
  715. base_name = filename.rsplit("/", 1)[-1]
  716. if base_name.endswith(".gcode.3mf"):
  717. root_name = base_name[: -len(".gcode.3mf")]
  718. possible_keys.append((printer_id, root_name))
  719. possible_keys.append((printer_id, base_name))
  720. possible_keys.append((printer_id, f"{root_name}.gcode"))
  721. possible_keys.append((printer_id, f"{root_name}.3mf"))
  722. elif base_name.endswith(".3mf"):
  723. root_name = base_name[: -len(".3mf")]
  724. possible_keys.append((printer_id, root_name))
  725. possible_keys.append((printer_id, base_name))
  726. elif base_name.endswith(".gcode"):
  727. root_name = base_name[: -len(".gcode")]
  728. possible_keys.append((printer_id, root_name))
  729. possible_keys.append((printer_id, f"{root_name}.3mf"))
  730. possible_keys.append((printer_id, base_name))
  731. else:
  732. possible_keys.append((printer_id, base_name))
  733. possible_keys.append((printer_id, f"{base_name}.3mf"))
  734. return possible_keys
  735. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  736. """The id of who started the print, unless that user has been deleted since.
  737. Deleting a user forgets them in printer_manager, but a print that ended a
  738. moment before still holds them.
  739. """
  740. if not print_user or print_user.get("user_id") is None:
  741. return None
  742. from backend.app.models.user import User
  743. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  744. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  745. """Check the cheap, process-local print ownership signals."""
  746. if printer_manager.get_current_print_user(printer_id):
  747. return True
  748. return any(key in _expected_prints or key in _active_prints for key in _build_status_print_keys(printer_id, state))
  749. async def _is_printer_kill_switch_enabled_cached() -> bool:
  750. """Return the kill-switch setting without querying on every MQTT frame."""
  751. global _kill_switch_setting_cache
  752. now = time.monotonic()
  753. if _kill_switch_setting_cache is not None:
  754. enabled, expires_at = _kill_switch_setting_cache
  755. if now < expires_at:
  756. return enabled
  757. async with async_session() as db:
  758. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  759. enabled = await is_printer_kill_switch_enabled(db)
  760. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  761. return enabled
  762. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  763. """Resolve whether the current print was started by Bambuddy.
  764. ``None`` means identity is not yet safe to decide. The kill switch must
  765. defer in that case: stopping a print is irreversible, and the first status
  766. frames after a restart may arrive before all subtask fields are populated.
  767. """
  768. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  769. return True
  770. possible_keys = _build_status_print_keys(printer_id, state)
  771. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  772. # is on disk. subtask_id is minted per print and pins the answer to the job
  773. # actually running, rather than to an unrelated one that reuses a filename.
  774. raw_subtask_id = getattr(state, "subtask_id", None)
  775. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  776. if subtask_id in ("", "0"):
  777. return None
  778. from backend.app.models.archive import PrintArchive
  779. result = await db.execute(
  780. select(PrintArchive)
  781. .where(
  782. PrintArchive.printer_id == printer_id,
  783. PrintArchive.status == "printing",
  784. PrintArchive.subtask_id == subtask_id,
  785. )
  786. .order_by(PrintArchive.created_at.desc())
  787. .limit(1)
  788. )
  789. archive = result.scalar_one_or_none()
  790. # An archive row on its own proves nothing: `on_print_start` archives every
  791. # print it observes, including ones started from Bambu Studio or Handy, and
  792. # stamps them with the same status and subtask_id. Authorizing on its mere
  793. # existence would disable the kill switch the moment the 3MF finishes
  794. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  795. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  796. # (carried over from the queue item that started it).
  797. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  798. # Rehydrate the fast in-memory path for subsequent status frames. Include
  799. # both the archive filename and every normalized key reported by MQTT.
  800. _active_prints[(printer_id, archive.filename)] = archive.id
  801. for key in possible_keys:
  802. _active_prints[key] = archive.id
  803. return True
  804. # No dispatch marker. Before calling this someone else's print, check whether
  805. # Bambuddy has a job of its own running on this printer: a library-file
  806. # dispatch has no archive at send time, and an archive created seconds later
  807. # by `on_print_start` carries neither marker. The queue row, which the
  808. # scheduler commits to status="printing" before the MQTT send, is the one
  809. # durable record every Bambuddy print has. It cannot be tied to this
  810. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  811. # print is irreversible, and refusing to act costs nothing but a log line.
  812. from backend.app.models.print_queue import PrintQueueItem
  813. dispatched_here = await db.scalar(
  814. select(PrintQueueItem.id)
  815. .where(
  816. PrintQueueItem.printer_id == printer_id,
  817. PrintQueueItem.status == "printing",
  818. )
  819. .limit(1)
  820. )
  821. if dispatched_here is not None:
  822. return None
  823. return False
  824. async def _send_kill_switch_provider_notification(
  825. printer_id: int,
  826. printer_name: str,
  827. data: dict,
  828. ) -> bool:
  829. """Send the immediate print-stopped provider notification.
  830. Returning a success flag lets the normal MQTT completion path retry when
  831. this early notification could not be delivered.
  832. """
  833. logger = logging.getLogger(__name__)
  834. try:
  835. async with async_session() as db:
  836. await notification_service.on_print_complete(
  837. printer_id,
  838. printer_name,
  839. "stopped",
  840. data,
  841. db,
  842. )
  843. return True
  844. except Exception as e:
  845. logger.warning(
  846. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  847. printer_id,
  848. e,
  849. )
  850. return False
  851. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  852. """Wait for an immediate kill-switch notification, if one was scheduled."""
  853. if task is None:
  854. return False
  855. try:
  856. return await task
  857. except Exception as e:
  858. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  859. return False
  860. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  861. """Capture the smart plug lifetime counter on the archive at print start.
  862. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  863. tracking survives a backend restart mid-print. The print-end handler reads
  864. this value back from the DB and computes the delta against the current
  865. plug counter.
  866. """
  867. _logger = logging.getLogger(__name__)
  868. try:
  869. candidates = await energy_plug_candidates(db, printer_id)
  870. if not candidates:
  871. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  872. return False
  873. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  874. if selected is None:
  875. # Naming the plugs matters here: with several linked to one printer
  876. # this is the difference between "the meter is offline" and "you
  877. # linked only accessories" (#2859).
  878. _logger.warning(
  879. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  880. printer_id,
  881. archive.id,
  882. ", ".join(plug.name for plug in candidates),
  883. )
  884. return False
  885. plug, energy = selected
  886. archive.energy_start_kwh = float(energy["total"])
  887. # With the plug's snapshots, what lets the cost follow the price over
  888. # the print rather than take the price at its end (#1251). A price that
  889. # can't be had must not cost the print its energy reading.
  890. archive.energy_start_at = utcnow_naive()
  891. archive.energy_start_plug_id = plug.id
  892. try:
  893. from backend.app.services.energy_price import current_price
  894. archive.energy_start_price = await current_price(db)
  895. except Exception as e:
  896. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  897. archive.energy_start_price = None
  898. await db.commit()
  899. _logger.info(
  900. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  901. f" ({context})" if context else "",
  902. archive.id,
  903. plug.name,
  904. energy["total"],
  905. )
  906. return True
  907. except Exception as e:
  908. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  909. return False
  910. def forget_print_creator(user_id: int) -> None:
  911. """The print-start emails of a deleted user's jobs go to nobody, not to
  912. whoever is given the id next (SQLite reuses it)."""
  913. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  914. del _expected_print_creators[key]
  915. async def forget_printer(printer_id: int) -> None:
  916. """Drop what is kept for a deleted printer's id, here and in the services.
  917. SQLite used to give the id to the next printer created, which inherited it
  918. all: the running print's owner (its prints passed the kill switch and were
  919. billed to that user), the plate-clear gate, pending and suppressed
  920. notifications, the camera feed, the plate references. Ids are no longer
  921. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  922. stay. Called after the delete is committed, and again by work that was in
  923. flight and wrote state back.
  924. Every printer-keyed map of this module is listed here or, with the reason,
  925. in tests/unit/test_forget_printer.py.
  926. """
  927. from backend.app.api.routes import camera
  928. from backend.app.services import (
  929. bambu_ftp,
  930. kprofile_drift,
  931. layer_timelapse,
  932. plate_detection,
  933. print_dispatch_context,
  934. usage_tracker,
  935. )
  936. from backend.app.services.notify_live_activities import notify_live_activities
  937. from backend.app.services.obico_detection import obico_detection_service
  938. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  939. archive_ids = set()
  940. for tracked in (_active_prints, _expected_prints):
  941. for key in [key for key in tracked if key[0] == printer_id]:
  942. archive_ids.add(tracked.pop(key))
  943. for archive_id in archive_ids:
  944. _print_ams_mappings.pop(archive_id, None)
  945. _print_cost_center_ids.pop(archive_id, None)
  946. _print_plate_ids.pop(archive_id, None)
  947. for tracked in (_expected_print_creators, _expected_print_registered_at):
  948. for key in [key for key in tracked if key[0] == printer_id]:
  949. del tracked[key]
  950. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  951. _ams_index_only_logged.discard(key)
  952. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  953. del _ams_alarm_cooldown[key]
  954. # Pending work that would act on the id: an offline notice, a 3MF retry.
  955. # A kill-switch notice is about a stop that happened and is left to finish.
  956. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  957. task = tasks.pop(printer_id, None)
  958. if task is not None:
  959. task.cancel()
  960. for keyed in (
  961. _stage22_finish_frames,
  962. _stage22_finish_in_flight,
  963. _inprint_frame_bank,
  964. _inprint_frame_bank_ts,
  965. _printer_reconciled_since_connect,
  966. _printer_kprofiles_primed_since_connect,
  967. _last_progress_milestone,
  968. _first_layer_notified,
  969. _kill_switch_notification_tasks,
  970. _notified_hms_errors,
  971. _hms_print_state,
  972. _hms_forget_when_gone,
  973. _timelapse_baselines,
  974. _bed_cool_waiters,
  975. _printer_last_connected,
  976. _unknown_tag_last_broadcast,
  977. _last_status_broadcast,
  978. _connection_watchdog_last_attempt,
  979. ):
  980. keyed.pop(printer_id, None)
  981. for marked in (
  982. _unauthorized_print_kill_sent,
  983. _user_stopped_printers,
  984. _printer_offline_published,
  985. _nozzle_count_updated,
  986. ):
  987. marked.discard(printer_id)
  988. printer_manager.forget_printer(printer_id)
  989. print_dispatch_context.clear(printer_id)
  990. kprofile_drift.forget_printer(printer_id, deleted=True)
  991. layer_timelapse.cancel_session(printer_id)
  992. usage_tracker.forget_printer(printer_id)
  993. obico_detection_service.forget_printer(printer_id)
  994. bambu_ftp.clear_3mf_cache(printer_id)
  995. await camera.forget_printer(printer_id)
  996. printers.clear_cover_cache(printer_id)
  997. print_scheduler.forget_printer(printer_id)
  998. notify_live_activities.forget_printer(printer_id)
  999. plate_detection.remove_printer_references(printer_id)
  1000. def register_expected_print(
  1001. printer_id: int,
  1002. filename: str,
  1003. archive_id: int,
  1004. ams_mapping: list[int] | None = None,
  1005. created_by_id: int | None = None,
  1006. cost_center_id: int | None = None,
  1007. plate_id: int | None = None,
  1008. ):
  1009. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1010. # Store with multiple filename variations to catch different naming patterns
  1011. _expected_prints[(printer_id, filename)] = archive_id
  1012. # Also store without .3mf extension if present
  1013. if filename.endswith(".3mf"):
  1014. base = filename[:-4]
  1015. _expected_prints[(printer_id, base)] = archive_id
  1016. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1017. # Store AMS mapping for usage tracking at print completion
  1018. if ams_mapping is not None:
  1019. _print_ams_mappings[archive_id] = ams_mapping
  1020. if cost_center_id is not None:
  1021. _print_cost_center_ids[archive_id] = cost_center_id
  1022. # Store plate_id for usage tracking when this is a single-plate dispatch from
  1023. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  1024. # file's filament total to the spool instead of just the printed plate (#1697).
  1025. if plate_id is not None:
  1026. _print_plate_ids[archive_id] = plate_id
  1027. # Store created_by_id so the user start email can be sent even when the archive
  1028. # itself has no created_by_id (e.g. library-file-based queue prints)
  1029. if created_by_id is not None:
  1030. _expected_print_creators[(printer_id, filename)] = created_by_id
  1031. if filename.endswith(".3mf"):
  1032. base = filename[:-4]
  1033. _expected_print_creators[(printer_id, base)] = created_by_id
  1034. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1035. # Record registration time for TTL-based eviction
  1036. _registered_at = time.monotonic()
  1037. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1038. if filename.endswith(".3mf"):
  1039. base = filename[:-4]
  1040. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1041. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1042. logging.getLogger(__name__).info(
  1043. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1044. )
  1045. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1046. """Undo :func:`register_expected_print` when the print never went out.
  1047. Registration has to happen *before* the MQTT print command, because the
  1048. printer can report the print before the line after the send executes. So
  1049. every path that registers and then fails to send — a cancel winning the
  1050. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1051. between — leaves an expectation for a print that will never arrive.
  1052. The TTL sweep evicts those after two hours, which is far longer than it
  1053. takes a user to react to a failed dispatch by pressing print again: that
  1054. reprint would be folded into the *old* archive and take the stale
  1055. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1056. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1057. ``_print_ams_mappings`` / ``_print_plate_ids`` are keyed by archive, not by
  1058. file, so they may only be dropped once no live key still points at that
  1059. archive.
  1060. """
  1061. keys = [(printer_id, filename)]
  1062. if filename.endswith(".3mf"):
  1063. base = filename[:-4]
  1064. keys.append((printer_id, base))
  1065. keys.append((printer_id, f"{base}.gcode"))
  1066. removed = False
  1067. for key in keys:
  1068. if _expected_prints.pop(key, None) is not None:
  1069. removed = True
  1070. _expected_print_creators.pop(key, None)
  1071. _expected_print_registered_at.pop(key, None)
  1072. if archive_id not in set(_expected_prints.values()):
  1073. _print_ams_mappings.pop(archive_id, None)
  1074. _print_plate_ids.pop(archive_id, None)
  1075. if removed:
  1076. logging.getLogger(__name__).info(
  1077. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1078. printer_id,
  1079. filename,
  1080. archive_id,
  1081. )
  1082. def _compute_run_filament_grams(
  1083. status: str,
  1084. archive_filament_used_grams: float | None,
  1085. progress: float | int | None,
  1086. usage_results: list[dict] | None,
  1087. ) -> float | None:
  1088. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1089. Priority for every status:
  1090. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1091. weight delta — same source that drives "Total Consumed" on the
  1092. Inventory page, so Stats and Inventory totals stay aligned).
  1093. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1094. back to the canonical "this print used X" value).
  1095. 3. For partial statuses: ``estimate * progress%``.
  1096. 4. ``None`` if nothing is known.
  1097. """
  1098. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1099. if tracked_grams > 0:
  1100. return round(tracked_grams, 1)
  1101. if status == "completed":
  1102. return archive_filament_used_grams
  1103. if archive_filament_used_grams:
  1104. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1105. if scale > 0:
  1106. return round(archive_filament_used_grams * scale, 1)
  1107. return None
  1108. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  1109. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1110. stored_ams_mapping = data.get("ams_mapping")
  1111. if not stored_ams_mapping and archive_id:
  1112. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  1113. return stored_ams_mapping
  1114. def _get_start_plate_id(archive_id: int | None) -> int | None:
  1115. """Resolve plate_id for print start without consuming stored direct-Print state.
  1116. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1117. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1118. read it back at print-start without popping (the entry is popped on print
  1119. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1120. """
  1121. if archive_id is None:
  1122. return None
  1123. return _print_plate_ids.get(archive_id)
  1124. def _partial_progress_scale(progress: int | float | None) -> float:
  1125. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1126. Used by every site that multiplies a "would-have-used" slicer estimate
  1127. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1128. so the three sites in ``_background_notifications`` (and the per-plate
  1129. override helper) can't drift apart on the coercion shape.
  1130. """
  1131. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1132. def _scope_notification_archive_data_to_plate(
  1133. archive_data: dict,
  1134. archive_file_path: str | None,
  1135. plate_id: int | None,
  1136. print_status: str,
  1137. progress: int | float | None,
  1138. base_dir: Path,
  1139. ) -> dict:
  1140. """Override summed-across-plates totals in ``archive_data`` with the values
  1141. for ``plate_id`` so the completion notification reports what was actually
  1142. printed, not the whole project (#1785).
  1143. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1144. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1145. the archive card's "whole project" headline, wrong for the completion
  1146. notification of a single-plate print. The queue UI already re-reads the
  1147. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1148. notification payload (filament grams, time estimate, per-slot breakdown).
  1149. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1150. no per-plate values — in every fail case the original ``archive_data`` is
  1151. returned unchanged so the notification still sends.
  1152. """
  1153. if plate_id is None or not archive_file_path:
  1154. return archive_data
  1155. from backend.app.utils.threemf_tools import (
  1156. extract_filament_usage_from_3mf,
  1157. extract_print_time_from_3mf,
  1158. )
  1159. archive_path = base_dir / archive_file_path
  1160. if not archive_path.exists():
  1161. return archive_data
  1162. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1163. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1164. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1165. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1166. if plate_time:
  1167. archive_data["print_time_seconds"] = plate_time
  1168. # Gate both the grams headline AND the per-slot breakdown on the same
  1169. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1170. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1171. # to the project-level grams the archive columns already provide rather
  1172. # than ship a project-level headline next to an all-zero per-plate
  1173. # breakdown.
  1174. if plate_grams > 0:
  1175. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1176. archive_data["filament_slots"] = [
  1177. {
  1178. "slot_id": s.get("slot_id"),
  1179. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1180. "type": s.get("type", ""),
  1181. "color": s.get("color", ""),
  1182. }
  1183. for s in plate_slots
  1184. ]
  1185. return archive_data
  1186. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1187. """Best-effort filament metadata from the MQTT print-start snapshot.
  1188. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1189. file during print, see #1533) so the fallback PrintArchive still has
  1190. enough filament info to support the inventory views and AMS-expansion
  1191. planning the operator opens it for. Returns a dict with optional
  1192. ``filament_type`` and ``filament_color`` keys in the same
  1193. comma-separated format the 3MF extractor produces, so the rest of the
  1194. codebase treats the fallback archive identically to a normal one.
  1195. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1196. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1197. entries). When supplied, only the slots actually consumed by this
  1198. print contribute. Without it the function falls back to every loaded
  1199. AMS slot — less accurate but still useful.
  1200. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1201. that the unit tests pass directly, AND the on_print_start callback
  1202. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1203. bambu_mqtt service hands to main.py at runtime. The original
  1204. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1205. handled the inner shape and silently returned ``{}`` for every real
  1206. print start, leaving fallback archives' filament fields NULL — the
  1207. exact regression the fix was meant to close. Reported with a log
  1208. proving the AMS state was right there at
  1209. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1210. """
  1211. result: dict[str, str] = {}
  1212. # Look at the on_print_start wrapper first, then the inner shape.
  1213. raw_data = (data or {}).get("raw_data")
  1214. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1215. if not isinstance(ams_root, dict):
  1216. ams_root = (data or {}).get("ams") or {}
  1217. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1218. if not isinstance(ams_units, list) or not ams_units:
  1219. return result
  1220. # Map global tray id (unit * 4 + tray) → (type, color).
  1221. loaded: dict[int, tuple[str, str]] = {}
  1222. for unit in ams_units:
  1223. if not isinstance(unit, dict):
  1224. continue
  1225. try:
  1226. unit_id = int(unit.get("id", 0))
  1227. except (TypeError, ValueError):
  1228. continue
  1229. for tray in unit.get("tray") or []:
  1230. if not isinstance(tray, dict):
  1231. continue
  1232. try:
  1233. tray_id = int(tray.get("id", 0))
  1234. except (TypeError, ValueError):
  1235. continue
  1236. ttype = (tray.get("tray_type") or "").strip()
  1237. tcolor = (tray.get("tray_color") or "").strip().upper()
  1238. if not ttype:
  1239. continue # Empty / unloaded slot.
  1240. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  1241. if not loaded:
  1242. return result
  1243. if ams_mapping:
  1244. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1245. filaments = [loaded[g] for g in used_ids if g in loaded]
  1246. if not filaments:
  1247. return result # Mapping points entirely at slots we have no data for.
  1248. else:
  1249. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1250. types_joined = ",".join(f[0] for f in filaments)
  1251. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1252. # Column limits per backend/app/models/archive.py: filament_type=50,
  1253. # filament_color=200.
  1254. if types_joined:
  1255. result["filament_type"] = types_joined[:50]
  1256. if colors_joined:
  1257. result["filament_color"] = colors_joined[:200]
  1258. return result
  1259. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1260. """Start a layer-timelapse session for *archive_id* when the printer has
  1261. an external camera configured. Returns True if a session was started.
  1262. Three call sites in on_print_start (expected-archive promotion, fallback
  1263. archive creation, fresh-archive creation) used to inline this same
  1264. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1265. on the first pass). Centralising the conditional + call here makes the
  1266. contract testable in isolation and keeps the three sites locked in step.
  1267. """
  1268. if not (printer.external_camera_enabled and printer.external_camera_url):
  1269. return False
  1270. from backend.app.services.layer_timelapse import start_session
  1271. start_session(
  1272. printer_id,
  1273. archive_id,
  1274. printer.external_camera_url,
  1275. printer.external_camera_type or "mjpeg",
  1276. snapshot_url=printer.external_camera_snapshot_url,
  1277. rotation=getattr(printer, "camera_rotation", 0),
  1278. )
  1279. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1280. return True
  1281. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1282. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1283. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1284. — since #2926 — the description the parser already resolved, which is preferred
  1285. when present so the queue's failure reason reads the same as the status
  1286. response. The short code still produces the bracketed label, and still
  1287. resolves the sentence for a caller whose entries predate the field. An entry
  1288. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1289. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1290. label when no description is on file. Returns None for an empty list so
  1291. callers can leave error_message unset.
  1292. """
  1293. if not hms_errors:
  1294. return None
  1295. from backend.app.services.hms_errors import get_error_description
  1296. parts: list[str] = []
  1297. for err in hms_errors:
  1298. try:
  1299. # `_hms_short_code` rather than a local derivation: this one used to
  1300. # format the error without masking it to 16 bits, so an `hms[]` entry
  1301. # whose code carries an alert-level group produced a five-digit label
  1302. # like "0500_3000A" — not a code the user can look up, and never a
  1303. # catalogue key, so the sentence was lost with it.
  1304. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1305. except (TypeError, ValueError):
  1306. continue
  1307. description = err.get("description") or get_error_description(short_code)
  1308. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1309. # groups and is not a code anyone can look up; its full code in the
  1310. # printer screen's four groups is (#2728).
  1311. full_code = str(err.get("full_code") or "")
  1312. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1313. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1314. return "; ".join(parts) if parts else None
  1315. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1316. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1317. print completes successfully. Gated to status=='completed': failed, cancelled
  1318. and aborted prints do not count as usage. Caller is responsible for committing
  1319. the session. No-op when the queue item has no linked library file (e.g. reprints
  1320. from an archive). See #1008."""
  1321. if queue_status != "completed" or item.library_file_id is None:
  1322. return
  1323. from backend.app.models.library import LibraryFile
  1324. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1325. if lib_file is None:
  1326. return
  1327. lib_file.print_count = (lib_file.print_count or 0) + 1
  1328. lib_file.last_printed_at = datetime.now(timezone.utc)
  1329. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1330. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1331. When on_print_complete fires with status 'failed' for a printer in this set we
  1332. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1333. rather than a 'print failed' notification.
  1334. """
  1335. _user_stopped_printers.add(printer_id)
  1336. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1337. _last_status_broadcast: dict[int, str] = {}
  1338. # Track printers where we've updated nozzle_count
  1339. _nozzle_count_updated: set[int] = set()
  1340. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1341. """Wait the debounce window then fire `on_printer_offline` if the printer
  1342. is still offline.
  1343. Scheduled by `on_printer_status_change` on the connected → disconnected
  1344. edge (#1752). Cancelled by the same handler if the printer reconnects
  1345. before the window elapses, so a single MQTT blip + recovery doesn't
  1346. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1347. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1348. route through the same status-change callback, so this covers both.
  1349. """
  1350. logger = logging.getLogger(__name__)
  1351. try:
  1352. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1353. still_offline = not printer_manager.is_connected(printer_id)
  1354. logger.info(
  1355. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1356. printer_id,
  1357. still_offline,
  1358. )
  1359. if not still_offline:
  1360. return
  1361. async with async_session() as db:
  1362. from backend.app.models.printer import Printer
  1363. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1364. printer = result.scalar_one_or_none()
  1365. if not printer:
  1366. logger.warning(
  1367. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1368. printer_id,
  1369. )
  1370. return
  1371. # Recorded only when the relay can publish it, so the reconnect's
  1372. # online event always has an offline before it.
  1373. if mqtt_relay.enabled and mqtt_relay.connected:
  1374. _printer_offline_published.add(printer_id)
  1375. try:
  1376. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1377. except Exception as e:
  1378. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1379. logger.info(
  1380. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1381. printer_id,
  1382. printer.name,
  1383. )
  1384. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1385. except asyncio.CancelledError:
  1386. raise
  1387. except Exception as e:
  1388. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1389. finally:
  1390. _printer_offline_notify_tasks.pop(printer_id, None)
  1391. def _hms_notify_key(error) -> str:
  1392. """What identifies a fault for notification de-duplication.
  1393. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1394. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1395. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1396. and -0006 together) shared a key and only the first was ever notified. An
  1397. entry without a full code falls back to attr and code together.
  1398. """
  1399. full_code = getattr(error, "full_code", "") or ""
  1400. if full_code:
  1401. return full_code.upper()
  1402. return f"{error.attr:08X}:{error.code}"
  1403. def _hms_fault_counts(error) -> bool:
  1404. """Whether a fault counts as a problem: the same rule the frontend's
  1405. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1406. It counts when Bambu publishes text for it or it offers action buttons, and
  1407. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1408. no actions does not count: those are things like "the top cover is open" or
  1409. "the chamber is hot, fan speed increased", which a printer can hold through
  1410. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1411. it always has; those are prompts such as "unable to start drying" (#2728).
  1412. """
  1413. if error.severity < 1:
  1414. return False
  1415. has_actions = bool(getattr(error, "actions", None))
  1416. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1417. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1418. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1419. """The new faults that count (see ``_hms_fault_counts``).
  1420. These go to the MQTT relay; the caller also needs a description before it
  1421. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1422. used to read ``severity >= 2`` when severity held the part byte; on the real
  1423. level that would drop the task-stopping errors (#2728).
  1424. """
  1425. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1426. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1427. """The faults on this printer not notified yet, and record them as notified.
  1428. Tracking is updated before anything is sent, so concurrent status callbacks
  1429. cannot notify the same fault twice. A notified fault is forgotten once it
  1430. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1431. and on is notified once (#3226), while one that clears and comes back much
  1432. later is notified again.
  1433. When ``print_state`` changes (a print resumed, started or finished), every
  1434. fault recorded so far is forgotten the first time it is gone, without the
  1435. wait: a runout fixed before resuming must be notified if it happens again a
  1436. few minutes later, while the printer sits paused. Not only the faults gone
  1437. at the change itself, because the update that flips the state can still
  1438. carry the old fault (a ``print_error`` entry stays until a payload brings
  1439. ``hms``).
  1440. """
  1441. now = time.time()
  1442. current = {_hms_notify_key(e) for e in errors}
  1443. seen = _notified_hms_errors.setdefault(printer_id, {})
  1444. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1445. if print_state is not None:
  1446. print_state = print_state.upper()
  1447. if _hms_print_state.get(printer_id, print_state) != print_state:
  1448. forget_when_gone.update(seen)
  1449. _hms_print_state[printer_id] = print_state
  1450. for key, last_seen in list(seen.items()):
  1451. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1452. del seen[key]
  1453. forget_when_gone.discard(key)
  1454. new = current - seen.keys()
  1455. for key in current:
  1456. seen[key] = now
  1457. if not seen:
  1458. _notified_hms_errors.pop(printer_id, None)
  1459. if not forget_when_gone:
  1460. _hms_forget_when_gone.pop(printer_id, None)
  1461. return _hms_errors_to_notify(errors, new)
  1462. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1463. # "Printing", -1 and 255 are "no stage" (#3211).
  1464. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1465. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1466. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1467. Records it as notified. Called only for a printing state with progress above 0.
  1468. Progress before the first layer is not progress through the print (#3211).
  1469. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1470. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1471. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1472. 75% notification together with Print Started, and since 75 was then on
  1473. record, 25 and 50 could never fire. So nothing counts while the printer
  1474. reports a layer count but has not started layer 1.
  1475. Without a layer count -- a print whose first frame carried no
  1476. ``total_layer_num``, until the pushall that asks for it is answered
  1477. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1478. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1479. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1480. reports neither keeps the old behaviour rather than never notifying.
  1481. """
  1482. if (state.layer_num or 0) < 1:
  1483. if (state.total_layers or 0) > 0:
  1484. return None
  1485. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1486. return None
  1487. progress = state.progress or 0
  1488. current_milestone = 0
  1489. if progress >= 75:
  1490. current_milestone = 75
  1491. elif progress >= 50:
  1492. current_milestone = 50
  1493. elif progress >= 25:
  1494. current_milestone = 25
  1495. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1496. _last_progress_milestone[printer_id] = current_milestone
  1497. return current_milestone
  1498. return None
  1499. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1500. """Handle printer status changes - broadcast via WebSocket."""
  1501. try:
  1502. notify_live_activities.observe(printer_id, state)
  1503. except Exception:
  1504. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1505. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1506. # transitions disconnected → connected — which covers both Bambuddy
  1507. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1508. # `reconcile_stale_active_prints` exactly once for this connection so
  1509. # any archive still in `status="printing"` that can't actually be
  1510. # running anymore (printer IDLE / different subtask / empty subtask)
  1511. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1512. # finished during a disconnect window + a smart-plug power cycle
  1513. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1514. # next boot. Reconciliation runs concurrently — it must not block the
  1515. # WebSocket dedup / broadcast logic below, and the connected edge is
  1516. # marked True BEFORE the await so concurrent status updates inside
  1517. # the same connection don't re-trigger reconciliation.
  1518. #
  1519. # Wait for a real push_status before reconciling (#1679): MQTT
  1520. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1521. # the connection, BEFORE `_request_push_all` round-trips. At that
  1522. # instant the `PrinterState` is still on construction defaults — most
  1523. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1524. # If reconcile spawns here, every in-flight archive falls through to
  1525. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1526. # creates a duplicate archive on the real PRINT COMPLETE and
  1527. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1528. # keeps the #1542 mechanism intact: once the first real push_status
  1529. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1530. # fires again with the flag still False — reconcile then runs against
  1531. # actual evidence.
  1532. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1533. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1534. _printer_reconciled_since_connect[printer_id] = True
  1535. spawn_background_task(
  1536. reconcile_stale_active_prints(printer_id),
  1537. name=f"reconcile-stale-prints-{printer_id}",
  1538. )
  1539. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1540. # Re-arm so the next reconnect triggers reconciliation again.
  1541. _printer_reconciled_since_connect[printer_id] = False
  1542. # Same edge, for the calibration table the AMS card reads its K values from.
  1543. #
  1544. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1545. # tables to ask for. A `state_known` gate alone is not enough: the first
  1546. # real push_status is what makes the state known, and the nozzle fields do
  1547. # not always arrive in it. Latching there would spend this connection's one
  1548. # attempt on a printer that could not yet say what was fitted.
  1549. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1550. if (
  1551. state.connected
  1552. and state_known
  1553. and nozzle_known
  1554. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1555. ):
  1556. _printer_kprofiles_primed_since_connect[printer_id] = True
  1557. spawn_background_task(
  1558. prime_kprofile_table(printer_id),
  1559. name=f"prime-kprofiles-{printer_id}",
  1560. )
  1561. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1562. _printer_kprofiles_primed_since_connect[printer_id] = False
  1563. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1564. # else in the AMS report changing -- a power cycle does it to every slot --
  1565. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1566. # while the printer is idle; needs_check is cheap and throttled per slot.
  1567. # Guarded: nothing here may stop the status broadcast below.
  1568. try:
  1569. if not state.connected:
  1570. kprofile_drift.forget_printer(printer_id)
  1571. elif kprofile_drift.needs_check(printer_id, state):
  1572. spawn_background_task(
  1573. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1574. name=f"reapply-kprofiles-{printer_id}",
  1575. )
  1576. except Exception:
  1577. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1578. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1579. # connected → disconnected. The "back online" channel is already covered
  1580. # by the print-failure notification (firmware reports gcode_state=FAILED
  1581. # on reconnect of an interrupted print), so there is no online
  1582. # notification. The MQTT relay gets both: offline after the debounce, and
  1583. # online on the reconnect that follows a published offline.
  1584. prev_connected = _printer_last_connected.get(printer_id)
  1585. _printer_last_connected[printer_id] = state.connected
  1586. if prev_connected is True and not state.connected:
  1587. existing = _printer_offline_notify_tasks.get(printer_id)
  1588. if existing is None or existing.done():
  1589. logging.getLogger(__name__).info(
  1590. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1591. printer_id,
  1592. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1593. )
  1594. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1595. _maybe_notify_printer_offline(printer_id),
  1596. name=f"printer-offline-notify-{printer_id}",
  1597. )
  1598. elif state.connected:
  1599. # Kept until the relay can actually send online: with its broker down
  1600. # now, the next status update after the reconnect sends it.
  1601. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1602. _printer_offline_published.discard(printer_id)
  1603. printer_info = printer_manager.get_printer(printer_id)
  1604. if printer_info:
  1605. try:
  1606. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1607. except Exception as e:
  1608. logging.getLogger(__name__).warning(
  1609. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1610. )
  1611. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1612. if pending is not None and not pending.done():
  1613. logging.getLogger(__name__).info(
  1614. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1615. printer_id,
  1616. )
  1617. pending.cancel()
  1618. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1619. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1620. temps = state.temperatures or {}
  1621. nozzle_temp = round(temps.get("nozzle", 0))
  1622. bed_temp = round(temps.get("bed", 0))
  1623. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1624. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1625. # Auto-detect dual-nozzle printers from MQTT temperature data
  1626. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1627. _nozzle_count_updated.add(printer_id)
  1628. # Update nozzle_count in database
  1629. async with async_session() as db:
  1630. from backend.app.models.printer import Printer
  1631. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1632. printer = result.scalar_one_or_none()
  1633. if printer and printer.nozzle_count != 2:
  1634. printer.nozzle_count = 2
  1635. await db.commit()
  1636. logging.getLogger(__name__).info(
  1637. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1638. )
  1639. # Include target temps for heating phase detection
  1640. bed_target = round(temps.get("bed_target", 0))
  1641. nozzle_target = round(temps.get("nozzle_target", 0))
  1642. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1643. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1644. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1645. #
  1646. # dry_countdown_stalled rides along because it is the one drying signal the
  1647. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1648. # dry_time stopped moving, so on the frame that flips it every other member
  1649. # of this key is identical and the push would be deduplicated away. Mid-print
  1650. # a temperature would eventually break the tie, but a parked command on an
  1651. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1652. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1653. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1654. ams_dry_key = (
  1655. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1656. if state.raw_data
  1657. else ()
  1658. )
  1659. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1660. #
  1661. # The filament identity fields are here because Configure Slot writes
  1662. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1663. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1664. # matched, this function returned before broadcasting, and the card kept
  1665. # showing the old filament until the 30s fallback poll or a page reload —
  1666. # even though the configure route asks the printer for a fresh pushall and
  1667. # that push does carry the new values. Reset always worked, because it
  1668. # clears tray_type.
  1669. #
  1670. # These fields only change when someone configures a slot or swaps a spool,
  1671. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1672. ams_tray_key = (
  1673. tuple(
  1674. (
  1675. t.get("id"),
  1676. t.get("tray_type", ""),
  1677. t.get("state"),
  1678. t.get("tray_color", ""),
  1679. t.get("tray_info_idx", ""),
  1680. t.get("tray_sub_brands", ""),
  1681. t.get("cali_idx"),
  1682. )
  1683. for a in (state.raw_data.get("ams") or [])
  1684. for t in a.get("tray", [])
  1685. )
  1686. if state.raw_data
  1687. else ()
  1688. )
  1689. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1690. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1691. # in the AMS change-hash (tray fields only, and widening that would fire
  1692. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1693. # screen changed no key at all and the card's inlet badges sat stale until a
  1694. # reload. Like the filament-backup flag, these only move when someone
  1695. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1696. fts_key = (
  1697. state.fila_switch.installed if state.fila_switch else False,
  1698. tuple(sorted(state.ams_switch_inlet.items())),
  1699. # Which hotend holds which slot. Unlike the two above this does move
  1700. # mid-print, on every filament change — but only between discrete slots,
  1701. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1702. # it live: it decides which hotend the Load dialog may offer and whether
  1703. # Unload has anything to act on.
  1704. tuple(
  1705. sorted(
  1706. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1707. # Sort on the extruder id alone: the other members are nullable
  1708. # and comparing None with an int raises.
  1709. key=lambda entry: entry[0],
  1710. )
  1711. ),
  1712. )
  1713. status_key = (
  1714. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1715. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1716. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1717. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1718. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1719. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1720. )
  1721. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1722. if not is_active_print:
  1723. _unauthorized_print_kill_sent.discard(printer_id)
  1724. elif printer_id in _unauthorized_print_kill_sent:
  1725. # stop_print() was already sent for this print; avoid all further
  1726. # ownership and settings work until the printer leaves an active state.
  1727. pass
  1728. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1729. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1730. _unauthorized_print_kill_sent.discard(printer_id)
  1731. else:
  1732. kill_switch_enabled = False
  1733. authorization: bool | None = None
  1734. status_logger = logging.getLogger(__name__)
  1735. try:
  1736. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1737. if kill_switch_enabled:
  1738. async with async_session() as db:
  1739. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1740. except Exception as e:
  1741. # Fail safe: a database/reconciliation error must never turn into an
  1742. # irreversible stop of a print whose ownership is still unknown.
  1743. authorization = None
  1744. status_logger.warning(
  1745. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1746. )
  1747. if not kill_switch_enabled or authorization is True:
  1748. _unauthorized_print_kill_sent.discard(printer_id)
  1749. elif authorization is None:
  1750. _unauthorized_print_kill_sent.discard(printer_id)
  1751. status_logger.debug(
  1752. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1753. printer_id,
  1754. )
  1755. else:
  1756. try:
  1757. stopped = printer_manager.stop_print(printer_id)
  1758. if stopped:
  1759. _unauthorized_print_kill_sent.add(printer_id)
  1760. printer_info = printer_manager.get_printer(printer_id)
  1761. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1762. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1763. notification_data = {
  1764. "status": "stopped",
  1765. "filename": state.gcode_file or state.current_print or "",
  1766. "subtask_name": state.subtask_name or "",
  1767. "progress": state.progress,
  1768. "reason": "unauthorized_print",
  1769. }
  1770. status_logger.warning(
  1771. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1772. printer_id,
  1773. state.state,
  1774. )
  1775. try:
  1776. await ws_manager.broadcast(
  1777. {
  1778. "type": "kill_switch_triggered",
  1779. "printer_id": printer_id,
  1780. "printer_name": printer_name,
  1781. "filename": filename,
  1782. "reason": "unauthorized_print",
  1783. }
  1784. )
  1785. except Exception as e:
  1786. status_logger.warning(
  1787. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1788. )
  1789. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1790. if previous_task is not None and not previous_task.done():
  1791. previous_task.cancel()
  1792. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1793. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1794. name=f"kill-switch-notification-{printer_id}",
  1795. )
  1796. else:
  1797. status_logger.warning(
  1798. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1799. printer_id,
  1800. state.state,
  1801. )
  1802. except Exception as e:
  1803. status_logger.warning(
  1804. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1805. )
  1806. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1807. try:
  1808. printer_info = printer_manager.get_printer(printer_id)
  1809. if printer_info:
  1810. await mqtt_relay.on_printer_status(
  1811. printer_id,
  1812. state,
  1813. printer_info.name,
  1814. printer_info.serial_number,
  1815. printer_manager.is_awaiting_plate_clear(printer_id),
  1816. )
  1817. except Exception:
  1818. pass # Don't fail status callback if MQTT fails
  1819. if _last_status_broadcast.get(printer_id) == status_key:
  1820. return # No change, skip WebSocket broadcast
  1821. _last_status_broadcast[printer_id] = status_key
  1822. # Check for progress milestone notifications (25%, 50%, 75%)
  1823. progress = state.progress or 0
  1824. is_printing = state.state in ("RUNNING", "PRINTING")
  1825. if is_printing and progress > 0:
  1826. current_milestone = _progress_milestone_to_notify(printer_id, state)
  1827. if current_milestone is not None:
  1828. try:
  1829. from backend.app.models.printer import Printer
  1830. # Read the printer in a short session and release the connection
  1831. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1832. # pinned a pooled connection per milestone, per printer (issue #2572).
  1833. async with async_session() as db:
  1834. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1835. printer = result.scalar_one_or_none()
  1836. printer_name = printer.name if printer else f"Printer {printer_id}"
  1837. filename = state.subtask_name or state.gcode_file or "Unknown"
  1838. # remaining_time is in minutes, convert to seconds for notification
  1839. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1840. # Capture camera snapshot for notification image attachment (no DB held).
  1841. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1842. # Notification send needs a session (provider/template lookups).
  1843. async with async_session() as db:
  1844. await notification_service.on_print_progress(
  1845. printer_id,
  1846. printer_name,
  1847. filename,
  1848. current_milestone,
  1849. db,
  1850. remaining_time_seconds,
  1851. image_data=image_data,
  1852. )
  1853. except Exception as e:
  1854. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1855. elif progress < 5:
  1856. # Reset milestone tracking when print restarts or new print begins
  1857. _last_progress_milestone[printer_id] = 0
  1858. _first_layer_notified[printer_id] = False
  1859. # HMS error codes that should not trigger notifications even though they
  1860. # have known descriptions (e.g. user-initiated actions, not real errors).
  1861. _HMS_NOTIFICATION_SUPPRESS = {
  1862. "0500_400E", # Printing was cancelled (user action, not an error)
  1863. }
  1864. # Check for new HMS errors and send notifications
  1865. current_hms_errors = getattr(state, "hms_errors", []) or []
  1866. if current_hms_errors:
  1867. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  1868. if new_errors:
  1869. try:
  1870. from backend.app.models.printer import Printer
  1871. # Read the printer in a short session and release the connection
  1872. # BEFORE the ~15s camera snapshot below (issue #2572).
  1873. async with async_session() as db:
  1874. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1875. printer = result.scalar_one_or_none()
  1876. printer_name = printer.name if printer else f"Printer {printer_id}"
  1877. # Format error details for notification
  1878. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1879. module_names = {
  1880. 0x03: "Print/Task",
  1881. 0x05: "Nozzle/Extruder",
  1882. 0x07: "AMS/Filament",
  1883. 0x0C: "Motion Controller",
  1884. 0x12: "Chamber",
  1885. }
  1886. # Capture camera snapshot once for all error notifications (no DB held).
  1887. error_image_data = await _capture_snapshot_for_notification(
  1888. printer_id, printer, logging.getLogger(__name__)
  1889. )
  1890. # Notification sends need a session (provider/template lookups).
  1891. async with async_session() as db:
  1892. sent_count = 0
  1893. for error in new_errors:
  1894. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1895. # Build short code like "0700_8010"
  1896. # Mask to 16 bits to handle printers that send larger values
  1897. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1898. error_code_masked = error_code_int & 0xFFFF
  1899. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1900. # Only notify for errors Bambu publishes text for — printers
  1901. # send undocumented codes that aren't real errors, and Bambu
  1902. # lists some with empty text. Resolved at parse time (#2926);
  1903. # short_code is still needed for the suppression set below.
  1904. description = error.description
  1905. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1906. continue
  1907. error_type = f"{module_name} Error"
  1908. error_detail = description
  1909. await notification_service.on_printer_error(
  1910. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1911. )
  1912. sent_count += 1
  1913. if sent_count:
  1914. logging.getLogger(__name__).info(
  1915. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1916. )
  1917. # Also publish to MQTT relay (no DB): every new fault that
  1918. # counts, with or without text, the same set the UI counts.
  1919. printer_info = printer_manager.get_printer(printer_id)
  1920. if printer_info:
  1921. errors_data = [
  1922. {
  1923. "code": e.code,
  1924. "attr": e.attr,
  1925. "module": e.module,
  1926. "severity": e.severity,
  1927. }
  1928. for e in new_errors
  1929. ]
  1930. await mqtt_relay.on_printer_error(
  1931. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1932. )
  1933. except Exception as e:
  1934. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1935. else:
  1936. # No HMS errors: nothing to send, but faults gone long enough (or gone
  1937. # across a print state change) are forgotten. Some codes, e.g. chamber
  1938. # temperature regulation during PETG prints, toggle every few seconds.
  1939. _take_new_hms_faults(printer_id, [], state.state)
  1940. await ws_manager.send_printer_status(
  1941. printer_id,
  1942. printer_state_to_dict(
  1943. state,
  1944. printer_id,
  1945. printer_manager.get_model(printer_id),
  1946. printer_manager.get_drying_targets(printer_id),
  1947. ),
  1948. )
  1949. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1950. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1951. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1952. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  1953. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  1954. K-profiles are per-nozzle and the printer's calibration table is numbered
  1955. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  1956. switch's other inlet therefore silently invalidates every configured slot in
  1957. it: the index stays put and now resolves against the other nozzle's table.
  1958. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  1959. and 0.020 on the right kept the left profile after the move, and a manual
  1960. RFID re-read only re-asserted the same wrong one.
  1961. Configuring a slot is a deliberate preparation step, so this re-selects
  1962. rather than re-configures: only the calibration binding moves, and only for
  1963. slots whose spool already has a stored profile for the new nozzle. A slot
  1964. Bambuddy knows nothing about is left exactly as the operator left it.
  1965. """
  1966. logger = logging.getLogger(__name__)
  1967. target_extruder = extruder_for_inlet(inlet)
  1968. if target_extruder is None:
  1969. return
  1970. client = printer_manager.get_client(printer_id)
  1971. state = printer_manager.get_status(printer_id)
  1972. if not client or not state or not state.raw_data:
  1973. return
  1974. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  1975. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  1976. # the nozzle width, which changes both the K profile to select and the
  1977. # preset the slot should carry.
  1978. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  1979. ams_raw = state.raw_data.get("ams")
  1980. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  1981. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  1982. if not unit:
  1983. return
  1984. try:
  1985. async with async_session() as db:
  1986. for tray in unit.get("tray", []):
  1987. tray_id = int(tray.get("id", -1))
  1988. if tray_id < 0 or not tray.get("tray_type"):
  1989. continue
  1990. current_idx = tray.get("cali_idx")
  1991. profile = await find_slot_kprofile_for_extruder(
  1992. db,
  1993. printer_id,
  1994. ams_id,
  1995. tray_id,
  1996. target_extruder,
  1997. nozzle_diameter,
  1998. printer_manager.get_model(printer_id),
  1999. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2000. )
  2001. if profile is None or profile.cali_idx is None:
  2002. continue
  2003. if current_idx == profile.cali_idx:
  2004. continue # Already on the right one.
  2005. logger.info(
  2006. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2007. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2008. printer_id,
  2009. ams_id,
  2010. tray_id,
  2011. inlet,
  2012. target_extruder,
  2013. profile.name,
  2014. current_idx,
  2015. profile.cali_idx,
  2016. profile.k_value,
  2017. )
  2018. client.extrusion_cali_sel(
  2019. ams_id=ams_id,
  2020. tray_id=tray_id,
  2021. cali_idx=profile.cali_idx,
  2022. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2023. nozzle_diameter=nozzle_diameter,
  2024. )
  2025. except Exception as e:
  2026. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2027. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2028. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2029. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2030. from the delayed re-check -- which is why it takes the AMS data and print
  2031. state as arguments instead of reading them from the push (#3186).
  2032. """
  2033. logger = logging.getLogger(__name__)
  2034. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2035. # Auto-unlink spool assignments with stale fingerprints. Under the
  2036. # per-printer assignment lock since #3186: the held-removal re-check runs
  2037. # this outside any MQTT push, so it can now overlap one.
  2038. try:
  2039. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2040. from sqlalchemy.orm import selectinload
  2041. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2042. from backend.app.models.spool import Spool as _Spool
  2043. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2044. from backend.app.services.ams_slot_presence import spool_present
  2045. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2046. # Built-in assignments only. Since #2812 they survive a switch to
  2047. # Spoolman mode rather than being deleted by it, and this pass ends
  2048. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2049. # time as the AMS contents changed under the other mode, undoing the
  2050. # preservation more slowly but just as completely.
  2051. assignments = []
  2052. if not await spoolman_owns_assignments(db):
  2053. result = await db.execute(
  2054. select(SA)
  2055. .where(SA.printer_id == printer_id)
  2056. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2057. )
  2058. assignments = result.scalars().all()
  2059. # ``printing_now`` (top of this function) keeps a runout from
  2060. # unlinking the spool that fed the print — the next idle-time pass
  2061. # unlinks it if the user really did take it out.
  2062. stale = []
  2063. # Removals this pass is holding rather than unlinking (#3186).
  2064. held: set[tuple] = set()
  2065. for assignment in assignments:
  2066. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2067. if assignment.ams_id == 255:
  2068. ps = printer_manager.get_status(printer_id)
  2069. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2070. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2071. current_tray = None
  2072. for vt in vt_tray_raw:
  2073. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2074. current_tray = vt
  2075. break
  2076. if not current_tray:
  2077. # vt_tray data may not have arrived yet — keep assignment
  2078. continue
  2079. else:
  2080. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2081. if not current_tray:
  2082. if printing_now:
  2083. logger.info(
  2084. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2085. assignment.spool_id,
  2086. assignment.ams_id,
  2087. assignment.tray_id,
  2088. )
  2089. continue
  2090. # A whole AMS unit can drop out of one push and come back in
  2091. # the next; only a slot that stays gone is a removal (#3186).
  2092. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2093. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2094. held.add(hold_key)
  2095. logger.info(
  2096. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2097. "unlinking if it is still gone in %ds",
  2098. assignment.spool_id,
  2099. assignment.ams_id,
  2100. assignment.tray_id,
  2101. int(slot_unlink_grace.GRACE_SECONDS),
  2102. )
  2103. continue
  2104. logger.info(
  2105. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2106. assignment.spool_id,
  2107. assignment.ams_id,
  2108. assignment.tray_id,
  2109. )
  2110. stale.append(assignment) # Slot empty
  2111. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2112. # A Bambu Lab spool is in this slot — check if it's the same spool
  2113. # that's currently assigned. If yes, keep the assignment (avoids
  2114. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2115. # the printer's filament preset on every startup).
  2116. tray_uuid = current_tray.get("tray_uuid", "")
  2117. tag_uid = current_tray.get("tag_uid", "")
  2118. spool = assignment.spool
  2119. spool_matches = False
  2120. if spool:
  2121. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2122. spool.tag_uid
  2123. and tag_uid
  2124. and tag_uid != "0000000000000000"
  2125. and spool.tag_uid.upper() == tag_uid.upper()
  2126. ):
  2127. spool_matches = True
  2128. if spool_matches:
  2129. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2130. cur_color = current_tray.get("tray_color", "")
  2131. cur_type = current_tray.get("tray_type", "")
  2132. fp_color = assignment.fingerprint_color or ""
  2133. fp_type = assignment.fingerprint_type or ""
  2134. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2135. assignment.fingerprint_color = cur_color
  2136. assignment.fingerprint_type = cur_type
  2137. logger.debug(
  2138. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2139. assignment.spool_id,
  2140. assignment.ams_id,
  2141. assignment.tray_id,
  2142. )
  2143. continue
  2144. # Different BL spool or unrecognized — unlink so auto-assign can match
  2145. logger.info(
  2146. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2147. assignment.spool_id,
  2148. assignment.ams_id,
  2149. assignment.tray_id,
  2150. tray_uuid,
  2151. )
  2152. stale.append(assignment)
  2153. else:
  2154. cur_color = current_tray.get("tray_color", "")
  2155. cur_type = current_tray.get("tray_type", "")
  2156. cur_state = current_tray.get("state")
  2157. fp_color = assignment.fingerprint_color or ""
  2158. fp_type = assignment.fingerprint_type or ""
  2159. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2160. # the slot was empty when the user pre-assigned via SpoolBuddy
  2161. # (the firmware drops ams_filament_setting on empty slots, so
  2162. # MQTT was deferred). The moment any filament gets inserted
  2163. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2164. # reconfigured spool — fire the deferred configuration.
  2165. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2166. # extruder" code) OR, on firmwares that don't use the state
  2167. # enum meaningfully, a non-empty tray_type when state is
  2168. # NOT one of the firmware's explicit empty signals (9, 10).
  2169. # state-only was wrong for firmwares that never set 11 — A1
  2170. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2171. # always report state=3 — so the replay never fired for them
  2172. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2173. # explicit "empty" signals authoritative over any stale
  2174. # tray_type that might survive the relay's auto-clearing.
  2175. #
  2176. # tray_exist_bits comes first because that guard cannot tell
  2177. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2178. # writes state=9 when the bit is 0 and leaves it there when the
  2179. # bit returns. A non-RFID spool inserted into a pre-assigned
  2180. # slot brings no tray_type with it, so the stale 9 made this
  2181. # expression false forever and the deferred config never fired
  2182. # — the deadlock #1322 removed from the assign path, still in
  2183. # place here (#3084, #3100).
  2184. loaded = spool_present(current_tray) is True or (
  2185. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2186. )
  2187. if not fp_type.strip() and loaded and assignment.spool:
  2188. try:
  2189. from backend.app.api.routes.inventory import (
  2190. apply_spool_to_slot_via_mqtt,
  2191. )
  2192. await apply_spool_to_slot_via_mqtt(
  2193. db=db,
  2194. current_user=None,
  2195. spool=assignment.spool,
  2196. printer_id=printer_id,
  2197. ams_id=assignment.ams_id,
  2198. tray_id=assignment.tray_id,
  2199. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2200. current_tray_type=cur_type,
  2201. )
  2202. logger.info(
  2203. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2204. assignment.spool_id,
  2205. printer_id,
  2206. assignment.ams_id,
  2207. assignment.tray_id,
  2208. )
  2209. except Exception:
  2210. logger.exception(
  2211. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2212. assignment.spool_id,
  2213. printer_id,
  2214. assignment.ams_id,
  2215. assignment.tray_id,
  2216. )
  2217. assignment.fingerprint_color = cur_color
  2218. assignment.fingerprint_type = cur_type
  2219. continue
  2220. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2221. # Blank tray data mid-print is a runout, not a swap: the
  2222. # firmware clears colour and type when it unloads a spool
  2223. # it just emptied. Unlinking here would erase the record
  2224. # of which spool fed the print so far.
  2225. if printing_now and not cur_color.strip() and not cur_type.strip():
  2226. logger.info(
  2227. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2228. "(runout?)",
  2229. assignment.spool_id,
  2230. assignment.ams_id,
  2231. assignment.tray_id,
  2232. )
  2233. continue
  2234. # Same reasoning off the print, on firmware's own say-so:
  2235. # a blank tray report from a slot whose tray_exist_bits
  2236. # bit is set describes a spool the AMS cannot identify —
  2237. # a non-RFID one, or one whose slot was reset — not a
  2238. # spool that was taken out. Deleting the assignment there
  2239. # threw away the identity the user had supplied, which is
  2240. # the only place it existed (#3100). A slot the bit calls
  2241. # empty, or one that carries no bit at all, still unlinks.
  2242. #
  2243. # Unless the slot was reported empty first: a removal
  2244. # already held means a spool came out and another went
  2245. # in, so the blank report keeps the hold running below
  2246. # rather than cancelling it (#3186).
  2247. if (
  2248. spool_present(current_tray) is True
  2249. and not cur_color.strip()
  2250. and not cur_type.strip()
  2251. and not slot_unlink_grace.is_held(
  2252. printer_id,
  2253. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2254. )
  2255. ):
  2256. logger.info(
  2257. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2258. "tray reports no filament data yet",
  2259. assignment.spool_id,
  2260. assignment.ams_id,
  2261. assignment.tray_id,
  2262. )
  2263. continue
  2264. # A blank report the presence bit does not vouch for is
  2265. # still only one push. An idle X1C cleared a whole AMS
  2266. # unit's bits, colour and type for a moment and lost
  2267. # four saved assignments that way (#3186); unlink only
  2268. # if the slot is still blank after the grace period.
  2269. if not cur_color.strip() and not cur_type.strip():
  2270. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2271. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2272. held.add(hold_key)
  2273. logger.info(
  2274. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2275. "unlinking if it is still blank in %ds",
  2276. assignment.spool_id,
  2277. assignment.ams_id,
  2278. assignment.tray_id,
  2279. int(slot_unlink_grace.GRACE_SECONDS),
  2280. )
  2281. continue
  2282. # Fingerprint mismatch — but check if tray now matches the
  2283. # assigned spool (e.g. auto-configure changed the tray).
  2284. # Both sides are reduced to the type the slot can carry
  2285. # before comparing: the assign path writes that rather
  2286. # than the spool's raw material (#2902), so a spool whose
  2287. # material is a product line — "PLA+", "HTPLA" — reports
  2288. # back as "PLA" and would otherwise fail this check and
  2289. # be auto-unlinked from the slot it was just assigned to.
  2290. # Reducing the printer's side too keeps slots configured
  2291. # by an older Bambuddy, still reporting "PLA+", matching.
  2292. spool = assignment.spool
  2293. if spool:
  2294. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2295. # Two ways the assign path can have arrived at the
  2296. # slot's type, so both count as "we wrote this".
  2297. # The material column is one; the spool's preset is
  2298. # the other, and it outranks the material when the
  2299. # spool has one -- a spool whose material says PLA
  2300. # and whose preset is "Bambu PLA Aero" puts
  2301. # PLA-AERO in the slot (#2902). Read from the stored
  2302. # preset name rather than resolving the preset,
  2303. # because this runs on every AMS push and a cloud
  2304. # lookup here would be both slow and unavailable on
  2305. # the unauthenticated replay path.
  2306. spool_types = {printer_filament_type(spool.material).upper()}
  2307. if spool.slicer_filament_name:
  2308. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2309. # An imported local preset stores its type outright,
  2310. # which is what the assign path used -- and the name
  2311. # above may be unset. One keyed read, and only on a
  2312. # mismatch, which is rare.
  2313. #
  2314. # slicer_filament is free text up to fifty characters,
  2315. # so the digits have to be checked against the range
  2316. # of the integer primary key they are about to be
  2317. # compared with. Postgres raises on an out-of-range
  2318. # integer rather than simply not matching, and that
  2319. # would poison this session and abandon the rest of
  2320. # the cleanup pass.
  2321. lp_ref = (spool.slicer_filament or "").strip()
  2322. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2323. from backend.app.models.local_preset import LocalPreset as _LP
  2324. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2325. if lp_type:
  2326. spool_types.add(printer_filament_type(lp_type).upper())
  2327. if (
  2328. _colors_similar(cur_color, spool_color)
  2329. and printer_filament_type(cur_type).upper() in spool_types
  2330. ):
  2331. logger.info(
  2332. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2333. assignment.spool_id,
  2334. assignment.ams_id,
  2335. assignment.tray_id,
  2336. )
  2337. assignment.fingerprint_color = cur_color
  2338. assignment.fingerprint_type = cur_type
  2339. continue
  2340. logger.info(
  2341. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2342. assignment.spool_id,
  2343. assignment.ams_id,
  2344. assignment.tray_id,
  2345. cur_color,
  2346. cur_type,
  2347. fp_color,
  2348. fp_type,
  2349. spool.rgba if spool else "?",
  2350. spool.material if spool else "?",
  2351. )
  2352. stale.append(assignment) # Spool changed
  2353. slot_unlink_grace.settle(printer_id, "inventory", held)
  2354. # Snapshot slots before delete — ORM attribute access after the
  2355. # commit would refresh against a deleted row.
  2356. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2357. for a in stale:
  2358. await db.delete(a)
  2359. if stale:
  2360. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2361. # Commit any changes (stale deletions and/or fingerprint updates)
  2362. await db.commit()
  2363. # Tell open browsers the assignment is gone (#2575). Only the manual
  2364. # REST assign/unassign endpoints broadcast this event; without it the
  2365. # frontend's spool-assignments cache keeps rendering the unlinked
  2366. # spool on the slot until an unrelated refetch — which reads exactly
  2367. # like "the fix didn't work" (reporter verified: a browser refresh
  2368. # after the swap showed the correct state all along).
  2369. for ams_id, tray_id in unlinked_slots:
  2370. await ws_manager.broadcast(
  2371. {
  2372. "type": "spool_assignment_changed",
  2373. "printer_id": printer_id,
  2374. "ams_id": ams_id,
  2375. "tray_id": tray_id,
  2376. }
  2377. )
  2378. except Exception as e:
  2379. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2380. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2381. """Delete Spoolman slot rows whose held removal has run its grace period.
  2382. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2383. talks to Spoolman for every tray; this only needs the local rows, so it
  2384. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2385. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2386. not in a slot the presence bit calls occupied -- and nothing else.
  2387. """
  2388. logger = logging.getLogger(__name__)
  2389. try:
  2390. async with async_session() as db:
  2391. from backend.app.api.routes.settings import get_setting
  2392. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2393. from backend.app.services.ams_slot_presence import spool_present
  2394. enabled = await get_setting(db, "spoolman_enabled")
  2395. if not enabled or enabled.lower() != "true":
  2396. return
  2397. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2398. if sync_mode and sync_mode != "auto":
  2399. return
  2400. trays: dict[tuple[int, int], dict] = {}
  2401. for ams_unit in ams_data or []:
  2402. if not isinstance(ams_unit, dict):
  2403. continue
  2404. for tray in ams_unit.get("tray", []):
  2405. if isinstance(tray, dict):
  2406. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2407. rows = (
  2408. (
  2409. await db.execute(
  2410. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2411. )
  2412. )
  2413. .scalars()
  2414. .all()
  2415. )
  2416. held: set[tuple] = set()
  2417. expired: list[tuple[int, int]] = []
  2418. for row in rows:
  2419. tray = trays.get((row.ams_id, row.tray_id))
  2420. if tray is None or printing_now:
  2421. continue
  2422. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2423. continue
  2424. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2425. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2426. continue
  2427. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2428. expired.append((row.ams_id, row.tray_id))
  2429. else:
  2430. held.add(hold_key)
  2431. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2432. if not expired:
  2433. return
  2434. # A statement rather than ORM deletes, like the sync pass: the two
  2435. # can overlap, and a row the other already removed must not fail
  2436. # this commit.
  2437. for ams_id, tray_id in expired:
  2438. await db.execute(
  2439. delete(SpoolmanSlotAssignment).where(
  2440. SpoolmanSlotAssignment.printer_id == printer_id,
  2441. SpoolmanSlotAssignment.ams_id == ams_id,
  2442. SpoolmanSlotAssignment.tray_id == tray_id,
  2443. )
  2444. )
  2445. await db.commit()
  2446. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2447. for ams_id, tray_id in expired:
  2448. await ws_manager.broadcast(
  2449. {
  2450. "type": "spool_assignment_changed",
  2451. "printer_id": printer_id,
  2452. "ams_id": ams_id,
  2453. "tray_id": tray_id,
  2454. }
  2455. )
  2456. except Exception as e:
  2457. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2458. async def _recheck_held_unlinks(printer_id: int) -> None:
  2459. """Re-run just the slot cleanup against the printer's current AMS state.
  2460. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2461. passes otherwise run only when the AMS hash changes, and a slot that went
  2462. empty and stayed empty may never change it again.
  2463. """
  2464. status = printer_manager.get_status(printer_id)
  2465. # A disconnected printer's state is its last report, not a new one: acting
  2466. # on it would "confirm" a removal nobody has seen for the whole grace
  2467. # period. Leave the holds; the first push after reconnecting decides.
  2468. if status is None or not status.connected:
  2469. return
  2470. ams_raw = status.raw_data.get("ams")
  2471. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2472. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2473. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2474. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2475. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2476. async def on_ams_change(printer_id: int, ams_data: list):
  2477. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2478. logger = logging.getLogger(__name__)
  2479. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  2480. # on_print_complete may pop _active_sessions during our awaits (#880).
  2481. from backend.app.services.usage_tracker import _active_sessions
  2482. _print_active = printer_id in _active_sessions
  2483. # A slot that reports empty while a print is running is a filament runout,
  2484. # not a spool swap: the spool is still physically in the AMS, just
  2485. # consumed. Dropping either inventory backend's slot link there loses the
  2486. # only record of which spool fed the print, so the completion path can't
  2487. # charge the runout segment to anything. Both cleanup passes below consult
  2488. # this; computed once, up front, so neither depends on the other having run.
  2489. _unlink_state = printer_manager.get_status(printer_id)
  2490. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2491. # MQTT relay - publish AMS change
  2492. try:
  2493. printer_info = printer_manager.get_printer(printer_id)
  2494. if printer_info:
  2495. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2496. except Exception:
  2497. pass # Don't fail AMS callback if MQTT fails
  2498. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2499. # This ensures frontend gets immediate updates when AMS slots are configured
  2500. try:
  2501. state = printer_manager.get_status(printer_id)
  2502. if state:
  2503. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2504. await ws_manager.send_printer_status(
  2505. printer_id,
  2506. printer_state_to_dict(
  2507. state,
  2508. printer_id,
  2509. printer_manager.get_model(printer_id),
  2510. printer_manager.get_drying_targets(printer_id),
  2511. ),
  2512. )
  2513. except Exception as e:
  2514. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2515. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2516. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2517. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  2518. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2519. # "no existing assignment" for the same (printer, ams, tray) and race to
  2520. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2521. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2522. # bug stayed latent there. See _ams_assignment_locks comment for details.
  2523. try:
  2524. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2525. from sqlalchemy.orm import selectinload
  2526. from backend.app.api.routes.settings import get_setting
  2527. from backend.app.models.spool import Spool
  2528. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2529. from backend.app.services.spool_tag_matcher import (
  2530. auto_assign_spool,
  2531. create_spool_from_tray,
  2532. find_matching_untagged_spool,
  2533. get_spool_by_tag,
  2534. is_bambu_tag,
  2535. is_valid_tag,
  2536. link_tag_to_inventory_spool,
  2537. )
  2538. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2539. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2540. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2541. if not _spoolman_on or _spoolman_on.lower() != "true":
  2542. for ams_unit in ams_data:
  2543. if not isinstance(ams_unit, dict):
  2544. continue
  2545. ams_id = int(ams_unit.get("id", 0))
  2546. for tray in ams_unit.get("tray", []):
  2547. if not isinstance(tray, dict):
  2548. continue
  2549. tray_id = int(tray.get("id", 0))
  2550. tag_uid = tray.get("tag_uid", "")
  2551. tray_uuid = tray.get("tray_uuid", "")
  2552. tray_info_idx = tray.get("tray_info_idx", "")
  2553. if not tray.get("tray_type"):
  2554. # Slot reported empty — drop any cached unknown-tag
  2555. # broadcast so reinserting the same spool re-prompts.
  2556. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2557. continue # Empty slot
  2558. # Check if assignment already exists for this slot
  2559. existing = await db.execute(
  2560. select(SA)
  2561. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2562. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2563. )
  2564. existing_assignment = existing.scalar_one_or_none()
  2565. if existing_assignment:
  2566. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2567. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2568. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2569. # Skip during active prints: the usage tracker handles deduction
  2570. # precisely via 3MF data on print completion. Without this guard the
  2571. # AMS remain% SET and the usage tracker ADD both fire from the same
  2572. # MQTT message, doubling the deduction (#880).
  2573. if _print_active:
  2574. continue
  2575. remain_raw = tray.get("remain")
  2576. if (
  2577. remain_raw is not None
  2578. and existing_assignment.spool
  2579. and not existing_assignment.spool.weight_locked
  2580. ):
  2581. try:
  2582. remain_val = int(remain_raw)
  2583. except (TypeError, ValueError):
  2584. remain_val = -1
  2585. if 1 <= remain_val <= 100:
  2586. lw = existing_assignment.spool.label_weight or 1000
  2587. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2588. current_used = existing_assignment.spool.weight_used or 0
  2589. if new_used > current_used + 1:
  2590. logger.info(
  2591. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2592. existing_assignment.spool_id,
  2593. current_used,
  2594. new_used,
  2595. remain_val,
  2596. )
  2597. existing_assignment.spool.weight_used = new_used
  2598. await db.commit()
  2599. # Re-apply stored K-profile when the live tray's
  2600. # cali_idx drifted from the spool's stored profile.
  2601. # This catches "reset slot → re-read" and any other
  2602. # path where the firmware loses the user's K-profile
  2603. # selection while the SpoolAssignment row persists.
  2604. # Per the maintainer's rule: any time a spool tag is
  2605. # identified and matches inventory, the slot must be
  2606. # configured with the spool's stored settings. Without
  2607. # this block the existing-assignment branch only ran
  2608. # weight-sync and let the firmware-default cali_idx win.
  2609. try:
  2610. spool = existing_assignment.spool
  2611. if (
  2612. spool is not None
  2613. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  2614. and spool.k_profiles
  2615. ):
  2616. state = printer_manager.get_status(printer_id)
  2617. slot_nozzle = resolve_slot_nozzle(
  2618. state, ams_id, tray_id, printer_manager.get_model(printer_id)
  2619. )
  2620. nozzle_diameter = slot_nozzle.diameter
  2621. slot_extruder = slot_nozzle.extruder
  2622. # Prefer exact extruder match, fall back to
  2623. # extruder-agnostic kp for the same printer +
  2624. # nozzle. Avoids hard-skipping when the AMS is
  2625. # mapped differently than at calibration time.
  2626. matching_kp = None
  2627. fallback_kp = None
  2628. for kp in spool.k_profiles:
  2629. if (
  2630. kp.printer_id != printer_id
  2631. or kp.nozzle_diameter != nozzle_diameter
  2632. or kp.cali_idx is None
  2633. or not slot_nozzle.flow_matches(kp.nozzle_type)
  2634. ):
  2635. continue
  2636. if (
  2637. slot_extruder is not None
  2638. and kp.extruder is not None
  2639. and kp.extruder == slot_extruder
  2640. ):
  2641. matching_kp = kp
  2642. break
  2643. if fallback_kp is None:
  2644. fallback_kp = kp
  2645. chosen_kp = matching_kp or fallback_kp
  2646. if chosen_kp is not None:
  2647. live_cali_idx = tray.get("cali_idx")
  2648. # Only fire MQTT when the printer's live
  2649. # cali_idx differs from the stored value.
  2650. # Avoids spamming the broker on every
  2651. # MQTT push during steady-state operation.
  2652. if live_cali_idx != chosen_kp.cali_idx:
  2653. client = printer_manager.get_client(printer_id)
  2654. if client:
  2655. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  2656. client.extrusion_cali_sel(
  2657. ams_id=ams_id,
  2658. tray_id=tray_id,
  2659. cali_idx=chosen_kp.cali_idx,
  2660. filament_id=cali_filament_id,
  2661. nozzle_diameter=nozzle_diameter,
  2662. )
  2663. logger.info(
  2664. "Re-applied K-profile cali_idx=%d for spool %d "
  2665. "on printer %d AMS%d-T%d (live=%s drift detected)",
  2666. chosen_kp.cali_idx,
  2667. spool.id,
  2668. printer_id,
  2669. ams_id,
  2670. tray_id,
  2671. live_cali_idx,
  2672. )
  2673. except Exception:
  2674. logger.exception(
  2675. "K-profile re-apply failed for printer %d AMS%d-T%d",
  2676. printer_id,
  2677. ams_id,
  2678. tray_id,
  2679. )
  2680. continue
  2681. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2682. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2683. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2684. if not spool:
  2685. # Try matching an untagged inventory spool (same material/color)
  2686. spool = await find_matching_untagged_spool(db, tray)
  2687. if spool:
  2688. await link_tag_to_inventory_spool(db, spool, tray)
  2689. elif _auto_add_unknown:
  2690. spool = await create_spool_from_tray(db, tray)
  2691. else:
  2692. # Auto-add disabled: surface the slot so the
  2693. # user can add it manually via the UI.
  2694. await _broadcast_unknown_tag(
  2695. printer_id=printer_id,
  2696. ams_id=ams_id,
  2697. tray_id=tray_id,
  2698. tag_uid=tag_uid,
  2699. tray_uuid=tray_uuid,
  2700. tray_type=tray.get("tray_type"),
  2701. tray_color=tray.get("tray_color"),
  2702. tray_sub_brands=tray.get("tray_sub_brands"),
  2703. tray_count=len(ams_unit.get("tray", [])),
  2704. )
  2705. continue
  2706. # Slot matched (existing tag, untagged inventory
  2707. # match, or freshly auto-created spool) — drop any
  2708. # stale dedup so a future tag swap re-prompts.
  2709. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2710. await auto_assign_spool(
  2711. printer_id,
  2712. ams_id,
  2713. tray_id,
  2714. spool,
  2715. printer_manager,
  2716. db,
  2717. tray_info_idx=tray_info_idx,
  2718. )
  2719. await db.commit()
  2720. await ws_manager.broadcast(
  2721. {
  2722. "type": "spool_auto_assigned",
  2723. "printer_id": printer_id,
  2724. "ams_id": ams_id,
  2725. "tray_id": tray_id,
  2726. "spool_id": spool.id,
  2727. }
  2728. )
  2729. logger.info(
  2730. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2731. spool.id,
  2732. printer_id,
  2733. ams_id,
  2734. tray_id,
  2735. )
  2736. elif is_valid_tag(tag_uid, tray_uuid):
  2737. # Non-BL spool with some tag — let user choose
  2738. await _broadcast_unknown_tag(
  2739. printer_id=printer_id,
  2740. ams_id=ams_id,
  2741. tray_id=tray_id,
  2742. tag_uid=tag_uid,
  2743. tray_uuid=tray_uuid,
  2744. tray_type=tray.get("tray_type"),
  2745. tray_color=tray.get("tray_color"),
  2746. tray_sub_brands=tray.get("tray_sub_brands"),
  2747. tray_count=len(ams_unit.get("tray", [])),
  2748. )
  2749. # No-tag slots (generic non-RFID filament) are left alone:
  2750. # nothing to identify, prompting "+ Add" would just create
  2751. # ghost spools with empty tags on every confirm.
  2752. except Exception as e:
  2753. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2754. try:
  2755. async with async_session() as db:
  2756. from backend.app.api.routes.settings import get_setting
  2757. from backend.app.models.printer import Printer
  2758. # Check if Spoolman is enabled
  2759. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2760. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2761. return
  2762. # Check sync mode
  2763. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2764. if sync_mode and sync_mode != "auto":
  2765. return # Only sync on auto mode
  2766. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2767. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2768. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2769. # always owned by per-print tracking, never by AMS auto-sync. The
  2770. # setting is still read by the settings UI for backwards compat but
  2771. # has no effect on the sync path here.
  2772. # Get Spoolman URL
  2773. spoolman_url = await get_setting(db, "spoolman_url")
  2774. if not spoolman_url:
  2775. return
  2776. # Get or create Spoolman client
  2777. client = await get_spoolman_client()
  2778. if not client:
  2779. try:
  2780. client = await init_spoolman_client(spoolman_url)
  2781. except ValueError as exc:
  2782. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2783. return
  2784. # Check if Spoolman is reachable
  2785. if not await client.health_check():
  2786. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2787. return
  2788. # Get printer name for location
  2789. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2790. printer = result.scalar_one_or_none()
  2791. printer_name = printer.name if printer else f"Printer {printer_id}"
  2792. # OPTIMIZATION: Fetch all spools once before processing trays
  2793. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2794. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2795. try:
  2796. cached_spools = await client.get_spools()
  2797. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2798. except Exception as e:
  2799. logger.error(
  2800. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2801. printer_id,
  2802. e,
  2803. )
  2804. return
  2805. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2806. from sqlalchemy.orm import selectinload
  2807. from backend.app.models.spool_assignment import SpoolAssignment
  2808. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2809. from backend.app.services.ams_slot_presence import spool_present
  2810. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2811. # Built-in remaining weight, used by sync_ams_tray only when the
  2812. # firmware reports an unusable remain%/tray_weight for a slot.
  2813. #
  2814. # Left empty since #2812. This block runs in Spoolman mode only,
  2815. # and until then the built-in table was emptied on the switch, so
  2816. # there was never anything here to read and the fallback was inert.
  2817. # Preserving those rows makes it live again, and it is keyed by slot
  2818. # rather than by spool: after a mode switch the tray may well hold
  2819. # different filament, and ``create_spool`` writes ``remaining_weight``
  2820. # unconditionally, so a stale figure would be seeded into a brand new
  2821. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2822. # intent survives for whoever revisits the cross-mode fallback.
  2823. inventory_weights: dict[tuple[int, int], float] = {}
  2824. if not await spoolman_owns_assignments(db):
  2825. try:
  2826. assign_result = await db.execute(
  2827. select(SpoolAssignment)
  2828. .options(selectinload(SpoolAssignment.spool))
  2829. .where(SpoolAssignment.printer_id == printer_id)
  2830. )
  2831. for assignment in assign_result.scalars().all():
  2832. spool = assignment.spool
  2833. if spool and spool.label_weight > 0:
  2834. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2835. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2836. except Exception as e:
  2837. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2838. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2839. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2840. try:
  2841. slot_result = await db.execute(
  2842. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2843. )
  2844. for slot in slot_result.scalars().all():
  2845. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2846. except Exception as e:
  2847. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2848. # Sync each AMS tray and collect slot changes for DB persistence
  2849. synced = 0
  2850. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2851. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2852. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  2853. for ams_unit in ams_data:
  2854. if not isinstance(ams_unit, dict):
  2855. continue
  2856. ams_id = int(ams_unit.get("id", 0))
  2857. trays = ams_unit.get("tray", [])
  2858. for tray_data in trays:
  2859. if not isinstance(tray_data, dict):
  2860. continue
  2861. tray_id_raw = int(tray_data.get("id", 0))
  2862. tray = client.parse_ams_tray(ams_id, tray_data)
  2863. if not tray:
  2864. # Empty tray slot — record for local assignment cleanup
  2865. # and drop any cached unknown-tag broadcast so a
  2866. # reinserted spool re-prompts.
  2867. #
  2868. # Not during a running print: a slot that empties there
  2869. # is a filament runout, and the spool is still in the
  2870. # AMS. `spoolman_slot_assignments` is how a tag-less
  2871. # spool assigned through the Bambuddy UI is resolved at
  2872. # completion (#1459), so deleting the row mid-print
  2873. # loses the runout segment's usage — the same failure
  2874. # the internal inventory's auto-unlink had.
  2875. #
  2876. # Nor when firmware's presence bit says the slot is
  2877. # occupied. parse_ams_tray calls a tray with no type or
  2878. # no colour empty, and a spool the AMS cannot read has
  2879. # neither until something configures it — so a tag-less
  2880. # spool assigned through the UI had its row deleted by
  2881. # the first idle push after it was inserted. Same
  2882. # deletion as the internal inventory's in #3100, same
  2883. # answer, so the two modes stay in step.
  2884. #
  2885. # And only once the slot has stayed empty for the grace
  2886. # period -- the internal inventory's #3186 answer, for
  2887. # the same one-push blank.
  2888. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  2889. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  2890. if not printing_now and (
  2891. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  2892. ):
  2893. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2894. empty_slots.append((ams_id, tray_id_raw))
  2895. else:
  2896. spoolman_held.add(hold_key)
  2897. logger.info(
  2898. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  2899. "unlinking if it is still empty in %ds",
  2900. ams_id,
  2901. tray_id_raw,
  2902. linked_spool,
  2903. int(slot_unlink_grace.GRACE_SECONDS),
  2904. )
  2905. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2906. continue
  2907. spool_tag = (
  2908. tray.tray_uuid
  2909. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2910. else tray.tag_uid
  2911. )
  2912. # Provide the hint only when no RFID is available
  2913. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2914. try:
  2915. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2916. result = await client.sync_ams_tray(
  2917. tray,
  2918. printer_name,
  2919. db,
  2920. # Per-print tracking is the only weight writer (#1119).
  2921. # AMS auto-sync still maintains spool metadata / slot
  2922. # assignments but no longer touches remaining_weight.
  2923. disable_weight_sync=True,
  2924. cached_spools=cached_spools,
  2925. inventory_remaining=inv_remaining,
  2926. spoolman_spool_id_hint=hint,
  2927. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2928. )
  2929. if result is None and spool_tag and not auto_add_unknown_rfid:
  2930. # Spoolman skipped auto-create per user setting — surface
  2931. # the slot so the UI can offer "+ Add to inventory".
  2932. await _broadcast_unknown_tag(
  2933. printer_id=printer_id,
  2934. ams_id=ams_id,
  2935. tray_id=tray.tray_id,
  2936. tag_uid=tray.tag_uid or "",
  2937. tray_uuid=tray.tray_uuid or "",
  2938. tray_type=tray.tray_type,
  2939. tray_color=tray.tray_color,
  2940. tray_sub_brands=tray.tray_sub_brands,
  2941. tray_count=len(trays),
  2942. )
  2943. elif result:
  2944. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2945. if result:
  2946. synced += 1
  2947. if result.get("id"):
  2948. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2949. # If a new spool was created, add it to the cache
  2950. # so subsequent trays can find it if they reference the same tag
  2951. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  2952. if not spool_exists:
  2953. cached_spools.append(result)
  2954. logger.debug(
  2955. "[Printer %s] Added newly created spool %s to cache",
  2956. printer_id,
  2957. result["id"],
  2958. )
  2959. # Reconcile slot_preset_mappings (the same row internal
  2960. # mode keeps in sync via inventory + spool_tag_matcher).
  2961. # Without this the slot card surfaces the previous spool's
  2962. # preset name — same bug shape, different inventory mode.
  2963. from backend.app.services.slot_preset_writer import (
  2964. upsert_slot_preset_for_spoolman_spool,
  2965. )
  2966. await upsert_slot_preset_for_spoolman_spool(
  2967. db=db,
  2968. spoolman_spool=result,
  2969. tray_info_idx=tray.tray_info_idx or "",
  2970. tray_sub_brands=tray.tray_sub_brands or "",
  2971. tray_type=tray.tray_type or "",
  2972. printer_id=printer_id,
  2973. ams_id=ams_id,
  2974. tray_id=tray.tray_id,
  2975. )
  2976. except Exception as e:
  2977. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  2978. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  2979. if synced > 0:
  2980. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  2981. # Persist slot assignment changes to the local table
  2982. if slot_changes or empty_slots:
  2983. try:
  2984. for ams_id, tray_id, spool_id in slot_changes:
  2985. await db.execute(
  2986. text(
  2987. "INSERT INTO spoolman_slot_assignments"
  2988. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  2989. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  2990. " ON CONFLICT(printer_id, ams_id, tray_id)"
  2991. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  2992. ),
  2993. {
  2994. "printer_id": printer_id,
  2995. "ams_id": ams_id,
  2996. "tray_id": tray_id,
  2997. "spool_id": spool_id,
  2998. },
  2999. )
  3000. for ams_id, tray_id in empty_slots:
  3001. await db.execute(
  3002. delete(SpoolmanSlotAssignment).where(
  3003. SpoolmanSlotAssignment.printer_id == printer_id,
  3004. SpoolmanSlotAssignment.ams_id == ams_id,
  3005. SpoolmanSlotAssignment.tray_id == tray_id,
  3006. )
  3007. )
  3008. await db.commit()
  3009. except Exception as e:
  3010. await db.rollback()
  3011. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3012. else:
  3013. # Tell open browsers the slot changed. This loop rewrites
  3014. # slot_preset_mappings via upsert_slot_preset_for_spoolman_spool
  3015. # above, and the AMS slot card reads that row ahead of the
  3016. # live tray_info_idx -- so with no event the card keeps
  3017. # showing the previous spool's preset name. Internal mode
  3018. # raises spool_auto_assigned for the same reason; this loop
  3019. # broadcast nothing at all, which made Spoolman mode the
  3020. # worse half of the same bug. On the else branch so a
  3021. # failed commit stays silent and a broadcast failure cannot
  3022. # roll back rows that are already committed.
  3023. for ams_id, tray_id, *_ in (*slot_changes, *empty_slots):
  3024. await ws_manager.broadcast(
  3025. {
  3026. "type": "spool_assignment_changed",
  3027. "printer_id": printer_id,
  3028. "ams_id": ams_id,
  3029. "tray_id": tray_id,
  3030. }
  3031. )
  3032. except Exception as e:
  3033. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3034. # Largest finish photo attached to a notification; a bigger one is still linked.
  3035. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3036. async def _finish_photo_for_notification(
  3037. db, archive, archive_id: int, filename: str
  3038. ) -> tuple[str | None, bytes | None]:
  3039. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3040. With authentication off the link is the archive's own photo route, as it
  3041. always was: it opens without a login and doesn't expire. With
  3042. authentication on that route needs a media token, which nothing tapping a
  3043. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3044. link only ever answered 401. The photo is then saved as a notification
  3045. photo as well (utils/notification_photos.py) and the link points there: an
  3046. unguessable name that opens this one photo and nothing else, for 3 days.
  3047. The link is relative when no External URL is set. Bytes over
  3048. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3049. ``(None, None)`` when the photo can't be found.
  3050. """
  3051. from backend.app.api.routes.settings import get_setting
  3052. from backend.app.core.auth import is_auth_enabled
  3053. from backend.app.utils.archive_paths import find_archive_photo
  3054. from backend.app.utils.notification_photos import save_notification_photo
  3055. log = logging.getLogger(__name__)
  3056. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3057. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3058. photo_bytes: bytes | None = None
  3059. try:
  3060. photo_path = find_archive_photo(archive, filename)
  3061. if photo_path is not None:
  3062. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3063. except Exception as e:
  3064. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3065. try:
  3066. auth_on = await is_auth_enabled(db)
  3067. except Exception:
  3068. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3069. if auth_on:
  3070. url = None
  3071. if photo_bytes:
  3072. try:
  3073. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3074. url = f"{base}/api/v1/notifications/photos/{name}"
  3075. except Exception as e:
  3076. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3077. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3078. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3079. return url, None
  3080. if photo_bytes:
  3081. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3082. return url, photo_bytes
  3083. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3084. """Capture a camera snapshot for notification image attachment.
  3085. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3086. Uses: external camera > buffered frame > fresh capture.
  3087. Turns the chamber light on for the picture when the printer asks for it
  3088. (#1655). ``light=False`` is for callers that capture all through a print,
  3089. where the light would flash with every frame.
  3090. """
  3091. if not printer:
  3092. return None
  3093. async with camera_light(printer if light else None):
  3094. return await _capture_snapshot_frame(printer_id, printer, logger)
  3095. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3096. """The capture behind ``_capture_snapshot_for_notification``."""
  3097. try:
  3098. from backend.app.api.routes.settings import get_setting
  3099. async with async_session() as db:
  3100. capture_enabled = await get_setting(db, "capture_finish_photo")
  3101. if capture_enabled is not None and capture_enabled.lower() != "true":
  3102. return None
  3103. # Try external camera first
  3104. if printer.external_camera_enabled and printer.external_camera_url:
  3105. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3106. from backend.app.api.routes.camera import live_frame_for_capture
  3107. from backend.app.services.external_camera import capture_frame
  3108. # An external camera allows one reader, so capturing while a viewer
  3109. # is attached fails (#2707). A None here falls through to the paths
  3110. # below exactly as a failed capture did.
  3111. defer, buffered = live_frame_for_capture(printer_id)
  3112. if defer:
  3113. frame_data = buffered
  3114. else:
  3115. frame_data = await capture_frame(
  3116. printer.external_camera_url,
  3117. printer.external_camera_type or "mjpeg",
  3118. snapshot_url=printer.external_camera_snapshot_url,
  3119. )
  3120. if frame_data and len(frame_data) <= 2_500_000:
  3121. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3122. return _apply_camera_rotation(frame_data, printer, logger)
  3123. # Try buffered frame from active stream
  3124. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3125. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3126. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3127. buffered_frame = get_buffered_frame(printer_id)
  3128. if (active_for_printer or active_chamber) and buffered_frame:
  3129. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3130. if len(buffered_frame) <= 2_500_000:
  3131. return _apply_camera_rotation(buffered_frame, printer, logger)
  3132. # Fresh capture from printer camera
  3133. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3134. from backend.app.services.camera import capture_camera_frame_bytes
  3135. frame_data = await capture_camera_frame_bytes(
  3136. printer.ip_address, printer.access_code, printer.model, timeout=15
  3137. )
  3138. if frame_data and len(frame_data) <= 2_500_000:
  3139. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3140. return _apply_camera_rotation(frame_data, printer, logger)
  3141. except Exception as e:
  3142. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3143. return None
  3144. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3145. """#1867: bank a recent in-print camera frame for the finish photo.
  3146. Called on every layer change and (#2547) on every print-progress advance.
  3147. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3148. path has a pre-End-G-code image for prints that end with a plate swap.
  3149. Both drivers are print telemetry that stops the instant printing ends: no
  3150. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3151. plate swap) executes. So the last banked frame is always the finished print,
  3152. never the swapped plate — that property is what the #1867 path relies on and
  3153. it must survive any change to the throttle below.
  3154. Layer changes alone were not enough: they stop when the *final* layer
  3155. begins, which on a three-minute last layer left the bank stale by the whole
  3156. length of that layer (#2547). Progress keeps ticking through it.
  3157. Best-effort: any failure just leaves the previous banked frame.
  3158. """
  3159. logger = logging.getLogger(__name__)
  3160. client = printer_manager.get_client(printer_id)
  3161. state = client.state if client else None
  3162. if not state or state.state != "RUNNING":
  3163. return
  3164. # Only during actual extrusion — firmware ticks layer_num during the
  3165. # pre-print calibration sequence, whose sub-stages are non-zero.
  3166. if state.mc_print_sub_stage not in (None, 0):
  3167. return
  3168. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3169. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3170. # now that progress advances also drive banking, that exemption would fire a
  3171. # camera grab on every percent tick of the last layer. Bambu printers accept
  3172. # one RTSP client at a time, so each grab contends with the live view.
  3173. now = time.monotonic()
  3174. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3175. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3176. return
  3177. total = state.total_layers or 0
  3178. try:
  3179. async with async_session() as db:
  3180. from backend.app.models.printer import Printer
  3181. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3182. printer = result.scalar_one_or_none()
  3183. if not printer:
  3184. return
  3185. # Reuses the notification snapshot path, which honours the
  3186. # `capture_finish_photo` setting (returns None when disabled) so we
  3187. # don't bank frames the user never asked for. Without the chamber light
  3188. # (#1655): this runs every 25 seconds for the whole print.
  3189. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3190. if frame:
  3191. _inprint_frame_bank[printer_id] = frame
  3192. _inprint_frame_bank_ts[printer_id] = now
  3193. logger.debug(
  3194. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3195. printer_id,
  3196. layer_num,
  3197. total,
  3198. len(frame),
  3199. )
  3200. except Exception as e:
  3201. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3202. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3203. """Apply camera rotation to snapshot image if configured."""
  3204. from backend.app.services.camera import apply_camera_rotation
  3205. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3206. async def _send_print_start_notification(
  3207. printer_id: int,
  3208. data: dict,
  3209. archive_data: dict | None = None,
  3210. logger=None,
  3211. ):
  3212. """Helper to send print start notification with optional archive data."""
  3213. if logger is None:
  3214. logger = logging.getLogger(__name__)
  3215. try:
  3216. async with async_session() as db:
  3217. from backend.app.models.printer import Printer
  3218. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3219. printer = result.scalar_one_or_none()
  3220. printer_name = printer.name if printer else f"Printer {printer_id}"
  3221. # Capture camera snapshot for notification image attachment
  3222. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3223. if image_data:
  3224. if archive_data is None:
  3225. archive_data = {}
  3226. archive_data["image_data"] = image_data
  3227. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3228. # Send user-specific email notification for print start
  3229. if archive_data and archive_data.get("created_by_id"):
  3230. await notification_service.send_user_print_email(
  3231. event_type="user_print_start",
  3232. created_by_id=archive_data["created_by_id"],
  3233. printer_name=printer_name,
  3234. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3235. db=db,
  3236. )
  3237. except Exception as e:
  3238. logger.warning("Notification on_print_start failed: %s", e)
  3239. async def _dispatch_user_print_email(
  3240. status: str,
  3241. created_by_id: int | None,
  3242. printer_name: str,
  3243. filename: str,
  3244. db,
  3245. image_data: bytes | None = None,
  3246. finish_photo_url: str | None = None,
  3247. ) -> None:
  3248. """Send a user-specific print-completion email based on print status.
  3249. Maps the normalised print status to the correct event type and delegates
  3250. to :meth:`NotificationService.send_user_print_email`. A single helper
  3251. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3252. "stopped"`` dispatch block at every call site.
  3253. Does nothing if *created_by_id* is ``None``.
  3254. """
  3255. if created_by_id is None:
  3256. return
  3257. if status == "completed":
  3258. event_type = "user_print_complete"
  3259. elif status == "failed":
  3260. event_type = "user_print_failed"
  3261. elif status in ("stopped", "aborted", "cancelled"):
  3262. event_type = "user_print_stopped"
  3263. else:
  3264. return
  3265. await notification_service.send_user_print_email(
  3266. event_type=event_type,
  3267. created_by_id=created_by_id,
  3268. printer_name=printer_name,
  3269. filename=filename,
  3270. db=db,
  3271. image_data=image_data,
  3272. finish_photo_url=finish_photo_url,
  3273. )
  3274. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3275. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3276. try:
  3277. from backend.app.services.archive import extract_printable_objects_from_archive
  3278. client = printer_manager.get_client(printer_id)
  3279. if not client:
  3280. return
  3281. # Extract with positions for UI overlay, scoped to the plate that
  3282. # is printing — resolve_plate_id is the same resolver /cover uses,
  3283. # so the object list can't disagree with the thumbnail it is drawn
  3284. # over (#2522).
  3285. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3286. app_settings.base_dir / archive.file_path,
  3287. plate_number=resolve_plate_id(client.state),
  3288. )
  3289. if printable_objects:
  3290. client.state.printable_objects = printable_objects
  3291. client.state.printable_objects_bbox_all = bbox_all
  3292. client.state.skipped_objects = []
  3293. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3294. except Exception as e:
  3295. logger.debug("Failed to extract printable objects from archive: %s", e)
  3296. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3297. """Put the skip-objects list back after a restart mid-print.
  3298. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3299. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3300. which the #1304 guard suppresses on the first RUNNING push after startup.
  3301. Everything else this hook restores (the archive, the usage-tracking session,
  3302. the timelapse baseline) was already handled; the object list was not, so a
  3303. restart mid-print took skip-objects away for the rest of that print.
  3304. Nothing recovered it either: the printer card gates its Skip button on the
  3305. object count, and the one endpoint that can rebuild the list is reachable
  3306. only from the modal that button opens.
  3307. Anchored on ``subtask_id``, which the firmware mints per print, so a
  3308. leftover ``status="printing"`` row from a completion we never saw cannot
  3309. hand this print someone else's objects. Without one, nothing is loaded
  3310. rather than guessed — the reload path on ``GET /print/objects`` covers that
  3311. case on demand.
  3312. """
  3313. client = printer_manager.get_client(printer_id)
  3314. if client is None or client.state.printable_objects:
  3315. return
  3316. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  3317. if subtask_id in ("", "0"):
  3318. return
  3319. from backend.app.models.archive import PrintArchive
  3320. archive = await db.scalar(
  3321. select(PrintArchive)
  3322. .where(
  3323. PrintArchive.printer_id == printer_id,
  3324. PrintArchive.status == "printing",
  3325. PrintArchive.subtask_id == subtask_id,
  3326. )
  3327. .order_by(PrintArchive.created_at.desc())
  3328. .limit(1)
  3329. )
  3330. if archive is not None:
  3331. _load_objects_from_archive(archive, printer_id, logger)
  3332. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3333. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3334. # past it; the second covers a handshake that failed again on the way back and
  3335. # armed a fresh one. Module-level so tests can shrink them.
  3336. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3337. # Retry ladder for the other temporary give-up: the file service answered and
  3338. # the transfer still did not finish, which at print start is usually the printer
  3339. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3340. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3341. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3342. # two cover a printer that stays busy well into the print.
  3343. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3344. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3345. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3346. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3347. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3348. # by view, so two views race), the cool-off retry task, and print completion.
  3349. # Without this they each read file_path == "" and each run a full copy, so the row
  3350. # ends up pointing at one timestamped directory while the others sit orphaned.
  3351. #
  3352. # Keyed by printer rather than archive because a printer runs one print at a time,
  3353. # which makes the two equally strong here — and it bounds the dict by printer
  3354. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3355. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3356. # resuming, so "no waiters" is not a question this API can answer.
  3357. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3358. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3359. """Fill in a no-3MF archive from a 3MF that turned up later.
  3360. Returns True when the row was upgraded. Safe to call speculatively: it
  3361. verifies the archive still exists, is still a fallback, and that the file
  3362. is a readable 3MF before touching anything.
  3363. Serialised per printer — see ``_fallback_recovery_locks``.
  3364. """
  3365. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3366. async with lock:
  3367. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id)
  3368. async def _recover_fallback_archive_locked(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3369. """The body of :func:`_recover_fallback_archive`, under its per-printer lock."""
  3370. import zipfile
  3371. from backend.app.models.archive import PrintArchive
  3372. from backend.app.services.archive import ArchiveService
  3373. logger = logging.getLogger(__name__)
  3374. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3375. return False
  3376. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3377. # A truncated or half-written download is worse than no download: it
  3378. # would replace an honest empty archive with wrong metadata.
  3379. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3380. return False
  3381. async with async_session() as db:
  3382. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3383. if archive is None or archive.deleted_at is not None:
  3384. return False
  3385. if archive.file_path:
  3386. # Already recovered, or never was a fallback. Either way there is a
  3387. # real 3MF attached and overwriting it is not this function's job.
  3388. return False
  3389. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3390. service = ArchiveService(db)
  3391. recovered = await service.archive_print(
  3392. printer_id=printer_id,
  3393. source_file=source_3mf,
  3394. print_data={**print_data, "status": archive.status or "printing"},
  3395. subtask_id=archive.subtask_id,
  3396. update_archive_id=archive.id,
  3397. )
  3398. if recovered is None:
  3399. return False
  3400. logger.info(
  3401. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3402. archive_id,
  3403. source_3mf,
  3404. recovered.file_size,
  3405. )
  3406. # `archive_updated`, not `archive_created` — the row was already on the
  3407. # Archives page as an empty card and is now filled in, not new.
  3408. await ws_manager.send_archive_updated(
  3409. {
  3410. "id": recovered.id,
  3411. "printer_id": recovered.printer_id,
  3412. "filename": recovered.filename,
  3413. "print_name": recovered.print_name,
  3414. "status": recovered.status,
  3415. }
  3416. )
  3417. return True
  3418. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path) -> bool:
  3419. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3420. Called from the paths that pull a 3MF for a print that is already under way
  3421. — chiefly the cover endpoint, which downloads the very file the archive flow
  3422. could not get and, before #2957, used it for a thumbnail and nothing else.
  3423. The bytes are already local, so this costs a parse and a row update.
  3424. No-op when the running print has a real archive, which is the common case.
  3425. """
  3426. from backend.app.models.archive import PrintArchive
  3427. logger = logging.getLogger(__name__)
  3428. # `_active_prints` is keyed on the raw names seen at print start — the
  3429. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3430. # Callers here arrive with whichever variant their own path produced, so
  3431. # match on the same normalization the download cache uses rather than on an
  3432. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3433. # endpoint find an archive registered under "Desktop_Goose".
  3434. wanted = normalize_3mf_name(name)
  3435. archive_id = None
  3436. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3437. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3438. archive_id = value
  3439. break
  3440. if archive_id is None:
  3441. return False
  3442. async with async_session() as db:
  3443. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3444. # Cheap pre-check so the common case (a normal archive) does no work.
  3445. if archive is None or archive.file_path or archive.deleted_at is not None:
  3446. return False
  3447. try:
  3448. return await _recover_fallback_archive(archive_id, path, printer_id)
  3449. except Exception as e:
  3450. # Recovery is opportunistic. A failure here must never take down the
  3451. # caller, which is usually just trying to render a thumbnail.
  3452. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3453. return False
  3454. def _schedule_fallback_3mf_retry(
  3455. printer_id: int,
  3456. archive_id: int,
  3457. filenames: list[str],
  3458. delays: tuple[float, ...] | None = None,
  3459. reason: str = REASON_FTPS_COOLOFF,
  3460. ) -> None:
  3461. """Re-attempt the 3MF download after a temporary give-up.
  3462. ``reason`` says which give-up this is, and picks the default ladder: an
  3463. FTPS cool-off has to be waited out, while a transfer that timed out under
  3464. contention is worth asking about again straight away (#3063). It is only
  3465. read for the ladder and the log line -- the retry itself is identical, since
  3466. in both cases the file is on the printer and the last attempt at it failed
  3467. for a reason that does not last.
  3468. """
  3469. logger = logging.getLogger(__name__)
  3470. if delays is None:
  3471. delays = (
  3472. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3473. if reason == REASON_FTP_TRANSFER_FAILED
  3474. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3475. )
  3476. async def _retry() -> None:
  3477. from backend.app.models.archive import PrintArchive
  3478. from backend.app.models.printer import Printer
  3479. for delay in delays:
  3480. await asyncio.sleep(delay)
  3481. async with async_session() as db:
  3482. archive = (
  3483. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3484. ).scalar_one_or_none()
  3485. if archive is None or archive.deleted_at is not None or archive.file_path:
  3486. return
  3487. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3488. if printer is None:
  3489. return
  3490. # Read the fields while the session is open rather than touching
  3491. # a detached instance minutes later, mid-download.
  3492. printer_ip = printer.ip_address
  3493. printer_code = printer.access_code
  3494. printer_model = printer.model
  3495. # Someone else may have fetched it in the meantime — the cover
  3496. # endpoint routinely does, and its copy is the same bytes.
  3497. for name in filenames:
  3498. cached = get_cached_3mf(printer_id, name)
  3499. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3500. return
  3501. if ftps_handshake_blocked(printer_ip):
  3502. logger.info(
  3503. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3504. printer_id,
  3505. archive_id,
  3506. )
  3507. continue
  3508. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3509. for candidate in filenames:
  3510. # Bare name only. These come from the print-start flow, which
  3511. # already strips the path, but the local temp write must not
  3512. # depend on that holding for every future caller — a name that
  3513. # is absolute or contains ".." would otherwise escape the data
  3514. # volume via the `/` operator.
  3515. name = Path(candidate).name
  3516. if not name or name in (".", ".."):
  3517. continue
  3518. if not name.endswith(".3mf"):
  3519. name = f"{name}.3mf"
  3520. temp_path = app_settings.archive_dir / "temp" / name
  3521. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3522. try:
  3523. hit = await download_file_try_paths_async(
  3524. printer_ip,
  3525. printer_code,
  3526. ftp_probe_paths(name),
  3527. temp_path,
  3528. socket_timeout=ftp_timeout,
  3529. printer_model=printer_model,
  3530. )
  3531. except Exception as e:
  3532. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3533. continue
  3534. if not hit:
  3535. continue
  3536. cache_3mf_download(printer_id, name, temp_path)
  3537. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3538. return
  3539. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3540. async def _guarded() -> None:
  3541. try:
  3542. await _retry()
  3543. except asyncio.CancelledError:
  3544. raise
  3545. except Exception as e:
  3546. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3547. finally:
  3548. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3549. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3550. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3551. if existing and not existing.done():
  3552. existing.cancel()
  3553. task = asyncio.create_task(_guarded())
  3554. _fallback_3mf_retry_tasks[printer_id] = task
  3555. logger.info(
  3556. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3557. archive_id,
  3558. reason,
  3559. printer_id,
  3560. ", ".join(f"{d:g}s" for d in delays),
  3561. )
  3562. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3563. """Whether an archive created here should ask for the print's outcome (#1898).
  3564. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3565. branches below: a queued job already has its archive and takes the
  3566. expected-print branch, where the queue item's own ``confirm_outcome``
  3567. decides. The queue is still consulted, because a restart mid-print empties
  3568. ``_expected_prints`` — without the check the setting could override a queue
  3569. item that deliberately has the flag off. Any failure answers "don't ask":
  3570. an unwanted prompt is worse than a missing one, and this must never be the
  3571. reason a print goes unarchived.
  3572. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3573. leaves one behind when a completion cannot be matched to it
  3574. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3575. only takes it back once the printer has sat connected and terminal for
  3576. minutes. Until then every screen-started print on that printer would
  3577. silently lose its prompt, so the row is held against ``observed_name`` by
  3578. the same comparison a completion uses: a positive disagreement means the row
  3579. is about some other run and this print is external after all.
  3580. """
  3581. logger = logging.getLogger(__name__)
  3582. try:
  3583. # A savepoint rather than a rollback of the caller's transaction on
  3584. # failure: a failed statement leaves the transaction unusable, but a
  3585. # full rollback also expires every object the caller has loaded (the
  3586. # printer, the archive it just created), and on an async session the
  3587. # next attribute read then raises instead of reloading. Everything here
  3588. # is a read, so undoing the savepoint loses nothing.
  3589. async with db.begin_nested():
  3590. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3591. except Exception as e:
  3592. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3593. return False
  3594. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3595. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3596. from backend.app.api.routes.settings import get_setting, setting_is_true
  3597. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3598. return False
  3599. from backend.app.models.print_queue import PrintQueueItem
  3600. dispatched_here = await db.scalar(
  3601. select(PrintQueueItem)
  3602. .where(
  3603. PrintQueueItem.printer_id == printer_id,
  3604. PrintQueueItem.status == "printing",
  3605. )
  3606. .limit(1)
  3607. )
  3608. if dispatched_here is None:
  3609. return True
  3610. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3611. observed = (observed_name or "").strip()
  3612. if not expected or not observed or _subtask_names_match(expected, observed):
  3613. logger.info(
  3614. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3615. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3616. printer_id,
  3617. dispatched_here.id,
  3618. )
  3619. return False
  3620. logger.info(
  3621. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3622. "%r; treating this as an externally started print.",
  3623. dispatched_here.id,
  3624. printer_id,
  3625. expected,
  3626. observed,
  3627. )
  3628. return True
  3629. async def _dispatch_outcome_confirmation_safely(
  3630. db,
  3631. printer_id: int,
  3632. printer_name: str,
  3633. data: dict,
  3634. archive_id: int,
  3635. archive_data: dict | None = None,
  3636. ) -> None:
  3637. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3638. The completion task sends the per-user print email on the same session
  3639. right after the prompt. A failed statement in the prompt leaves that
  3640. session needing a rollback, and without one the email step fails with
  3641. PendingRollbackError; the prompt is the optional part, so it must not be
  3642. the reason the email never goes out.
  3643. """
  3644. try:
  3645. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3646. except Exception as e:
  3647. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  3648. try:
  3649. await db.rollback()
  3650. except Exception:
  3651. pass
  3652. async def dispatch_outcome_confirmation(
  3653. db,
  3654. printer_id: int,
  3655. printer_name: str,
  3656. data: dict,
  3657. archive_id: int,
  3658. archive_data: dict | None = None,
  3659. ) -> bool:
  3660. """Emit the post-print outcome prompt for a completed archive (#1898).
  3661. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3662. queue item, or from ``confirm_outcome_external_prints`` for a print
  3663. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3664. question still open. Mints the per-archive capability token the one-tap
  3665. verdict links carry.
  3666. Lives here rather than inline in ``on_print_complete``'s notification task
  3667. because that task swallows every exception: extracted, the gate and the two
  3668. emissions can be driven by a test, which is the only thing standing between
  3669. a regression here and a farm that quietly stops asking.
  3670. Returns whether a prompt was sent.
  3671. """
  3672. logger = logging.getLogger(__name__)
  3673. from backend.app.models.archive import PrintArchive
  3674. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3675. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3676. return False
  3677. import secrets as _secrets
  3678. # A spent token stays on the row so the one-tap route can recognise it, so
  3679. # "has a token" no longer means "answerable". A prompt going out now needs a
  3680. # live one: mint a new token whenever the stored one is already spent, or
  3681. # every button in the new message would land on the already-answered page.
  3682. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  3683. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  3684. confirm_archive.confirm_token_used_at = None
  3685. await db.commit()
  3686. from backend.app.api.routes.settings import get_external_base_url, get_setting
  3687. base = await get_external_base_url(db)
  3688. if not await get_setting(db, "external_url"):
  3689. # Both the Telegram inline keyboard and the ntfy action buttons need an
  3690. # absolute URL, so an unconfigured install used to get a message body
  3691. # with two unusable relative paths and no buttons at all. The shared
  3692. # fallback at least produces tappable links; say which setting makes
  3693. # them resolve from a phone.
  3694. logger.warning(
  3695. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  3696. "Set Settings → External URL so they resolve away from this host.",
  3697. base,
  3698. )
  3699. token = confirm_archive.confirm_token
  3700. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  3701. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  3702. confirm_url = f"{base}/archives?confirm={archive_id}"
  3703. await ws_manager.send_print_confirm_request(
  3704. printer_id,
  3705. {
  3706. "archive_id": archive_id,
  3707. "print_name": confirm_archive.print_name or confirm_archive.filename,
  3708. },
  3709. )
  3710. await notification_service.on_print_confirm_request(
  3711. printer_id,
  3712. printer_name,
  3713. data,
  3714. db,
  3715. archive_data=archive_data,
  3716. good_url=good_url,
  3717. reject_url=reject_url,
  3718. confirm_url=confirm_url,
  3719. archive_id=archive_id,
  3720. )
  3721. return True
  3722. async def _printer_gone(db, printer_id: int) -> bool:
  3723. """Whether the printer was deleted. A column read: the session's loaded
  3724. Printer would otherwise answer for the database."""
  3725. from backend.app.models.printer import Printer
  3726. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  3727. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  3728. """Remove the archive just written if its printer was deleted meanwhile.
  3729. The delete route sweeps the printer's archives before it commits, so a row
  3730. committed after that sweep (the check before writing passed while the
  3731. delete was still uncommitted) is left for a printer that will never report
  3732. the print's end. A row the sweep reached is the route's: deleted with the
  3733. printer's archives, or detached (printer_id NULL) when the user kept them,
  3734. and then left as it is. Either way nothing is registered for it. Run after
  3735. the archive's commit, before anything is registered for it.
  3736. """
  3737. from backend.app.models.archive import PrintArchive
  3738. if not await _printer_gone(db, printer_id):
  3739. return False
  3740. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  3741. if owner == printer_id:
  3742. logging.getLogger(__name__).info(
  3743. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  3744. )
  3745. await ArchiveService(db).delete_archive(archive_id)
  3746. await forget_printer(printer_id)
  3747. return True
  3748. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  3749. """After an IntegrityError on a print start's archive write: whether it was
  3750. the printer being deleted, forgotten then (the caller returns).
  3751. PostgreSQL: the delete route locks the printer from its archive sweep to its
  3752. commit, so an archive written or adopted for it meanwhile (one that sets
  3753. printer_id) waits and the printer's foreign key then refuses it. That is
  3754. the printer being deleted, not an error; anything else is re-raised by the
  3755. caller.
  3756. """
  3757. await db.rollback()
  3758. if not await _printer_gone(db, printer_id):
  3759. return False
  3760. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  3761. await forget_printer(printer_id)
  3762. return True
  3763. async def _forget_if_printer_gone(printer_id: int) -> None:
  3764. """At the end of a print start: the slow steps after the last check (smart
  3765. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  3766. printer's delete and its forget_printer, and then wrote state back.
  3767. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  3768. SQLite; PostgreSQL refuses it.)
  3769. Its own session: those steps can leave the handler's needing a rollback (a
  3770. write to the archive the delete removed). Never raises: it runs inside the
  3771. fallback branch's try, whose except reports the archive as failed.
  3772. """
  3773. try:
  3774. async with async_session() as db:
  3775. gone = await _printer_gone(db, printer_id)
  3776. if gone:
  3777. await forget_printer(printer_id)
  3778. except Exception:
  3779. logging.getLogger(__name__).warning(
  3780. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  3781. )
  3782. async def on_print_start(printer_id: int, data: dict):
  3783. """Handle print start - archive the 3MF file immediately."""
  3784. logger = logging.getLogger(__name__)
  3785. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3786. try:
  3787. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  3788. except Exception:
  3789. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  3790. # Clear any stale user-stopped flag from previous print cycles
  3791. _user_stopped_printers.discard(printer_id)
  3792. # A new print starts its milestones from zero (#3211). The status path only
  3793. # resets on progress below 5 while not printing, which a printer that goes
  3794. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  3795. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  3796. # or on resume from pause, so it cannot repeat a milestone mid-print.
  3797. _last_progress_milestone[printer_id] = 0
  3798. _kill_switch_notification_tasks.pop(printer_id, None)
  3799. # #1721: drop any leftover pre-captured finish frame from a prior print
  3800. # so a never-consumed cache entry can't bleed into the new print's photo.
  3801. _stage22_finish_frames.pop(printer_id, None)
  3802. # #1867: same for the in-print frame bank — a queued print must not reuse
  3803. # the previous job's banked frame.
  3804. _inprint_frame_bank.pop(printer_id, None)
  3805. _inprint_frame_bank_ts.pop(printer_id, None)
  3806. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3807. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3808. # print's flag instead of inheriting it.
  3809. print_dispatch_context.adopt(printer_id)
  3810. # Cancel any active bed cooldown waiter for this printer
  3811. if _bed_cool_waiters.pop(printer_id, None):
  3812. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  3813. # Clear cached cover images so the new print's thumbnail is fetched fresh
  3814. from backend.app.api.routes.printers import clear_cover_cache
  3815. clear_cover_cache(printer_id)
  3816. await ws_manager.send_print_start(printer_id, data)
  3817. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  3818. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  3819. # MQTT relay - publish print start
  3820. try:
  3821. printer_info = printer_manager.get_printer(printer_id)
  3822. if printer_info:
  3823. await mqtt_relay.on_print_start(
  3824. printer_id,
  3825. printer_info.name,
  3826. printer_info.serial_number,
  3827. data.get("filename", ""),
  3828. data.get("subtask_name", ""),
  3829. )
  3830. except Exception:
  3831. pass # Don't fail print start callback if MQTT fails
  3832. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  3833. # and mapping, and the seeded tray-change log.
  3834. #
  3835. # Unconditional, for both inventory backends. This only *captures* — the
  3836. # writing is still split, with the internal tracker skipped at completion
  3837. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  3838. # carries its plate-scoped 3MF figures and stored mapping, but not the
  3839. # tray-change log, and that log is the only record of which spool fed
  3840. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  3841. # it on one side only would leave Spoolman users with the mid-print
  3842. # restart bug this fixes for everyone else.
  3843. try:
  3844. async with async_session() as db:
  3845. from backend.app.api.routes.settings import get_setting
  3846. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  3847. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3848. await usage_on_print_start(
  3849. printer_id,
  3850. data,
  3851. printer_manager,
  3852. db=db,
  3853. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  3854. )
  3855. except Exception as e:
  3856. logger.warning("Usage tracker on_print_start failed: %s", e)
  3857. # Track if notification was sent (to avoid sending twice)
  3858. notification_sent = False
  3859. # Smart plug automation: turn on plug when print starts
  3860. try:
  3861. async with async_session() as db:
  3862. await smart_plug_manager.on_print_start(printer_id, db)
  3863. except Exception as e:
  3864. logger.warning("Smart plug on_print_start failed: %s", e)
  3865. async with async_session() as db:
  3866. from backend.app.models.printer import Printer
  3867. from backend.app.services.bambu_ftp import list_files_async
  3868. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3869. printer = result.scalar_one_or_none()
  3870. # Plate detection check - pause if objects detected on build plate
  3871. logger.info(
  3872. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  3873. )
  3874. if printer and printer.plate_detection_enabled:
  3875. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  3876. # Release the pooled DB connection before the plate-detection camera
  3877. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  3878. # printer SELECT has run so far — nothing to persist — so this commit
  3879. # is a data-noop that ends the read transaction and returns the
  3880. # connection to the pool during the I/O (issue #2572). expire_on_commit
  3881. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  3882. # archive lookups below re-acquire a fresh connection on next execute.
  3883. await db.commit()
  3884. try:
  3885. from backend.app.services.plate_detection import check_plate_empty
  3886. # Build ROI tuple from printer settings if available
  3887. roi = None
  3888. if all(
  3889. [
  3890. printer.plate_detection_roi_x is not None,
  3891. printer.plate_detection_roi_y is not None,
  3892. printer.plate_detection_roi_w is not None,
  3893. printer.plate_detection_roi_h is not None,
  3894. ]
  3895. ):
  3896. roi = (
  3897. printer.plate_detection_roi_x,
  3898. printer.plate_detection_roi_y,
  3899. printer.plate_detection_roi_w,
  3900. printer.plate_detection_roi_h,
  3901. )
  3902. # Auto-turn on chamber light if it's off for better detection
  3903. light_was_off = False
  3904. client = printer_manager.get_client(printer_id)
  3905. if client and client.state:
  3906. light_was_off = not client.state.chamber_light
  3907. if light_was_off:
  3908. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  3909. client.set_chamber_light(True)
  3910. # Wait for light to physically turn on and camera to adjust exposure
  3911. await asyncio.sleep(2.5)
  3912. plate_photo_data = None
  3913. objects_detected = False
  3914. try:
  3915. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  3916. plate_result = await check_plate_empty(
  3917. printer_id=printer_id,
  3918. ip_address=printer.ip_address,
  3919. access_code=printer.access_code,
  3920. model=printer.model,
  3921. include_debug_image=False,
  3922. external_camera_url=printer.external_camera_url,
  3923. external_camera_type=printer.external_camera_type,
  3924. use_external=printer.external_camera_enabled,
  3925. roi=roi,
  3926. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  3927. )
  3928. objects_detected = not plate_result.needs_calibration and not plate_result.is_empty
  3929. if objects_detected:
  3930. # Objects detected - pause the print!
  3931. logger.warning(
  3932. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  3933. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  3934. )
  3935. pause_client = printer_manager.get_client(printer_id)
  3936. if pause_client:
  3937. pause_client.pause_print()
  3938. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  3939. # Snapshot while the light's still on — restoring it first
  3940. # would leave the notification with a dark photo.
  3941. try:
  3942. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3943. except Exception as snap_err:
  3944. logger.warning(
  3945. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  3946. )
  3947. finally:
  3948. # Restore chamber light to original state as soon as the
  3949. # camera is done with it, whatever happened above.
  3950. if light_was_off and client:
  3951. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  3952. try:
  3953. client.set_chamber_light(False)
  3954. except Exception as light_err:
  3955. logger.warning(
  3956. "[PLATE CHECK] Failed to restore chamber light for printer %s: %s",
  3957. printer_id,
  3958. light_err,
  3959. )
  3960. if objects_detected:
  3961. # Send notification about plate not empty
  3962. await ws_manager.broadcast(
  3963. {
  3964. "type": "plate_not_empty",
  3965. "printer_id": printer_id,
  3966. "printer_name": printer.name,
  3967. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  3968. }
  3969. )
  3970. # Also send push notification
  3971. try:
  3972. await notification_service.on_plate_not_empty(
  3973. printer_id=printer_id,
  3974. printer_name=printer.name,
  3975. db=db,
  3976. difference_percent=plate_result.difference_percent,
  3977. image_data=plate_photo_data,
  3978. )
  3979. except Exception as notif_err:
  3980. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  3981. else:
  3982. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  3983. except Exception as plate_err:
  3984. # Don't block print on plate detection errors
  3985. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  3986. if not printer:
  3987. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  3988. if not notification_sent:
  3989. await _send_print_start_notification(printer_id, data, logger=logger)
  3990. return
  3991. if not printer.auto_archive:
  3992. # auto-archive disabled — check if there's an expected print (dispatched
  3993. # by BamBuddy via queue/reprint) that already has an archive to promote.
  3994. # If so, fall through to the expected-print handling below so the archive
  3995. # is tracked in _active_prints and usage tracking works at completion.
  3996. _fn = data.get("filename", "")
  3997. _sn = data.get("subtask_name", "")
  3998. _check_keys: list[tuple[int, str]] = []
  3999. if _sn:
  4000. _check_keys += [
  4001. (printer_id, _sn),
  4002. (printer_id, f"{_sn}.3mf"),
  4003. (printer_id, f"{_sn}.gcode.3mf"),
  4004. ]
  4005. if _fn:
  4006. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4007. _check_keys.append((printer_id, _base_fn))
  4008. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4009. _check_keys += [
  4010. (printer_id, _no_archive_base),
  4011. (printer_id, f"{_no_archive_base}.3mf"),
  4012. ]
  4013. _has_expected = any(k in _expected_prints for k in _check_keys)
  4014. if not _has_expected:
  4015. # No expected print — truly external print (started from slicer/touchscreen)
  4016. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4017. if not notification_sent:
  4018. _no_archive_creator: int | None = None
  4019. for _key in _check_keys:
  4020. _expected_prints.pop(_key, None)
  4021. _expected_print_registered_at.pop(_key, None)
  4022. popped_creator = _expected_print_creators.pop(_key, None)
  4023. if _no_archive_creator is None:
  4024. _no_archive_creator = popped_creator
  4025. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4026. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4027. return
  4028. else:
  4029. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4030. # Get the filename and subtask_name
  4031. filename = data.get("filename", "")
  4032. subtask_name = data.get("subtask_name", "")
  4033. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4034. # present, it lets us match an archive across a backend restart (#972):
  4035. # same id → same print → resume the existing row instead of cancelling
  4036. # it and recreating from scratch (which loses started_at). Treat "0"
  4037. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4038. raw_mqtt = data.get("raw_data") or {}
  4039. subtask_id = raw_mqtt.get("subtask_id")
  4040. if subtask_id is not None:
  4041. subtask_id = str(subtask_id).strip()
  4042. if subtask_id in ("", "0"):
  4043. subtask_id = None
  4044. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4045. # Skip the printer's own jobs — a calibration run is not a user's print.
  4046. # See is_internal_printer_job for what counts and why both fields are
  4047. # tested; the pressure-advance line reports as a subtask name with no
  4048. # /usr/ path, which the old prefix-only test here missed entirely.
  4049. #
  4050. # No notification either. The event describes the printer calibrating
  4051. # itself, so "Print started" is as wrong as the archive was, and the
  4052. # matching completion is suppressed in on_print_complete for the same
  4053. # reason.
  4054. if is_internal_printer_job(filename, subtask_name):
  4055. logger.info(
  4056. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4057. filename,
  4058. subtask_name,
  4059. )
  4060. return
  4061. if not filename and not subtask_name:
  4062. # Send notification without archive data (no filename)
  4063. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4064. if not notification_sent:
  4065. await _send_print_start_notification(printer_id, data, logger=logger)
  4066. return
  4067. # Check if this is an expected print from reprint/scheduled
  4068. # Build list of possible keys to check
  4069. expected_keys = []
  4070. if subtask_name:
  4071. expected_keys.append((printer_id, subtask_name))
  4072. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  4073. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  4074. if filename:
  4075. fname = filename.split("/")[-1] if "/" in filename else filename
  4076. expected_keys.append((printer_id, fname))
  4077. # Strip extensions to match
  4078. base = fname.replace(".gcode", "").replace(".3mf", "")
  4079. expected_keys.append((printer_id, base))
  4080. expected_keys.append((printer_id, f"{base}.3mf"))
  4081. expected_archive_id = None
  4082. for key in expected_keys:
  4083. expected_archive_id = _expected_prints.pop(key, None)
  4084. _expected_print_registered_at.pop(key, None)
  4085. if expected_archive_id:
  4086. # Clean up other possible keys for this print
  4087. for other_key in expected_keys:
  4088. _expected_prints.pop(other_key, None)
  4089. _expected_print_registered_at.pop(other_key, None)
  4090. break
  4091. if expected_archive_id:
  4092. # This is a reprint/scheduled print - use existing archive, don't create new one
  4093. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4094. from backend.app.models.archive import PrintArchive
  4095. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4096. archive = result.scalar_one_or_none()
  4097. # Deleted after this handler loaded it (the plate check waits
  4098. # seconds) but before the route forgot the expected print: the
  4099. # archive the route kept or deleted is left as the route left it.
  4100. if archive and await _printer_gone(db, printer_id):
  4101. logger.info(
  4102. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4103. )
  4104. await forget_printer(printer_id)
  4105. return
  4106. if archive:
  4107. # As it was before this adoption: put back if the printer turns
  4108. # out to have been deleted while it was adopted (below).
  4109. before_adoption = {
  4110. attr.columns[0].name: getattr(archive, attr.key)
  4111. for attr in sa_inspect(PrintArchive).column_attrs
  4112. if attr.key != "id"
  4113. }
  4114. # Update archive status to printing
  4115. archive.status = "printing"
  4116. archive.started_at = datetime.now(timezone.utc)
  4117. # The previous run's answer is still on this row and the
  4118. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4119. # so without a reset the second run inherits the first run's
  4120. # verdict: no prompt at all, and a green "good" badge on a run
  4121. # nobody ever judged.
  4122. if archive.confirm_requested:
  4123. archive.user_verdict = None
  4124. archive.user_verdict_source = None
  4125. archive.user_verdict_at = None
  4126. archive.confirm_token = None
  4127. archive.confirm_token_used_at = None
  4128. # Reprint of an archive reuses the source row. Without resetting
  4129. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4130. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4131. # extracts the *original* print's last frame, which then ships in
  4132. # the completion notification (#1707). Clear the path so the
  4133. # scanner runs fresh; also unlink the old video file so reprints
  4134. # don't accumulate orphans in the archive directory. Photos list
  4135. # is left alone — accumulating one finish photo per run is fine.
  4136. # The print-start baseline (#2704) is stale for the same reason:
  4137. # it describes the printer before the previous run. The capture
  4138. # below overwrites it, but clear it here too so an early failure
  4139. # can't leave the scan diffing against the wrong snapshot.
  4140. #
  4141. # Unlinked only when it is the same plate printing again. Every
  4142. # plate of a Send All shares this archive, and the video on it
  4143. # can be the only copy of another plate's run -- the printer's
  4144. # was deleted once it attached (#3275). That one is left in the
  4145. # archive directory, which goes with the archive. A video whose
  4146. # plate is not on record (attached by hand, or before the
  4147. # column existed) is kept too: nothing tells it apart from
  4148. # another plate's, and keeping costs one file where deleting
  4149. # can cost the only copy.
  4150. archive.timelapse_baseline = None
  4151. stale_timelapse_relpath = archive.timelapse_path
  4152. stale_timelapse_plate_id = archive.timelapse_plate_id
  4153. starting_plate_id = _print_plate_ids.get(expected_archive_id)
  4154. if stale_timelapse_relpath:
  4155. archive.timelapse_path = None
  4156. archive.timelapse_plate_id = None
  4157. if stale_timelapse_relpath and stale_timelapse_plate_id != starting_plate_id:
  4158. logger.info(
  4159. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4160. stale_timelapse_relpath,
  4161. stale_timelapse_plate_id,
  4162. expected_archive_id,
  4163. starting_plate_id,
  4164. )
  4165. # The video is deleted once the adoption stands (below).
  4166. delete_stale_video = bool(stale_timelapse_relpath) and stale_timelapse_plate_id == starting_plate_id
  4167. # Persist a restart-stable id so a later restart resumes this
  4168. # archive by subtask_id instead of name-matching + duplicating
  4169. # it (#1485). The printer often hasn't echoed subtask_id back
  4170. # this soon after dispatch, so fall back to the id Bambuddy
  4171. # minted when it sent the print command. Scoped to this
  4172. # expected-print branch on purpose: an expected match means
  4173. # Bambuddy dispatched this exact print in this process, so the
  4174. # client's last-dispatch id genuinely belongs to it — using it
  4175. # for an externally-started print could mis-tag the archive.
  4176. effective_subtask_id = subtask_id
  4177. if not effective_subtask_id:
  4178. _client = printer_manager.get_client(printer_id)
  4179. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4180. if _dispatched:
  4181. effective_subtask_id = str(_dispatched).strip() or None
  4182. # Update on first-set OR on reprint (the queue dispatcher mints
  4183. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4184. # the rewrite for reprints leaves the archive holding the FIRST
  4185. # run's id; if MQTT then reconnects mid-print, the reconciler
  4186. # (#1542) compares the stale stored id against the printer's
  4187. # live id, sees a mismatch, and synthesises a bogus PRINT
  4188. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4189. # in #1807. Inequality check preserves the noop-on-stable-push
  4190. # behaviour the earlier `not archive.subtask_id` guard provided.
  4191. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4192. archive.subtask_id = effective_subtask_id
  4193. # #1403 follow-up: VP-queue archives are created with
  4194. # printer_id=None at queue-add time (we don't know which
  4195. # printer will run the job yet). When the print actually
  4196. # starts on a specific printer the expected-archive lookup
  4197. # used to skip this assignment, leaving printer_id=None
  4198. # forever — which then disables the "Scan for timelapse"
  4199. # button in ArchivesPage (gated on !archive.printer_id).
  4200. if archive.printer_id != printer_id:
  4201. archive.printer_id = printer_id
  4202. adopting_id = archive.id # a rollback expires the object
  4203. try:
  4204. await db.commit()
  4205. except (IntegrityError, StaleDataError):
  4206. # The archive stays unchanged, or is gone: "delete archives"
  4207. # removed the row under the adoption, which then matched no
  4208. # row (StaleDataError) rather than being refused.
  4209. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4210. return
  4211. raise
  4212. # The printer can be deleted between the check above and this
  4213. # commit (the route's transaction lasts seconds), and the commit
  4214. # then adopted the archive anyway: status, verdict and timelapse
  4215. # changed, and the deleted printer's id written on a row the
  4216. # route had detached or never touched. Undo the adoption.
  4217. if await _printer_gone(db, printer_id):
  4218. logger.info(
  4219. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4220. printer_id,
  4221. archive.id,
  4222. )
  4223. # Everything as before this adoption. The printer it had
  4224. # then stays, unless it was the deleted one: the route
  4225. # detached that row (kept) or deleted it (no row matches).
  4226. previous_printer = before_adoption["printer_id"]
  4227. await db.execute(
  4228. update(PrintArchive)
  4229. .where(PrintArchive.id == archive.id)
  4230. .values(
  4231. {
  4232. **before_adoption,
  4233. "printer_id": None if previous_printer == printer_id else previous_printer,
  4234. }
  4235. )
  4236. )
  4237. await db.commit()
  4238. await forget_printer(printer_id)
  4239. return
  4240. if delete_stale_video and stale_timelapse_relpath:
  4241. try:
  4242. stale_path = app_settings.base_dir / stale_timelapse_relpath
  4243. if stale_path.is_file():
  4244. stale_path.unlink()
  4245. logger.info(
  4246. "Deleted stale timelapse %s on reprint of archive %s",
  4247. stale_timelapse_relpath,
  4248. expected_archive_id,
  4249. )
  4250. except OSError as e:
  4251. logger.warning(
  4252. "Failed to delete stale timelapse %s on reprint: %s",
  4253. stale_timelapse_relpath,
  4254. e,
  4255. )
  4256. # Track as active print
  4257. _active_prints[(printer_id, archive.filename)] = archive.id
  4258. if subtask_name:
  4259. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  4260. # Start timelapse session if external camera is enabled (#1353).
  4261. # Queue / VP-dispatched prints land here in the expected-archive
  4262. # branch and used to skip start_session entirely — frames were
  4263. # never captured and the post-print stitch silently returned None.
  4264. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4265. # Inject ams_mapping into usage tracker session — the session was created
  4266. # before expected-print promotion, so it may have ams_mapping=None when
  4267. # the MQTT request topic subscription failed (common on P1S/A1).
  4268. _stored_map = _print_ams_mappings.get(expected_archive_id)
  4269. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  4270. if _stored_map or _stored_plate_id is not None:
  4271. try:
  4272. from backend.app.services.usage_tracker import _active_sessions
  4273. _ut_session = _active_sessions.get(printer_id)
  4274. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4275. _ut_session.ams_mapping = _stored_map
  4276. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4277. # plate_id injection covers direct-Print of plate N of a multi-plate
  4278. # 3MF — queue prints already capture it via the on_print_start queue
  4279. # lookup, but direct-Print never goes through the queue (#1697).
  4280. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4281. _ut_session.plate_id = _stored_plate_id
  4282. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4283. except Exception:
  4284. pass
  4285. # Set up energy tracking (#941: persist start on archive row)
  4286. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4287. await ws_manager.send_archive_updated(
  4288. {
  4289. "id": archive.id,
  4290. "status": "printing",
  4291. }
  4292. )
  4293. # Send notification with archive data (reprint/scheduled)
  4294. if not notification_sent:
  4295. # Use archive's created_by_id; fall back to the creator registered via
  4296. # register_expected_print (handles library-file-based queue items where
  4297. # the freshly-created archive has no created_by_id yet).
  4298. # Pop ALL matching keys so no stale entries remain in the dict.
  4299. fallback_creator = None
  4300. for key in expected_keys:
  4301. popped = _expected_print_creators.pop(key, None)
  4302. if fallback_creator is None:
  4303. fallback_creator = popped
  4304. archive_data = {
  4305. "print_time_seconds": archive.print_time_seconds,
  4306. "created_by_id": archive.created_by_id or fallback_creator,
  4307. }
  4308. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4309. # Extract printable objects from the archived 3MF file
  4310. _load_objects_from_archive(archive, printer_id, logger)
  4311. # Store Spoolman tracking data for per-filament usage reporting
  4312. try:
  4313. await _store_spoolman_print_data(
  4314. printer_id,
  4315. archive.id,
  4316. archive.file_path,
  4317. db,
  4318. printer_manager,
  4319. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4320. plate_id=_get_start_plate_id(archive.id),
  4321. )
  4322. except Exception as e:
  4323. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4324. # Price the print from its spools now rather than only at completion (#3261)
  4325. _schedule_archive_cost_estimate(
  4326. printer_id,
  4327. archive.id,
  4328. printer_manager,
  4329. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4330. plate_id=_get_start_plate_id(archive.id),
  4331. session_factory=async_session,
  4332. )
  4333. # Capture timelapse file baseline for snapshot-diff on completion
  4334. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4335. # hit this branch — without the baseline the completion-time scan
  4336. # falls into its "take baseline now" fallback, which snapshots
  4337. # AFTER the new MP4 already exists and never matches a diff
  4338. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4339. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4340. await _forget_if_printer_gone(printer_id)
  4341. return # Skip creating a new archive
  4342. # Check if there's already a "printing" archive for this printer/file
  4343. # This prevents duplicates when backend restarts during an active print
  4344. from backend.app.models.archive import PrintArchive
  4345. existing_archive: PrintArchive | None = None
  4346. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4347. # across a backend restart for the same print, so this is the most
  4348. # reliable way to reattach. We also accept a previously stale-cancelled
  4349. # archive here so users upgrading mid-print get revived when the row
  4350. # their earlier Bambuddy version wrongly cancelled reappears (#972).
  4351. if subtask_id:
  4352. by_id = await db.execute(
  4353. select(PrintArchive)
  4354. .where(PrintArchive.printer_id == printer_id)
  4355. .where(PrintArchive.subtask_id == subtask_id)
  4356. .where(PrintArchive.status.in_(["printing", "cancelled"]))
  4357. .order_by(PrintArchive.created_at.desc())
  4358. .limit(1)
  4359. )
  4360. candidate = by_id.scalar_one_or_none()
  4361. if candidate and (candidate.status == "printing" or (candidate.failure_reason or "").startswith("Stale")):
  4362. existing_archive = candidate
  4363. # Fallback match: name-based lookup. Kept as-is for prints whose
  4364. # subtask_id is missing ("0" / local / non-cloud prints).
  4365. if existing_archive is None:
  4366. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4367. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4368. # A print started from the printer's screen names its file in full,
  4369. # so the forms above double its extension. The file itself is the
  4370. # one exact match, and nothing looser is added (#3009).
  4371. if _subtask_is_the_file(subtask_name, filename):
  4372. archive_filenames.append(subtask_name)
  4373. existing = await db.execute(
  4374. select(PrintArchive)
  4375. .where(PrintArchive.printer_id == printer_id)
  4376. .where(PrintArchive.status == "printing")
  4377. .where(
  4378. or_(
  4379. PrintArchive.print_name == check_name,
  4380. PrintArchive.filename.in_(archive_filenames),
  4381. )
  4382. )
  4383. .order_by(PrintArchive.created_at.desc())
  4384. .limit(1)
  4385. )
  4386. existing_archive = existing.scalar_one_or_none()
  4387. if existing_archive:
  4388. # subtask_id match → always resume, regardless of age. Same print,
  4389. # just a backend restart. Revive if it was previously stale-cancelled.
  4390. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4391. if subtask_match:
  4392. if existing_archive.status == "cancelled":
  4393. logger.warning(
  4394. "Reviving stale-cancelled archive %s — matching subtask_id %s confirms same print (#972)",
  4395. existing_archive.id,
  4396. subtask_id,
  4397. )
  4398. existing_archive.status = "printing"
  4399. existing_archive.failure_reason = None
  4400. await db.commit()
  4401. else:
  4402. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4403. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4404. if existing_archive.energy_start_kwh is None:
  4405. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4406. if not notification_sent:
  4407. archive_data = {
  4408. "print_time_seconds": existing_archive.print_time_seconds,
  4409. "created_by_id": existing_archive.created_by_id,
  4410. }
  4411. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4412. _load_objects_from_archive(existing_archive, printer_id, logger)
  4413. return
  4414. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4415. # stale from the printer's *current* progress, not wall-clock age.
  4416. # A genuinely long print used to trip a blind 4h cutoff and have its
  4417. # live archive cancelled + duplicated on every backend restart
  4418. # (#1485). If the printer reports real progress, this name-matched
  4419. # 'printing' archive IS that ongoing print — resume it whatever its
  4420. # age. Only treat it as a stale leftover when the printer clearly
  4421. # shows a different, freshly-started print: near-0% progress on an
  4422. # archive far too old to still be at 0%. Unknown progress (printer
  4423. # not connected) never cancels — resuming is the safe default.
  4424. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4425. live_status = printer_manager.get_status(printer_id)
  4426. live_progress = getattr(live_status, "progress", None) if live_status else None
  4427. looks_stale = (
  4428. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4429. )
  4430. if looks_stale:
  4431. logger.warning(
  4432. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}, "
  4433. f"printer progress {live_progress:.0f}%) — marking cancelled and creating new archive"
  4434. )
  4435. existing_archive.status = "cancelled"
  4436. # Canonical key, not a sentence (issue #2974). "No status update
  4437. # received" is what both stale paths actually observed; which of
  4438. # the two it was is already carried by ``status`` -- cancelled
  4439. # here, the reconciled outcome at the reconnect site -- so one
  4440. # key loses no information and gives the Statistics breakdown a
  4441. # single bucket instead of two untranslatable prose strings.
  4442. existing_archive.failure_reason = "noStatusUpdate"
  4443. await db.commit()
  4444. # Fall through to create new archive (don't return)
  4445. else:
  4446. logger.info(
  4447. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4448. )
  4449. # Track this as the active print
  4450. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4451. # Attach subtask_id retroactively so future restarts can resume.
  4452. # Compare for inequality (not "is empty") to also pick up reprint
  4453. # dispatches that mint a fresh id — see #1807 for the bogus
  4454. # "Print Stopped" the strict-empty guard caused on reconnect.
  4455. if subtask_id and existing_archive.subtask_id != subtask_id:
  4456. existing_archive.subtask_id = subtask_id
  4457. await db.commit()
  4458. # Also set up energy tracking if not already tracked (#941: persisted column)
  4459. if existing_archive.energy_start_kwh is None:
  4460. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4461. # Send notification with archive data (existing archive)
  4462. if not notification_sent:
  4463. archive_data = {
  4464. "print_time_seconds": existing_archive.print_time_seconds,
  4465. "created_by_id": existing_archive.created_by_id,
  4466. }
  4467. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4468. # Extract printable objects from the archived 3MF file
  4469. _load_objects_from_archive(existing_archive, printer_id, logger)
  4470. return
  4471. # Build list of possible 3MF filenames to try
  4472. possible_names = []
  4473. # Bambu printers typically store files as "Name.gcode.3mf"
  4474. # The subtask_name is usually the best source for the filename
  4475. if subtask_name:
  4476. if _subtask_is_the_file(subtask_name, filename):
  4477. # A print started from the printer's own screen reports the
  4478. # file's full name, extension included. That is the file, so
  4479. # no extension is appended to it (#3009).
  4480. possible_names.append(subtask_name)
  4481. else:
  4482. # Try common Bambu naming patterns
  4483. possible_names.append(f"{subtask_name}.gcode.3mf")
  4484. possible_names.append(f"{subtask_name}.3mf")
  4485. # Try original filename with .3mf extension
  4486. if filename:
  4487. # Extract just the filename part, not the full path
  4488. fname = filename.split("/")[-1] if "/" in filename else filename
  4489. if fname.endswith(".3mf"):
  4490. possible_names.append(fname)
  4491. elif fname.endswith(".gcode"):
  4492. base = fname.rsplit(".", 1)[0]
  4493. possible_names.append(f"{base}.gcode.3mf")
  4494. possible_names.append(f"{base}.3mf")
  4495. else:
  4496. possible_names.append(f"{fname}.gcode.3mf")
  4497. possible_names.append(f"{fname}.3mf")
  4498. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4499. space_variants = []
  4500. for name in possible_names:
  4501. if " " in name:
  4502. space_variants.append(name.replace(" ", "_"))
  4503. possible_names.extend(space_variants)
  4504. # Remove duplicates while preserving order
  4505. seen = set()
  4506. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4507. logger.info("Trying filenames: %s", possible_names)
  4508. # Release the pooled DB connection before the 3MF FTP download. Reaching
  4509. # here means none of the expected-/existing-archive write branches ran
  4510. # (they all return earlier) — only SELECTs have executed on this path, so
  4511. # this commit persists nothing; it ends the read transaction so the
  4512. # connection returns to the pool during the download. That download tries
  4513. # up to five remote paths per candidate filename with retry/backoff and
  4514. # can run for minutes under FTP contention; holding the session across it
  4515. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  4516. # work runs during the download — the new-archive writes below re-acquire
  4517. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  4518. await db.commit()
  4519. # Try to find and download the 3MF file
  4520. temp_path = None
  4521. downloaded_filename = None
  4522. # Cache check: cover endpoint may have already pulled this 3MF during
  4523. # the print (frontend opens the card and shows the thumbnail) — reuse
  4524. # that file instead of re-downloading 36MB over the same FTP link that
  4525. # just served it (#972). The cache keys on a normalized filename so
  4526. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  4527. for try_filename in possible_names:
  4528. if not try_filename.endswith(".3mf"):
  4529. continue
  4530. cached = get_cached_3mf(printer_id, try_filename)
  4531. if cached:
  4532. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  4533. temp_path = cached
  4534. downloaded_filename = try_filename
  4535. break
  4536. # Does this printer keep the sliced file somewhere FTPS can reach? On
  4537. # H2-series and P2S the answer is routinely no — the file stays on
  4538. # internal eMMC and port 990 only ever serves external storage — and
  4539. # then the whole sweep below (six filenames x five directories x four
  4540. # retries, then the directory walk) is ~110 connections that cannot
  4541. # succeed. Skip it and say why (#2780).
  4542. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  4543. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  4544. # running rather than because the file is somewhere unreachable. The
  4545. # distinction is the whole of #2957: one is permanent, the other clears
  4546. # in minutes with the file still sitting on the printer.
  4547. blocked_by_ftps_cooloff = False
  4548. # Set when a probe reached the printer and still came back without the
  4549. # file -- a timeout mid-transfer, a refused connection, anything that is
  4550. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  4551. # caught by name below, so a file that genuinely is not on the card
  4552. # leaves this False and schedules nothing. Anything else means the
  4553. # transfer, not the file, is what failed, and that does not last (#3063).
  4554. ftp_transfer_failed = False
  4555. # The print's name, for a fallback archive whose `subtask_name` the
  4556. # plate guard below had to disown. Display only, and deliberately kept
  4557. # apart from `subtask_name`: that variable is what every file lookup
  4558. # here is built from, and once a name has been shown to fetch another
  4559. # plate's 3MF it must not key `_active_prints` either, or the cover
  4560. # endpoint hands the same contradicted file to
  4561. # `_recover_fallback_archive` and fills the row in with it (#3126).
  4562. display_name_after_plate_reject: str | None = None
  4563. # Get FTP retry settings
  4564. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  4565. # ...but "the printer put it on eMMC" is where it went, not whether we
  4566. # can read it. An H2D with a card in mirrors the job to /cache and
  4567. # serves it happily, and skipping on the URL alone cost that reporter
  4568. # every archive for two days (#2856). So ask the printer instead of
  4569. # guessing: the dispatch named the exact file, which is one connection
  4570. # walking five paths rather than the sweep's ~110. Only when the probe
  4571. # comes back empty does the verdict's reason stand.
  4572. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  4573. if ftps_handshake_blocked(printer.ip_address):
  4574. # Deliberately NOT recorded as a cool-off give-up. This branch
  4575. # only runs on an unreachable verdict, and that verdict is the
  4576. # honest, permanent reason the archive is empty — the probe was
  4577. # a long shot on top of it. Blaming the cool-off here would
  4578. # schedule a retry for a file sitting on internal eMMC, which is
  4579. # the sweep #2780 removed (#2957).
  4580. logger.debug(
  4581. "Not probing for %s on printer %s: its file service is not answering over TLS",
  4582. storage.probe_filename,
  4583. printer_id,
  4584. )
  4585. else:
  4586. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  4587. probe_path.parent.mkdir(parents=True, exist_ok=True)
  4588. try:
  4589. probe_hit = await download_file_try_paths_async(
  4590. printer.ip_address,
  4591. printer.access_code,
  4592. ftp_probe_paths(storage.probe_filename),
  4593. probe_path,
  4594. socket_timeout=ftp_timeout,
  4595. printer_model=printer.model,
  4596. )
  4597. except Exception as e:
  4598. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  4599. probe_hit = False
  4600. if probe_hit:
  4601. downloaded_filename = storage.probe_filename
  4602. temp_path = probe_path
  4603. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  4604. # Naming the path, not just the file: a printer that keeps
  4605. # uploads around for weeks can serve a same-named copy of an
  4606. # earlier slice, and without the directory in the log that
  4607. # mismatch is invisible rather than merely rare (#1820).
  4608. logger.info(
  4609. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  4610. downloaded_filename,
  4611. probe_hit,
  4612. printer_id,
  4613. storage.reason,
  4614. )
  4615. if not storage.reachable and not downloaded_filename:
  4616. # Same opening words whether or not a probe ran, because that is
  4617. # the phrase support asks people to grep for — only the tail says
  4618. # which of the two happened.
  4619. logger.info(
  4620. "Skipping the 3MF lookup for printer %s: %s — %s",
  4621. printer_id,
  4622. storage.reason,
  4623. "no copy of it on external storage either"
  4624. if storage.probe_filename
  4625. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  4626. )
  4627. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  4628. if not try_filename.endswith(".3mf"):
  4629. continue
  4630. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  4631. # printers, so try it first — deferring it to last cost #972's reporter
  4632. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  4633. # landing on the path that actually had the file.
  4634. remote_paths = [
  4635. f"/{try_filename}",
  4636. f"/cache/{try_filename}",
  4637. f"/model/{try_filename}",
  4638. f"/data/{try_filename}",
  4639. f"/data/Metadata/{try_filename}",
  4640. ]
  4641. temp_path = app_settings.archive_dir / "temp" / try_filename
  4642. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4643. for remote_path in remote_paths:
  4644. if ftps_handshake_blocked(printer.ip_address):
  4645. # The printer's FTPS service is not completing a TLS
  4646. # handshake, so it has no path we could reach — walking the
  4647. # remaining candidates only re-runs the same failure
  4648. # (#2780). Fall through to the no-3MF archive now.
  4649. #
  4650. # Remember *why*, though. This is the one give-up that is
  4651. # temporary: the cool-off clears in minutes and the file was
  4652. # on the printer the whole time. The fallback archive is
  4653. # stamped with it so a retry can be scheduled, and so the
  4654. # Archives banner stops blaming storage (#2957).
  4655. blocked_by_ftps_cooloff = True
  4656. logger.warning(
  4657. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  4658. printer_id,
  4659. )
  4660. break
  4661. logger.debug("Trying FTP download: %s", remote_path)
  4662. try:
  4663. if ftp_retry_enabled:
  4664. downloaded = await with_ftp_retry(
  4665. download_file_async,
  4666. printer.ip_address,
  4667. printer.access_code,
  4668. remote_path,
  4669. temp_path,
  4670. timeout=ftp_timeout,
  4671. socket_timeout=ftp_timeout,
  4672. printer_model=printer.model,
  4673. max_retries=ftp_retry_count,
  4674. retry_delay=ftp_retry_delay,
  4675. operation_name=f"Download 3MF from {remote_path}",
  4676. cooloff_ip=printer.ip_address,
  4677. non_retry_exceptions=(FileNotOnPrinterError,),
  4678. )
  4679. else:
  4680. downloaded = await download_file_async(
  4681. printer.ip_address,
  4682. printer.access_code,
  4683. remote_path,
  4684. temp_path,
  4685. timeout=ftp_timeout,
  4686. socket_timeout=ftp_timeout,
  4687. printer_model=printer.model,
  4688. )
  4689. if downloaded:
  4690. downloaded_filename = try_filename
  4691. logger.info("Downloaded: %s", remote_path)
  4692. # Populate shared cache so the cover endpoint (if it
  4693. # runs next) doesn't refetch the same 36MB over FTP.
  4694. cache_3mf_download(printer_id, try_filename, temp_path)
  4695. break
  4696. # with_ftp_retry returns None once it has spent its budget,
  4697. # and download_file_async returns False on a timeout, so an
  4698. # exhausted transfer arrives here rather than as an
  4699. # exception (#3063).
  4700. ftp_transfer_failed = True
  4701. except FileNotOnPrinterError:
  4702. # 550 — file isn't at this path. Advance to next candidate
  4703. # without burning the retry budget.
  4704. logger.debug("3MF not at %s (550), trying next path", remote_path)
  4705. except Exception as e:
  4706. ftp_transfer_failed = True
  4707. logger.debug("FTP download failed for %s: %s", remote_path, e)
  4708. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  4709. break
  4710. # If still not found, try listing directories to find matching file
  4711. # Different printer models use different directory structures. Skipped
  4712. # when the printer's FTPS handshake is failing — the directory walk is
  4713. # five more connections that cannot get further than the download did.
  4714. if (
  4715. not downloaded_filename
  4716. and storage.reachable
  4717. and (filename or subtask_name)
  4718. and not ftps_handshake_blocked(printer.ip_address)
  4719. ):
  4720. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  4721. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  4722. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  4723. for search_dir in search_dirs:
  4724. if downloaded_filename:
  4725. break
  4726. try:
  4727. dir_files = await list_files_async(
  4728. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  4729. )
  4730. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  4731. if threemf_files:
  4732. logger.info(
  4733. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  4734. )
  4735. for f in dir_files:
  4736. if f.get("is_directory"):
  4737. continue
  4738. fname = f.get("name", "")
  4739. # Normalize both for comparison (spaces and underscores are equivalent)
  4740. fname_normalized = fname.lower().replace(" ", "_")
  4741. search_normalized = search_term.replace(" ", "_")
  4742. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  4743. logger.info("Found matching file in %s: %s", search_dir, fname)
  4744. temp_path = app_settings.archive_dir / "temp" / fname
  4745. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4746. remote_full_path = posixpath.join(search_dir, fname)
  4747. if ftp_retry_enabled:
  4748. downloaded = await with_ftp_retry(
  4749. download_file_async,
  4750. printer.ip_address,
  4751. printer.access_code,
  4752. remote_full_path,
  4753. temp_path,
  4754. timeout=ftp_timeout,
  4755. socket_timeout=ftp_timeout,
  4756. printer_model=printer.model,
  4757. max_retries=ftp_retry_count,
  4758. retry_delay=ftp_retry_delay,
  4759. operation_name=f"Download 3MF from {remote_full_path}",
  4760. cooloff_ip=printer.ip_address,
  4761. )
  4762. else:
  4763. downloaded = await download_file_async(
  4764. printer.ip_address,
  4765. printer.access_code,
  4766. remote_full_path,
  4767. temp_path,
  4768. timeout=ftp_timeout,
  4769. socket_timeout=ftp_timeout,
  4770. printer_model=printer.model,
  4771. )
  4772. if downloaded:
  4773. downloaded_filename = fname
  4774. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  4775. cache_3mf_download(printer_id, fname, temp_path)
  4776. break
  4777. # The listing named the file, so it is on the card;
  4778. # only the transfer failed (#3063).
  4779. ftp_transfer_failed = True
  4780. except Exception as e:
  4781. logger.debug("Failed to list %s: %s", search_dir, e)
  4782. # Validate the downloaded 3MF actually matches the plate that's running
  4783. # (#1204): subtask_name lags across consecutive plates of the same model,
  4784. # so the first FTP candidate (built from subtask_name) can land on the
  4785. # previous plate's still-resident upload. Cross-check the slice_info
  4786. # plate index against the plate parsed from gcode_file (always fresh —
  4787. # it's the field whose change triggered this callback).
  4788. if downloaded_filename and temp_path:
  4789. expected_plate = parse_plate_id(filename)
  4790. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  4791. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  4792. logger.warning(
  4793. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  4794. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  4795. downloaded_filename,
  4796. actual_plate,
  4797. expected_plate,
  4798. subtask_name,
  4799. )
  4800. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  4801. retry_succeeded = False
  4802. if corrected_subtask and corrected_subtask != subtask_name:
  4803. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  4804. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  4805. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  4806. for remote_path in (
  4807. f"/{try_filename}",
  4808. f"/cache/{try_filename}",
  4809. f"/model/{try_filename}",
  4810. f"/data/{try_filename}",
  4811. f"/data/Metadata/{try_filename}",
  4812. ):
  4813. try:
  4814. if ftp_retry_enabled:
  4815. downloaded = await with_ftp_retry(
  4816. download_file_async,
  4817. printer.ip_address,
  4818. printer.access_code,
  4819. remote_path,
  4820. retry_temp_path,
  4821. timeout=ftp_timeout,
  4822. socket_timeout=ftp_timeout,
  4823. printer_model=printer.model,
  4824. max_retries=ftp_retry_count,
  4825. retry_delay=ftp_retry_delay,
  4826. operation_name=f"Re-download 3MF from {remote_path}",
  4827. cooloff_ip=printer.ip_address,
  4828. non_retry_exceptions=(FileNotOnPrinterError,),
  4829. )
  4830. else:
  4831. downloaded = await download_file_async(
  4832. printer.ip_address,
  4833. printer.access_code,
  4834. remote_path,
  4835. retry_temp_path,
  4836. timeout=ftp_timeout,
  4837. socket_timeout=ftp_timeout,
  4838. printer_model=printer.model,
  4839. )
  4840. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  4841. logger.info(
  4842. "[CALLBACK] Re-download succeeded with corrected name %s "
  4843. "(plate %s) — replacing wrong file",
  4844. try_filename,
  4845. expected_plate,
  4846. )
  4847. try:
  4848. temp_path.unlink(missing_ok=True)
  4849. except OSError:
  4850. pass
  4851. temp_path = retry_temp_path
  4852. downloaded_filename = try_filename
  4853. subtask_name = corrected_subtask
  4854. cache_3mf_download(printer_id, try_filename, temp_path)
  4855. retry_succeeded = True
  4856. break
  4857. elif downloaded:
  4858. # Wrong plate again — discard and keep trying
  4859. try:
  4860. retry_temp_path.unlink(missing_ok=True)
  4861. except OSError:
  4862. pass
  4863. except FileNotOnPrinterError:
  4864. continue
  4865. except Exception as e:
  4866. logger.debug("Re-download failed for %s: %s", remote_path, e)
  4867. if retry_succeeded:
  4868. break
  4869. # If the retry didn't find a matching file, drop the wrong 3MF
  4870. # so the no-3MF fallback below creates an archive whose name
  4871. # at least reflects the right plate.
  4872. if not retry_succeeded:
  4873. logger.warning(
  4874. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  4875. expected_plate,
  4876. )
  4877. try:
  4878. temp_path.unlink(missing_ok=True)
  4879. except OSError:
  4880. pass
  4881. temp_path = None
  4882. downloaded_filename = None
  4883. # Whatever the sweep's transport did earlier, it is not why
  4884. # this archive ends up empty: a 3MF downloaded fine, it was
  4885. # just the wrong plate. Retrying would re-fetch that same
  4886. # contradicted file under the same stale names and hand it
  4887. # to _recover_fallback_archive, which checks that a
  4888. # candidate is a readable 3MF but not which plate it is --
  4889. # so the row would be filled in with another plate's
  4890. # filament and cost, the exact swap #2957 removed (#3063).
  4891. ftp_transfer_failed = False
  4892. # Disown the name for *lookups*: it has just been shown to
  4893. # fetch another plate's 3MF, and it keys `_active_prints`
  4894. # below, where the cover endpoint's own download of that
  4895. # same name would find this archive and fill it in with the
  4896. # file we are discarding here.
  4897. #
  4898. # Keep it for the *title*, which is a separate question.
  4899. # ``swap_plate_suffix`` returns None both for a name that
  4900. # carries no "- Plate N" / "_plate_N" suffix and for no
  4901. # name at all, and those are not the same situation: a name
  4902. # without a suffix holds no stale plate number to be wrong
  4903. # about. Blanking both uses at once dropped the project
  4904. # name too, and the row fell through to the gcode_file path
  4905. # titled "plate_1" though the real name was in hand.
  4906. # #1204's own premise is consecutive plates *of the same
  4907. # model*, so the project part is right either way (#3126).
  4908. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  4909. subtask_name = corrected_subtask or ""
  4910. # Deleted while the 3MF was being fetched (that can take minutes): no
  4911. # archive, timelapse or tracking for a printer that will never report
  4912. # the print's end. forget_printer again: the download registered its
  4913. # 3MF cache entry after the delete cleared the id. (A delete committing
  4914. # while the archive is written is caught after its commit.)
  4915. if await _printer_gone(db, printer_id):
  4916. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  4917. await forget_printer(printer_id)
  4918. return
  4919. if not downloaded_filename or not temp_path:
  4920. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  4921. # Create a fallback archive without 3MF data so the print is still tracked
  4922. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  4923. try:
  4924. from backend.app.models.archive import PrintArchive
  4925. # Why the card is empty. The two temporary causes outrank the
  4926. # storage verdict because they say the sweep never got a fair
  4927. # answer: a cool-off skipped it at the transport, and a failed
  4928. # transfer reached the printer but never finished. Either way
  4929. # the file is still on the card, so reporting where the printer
  4930. # files its jobs would describe a setting that is not the
  4931. # problem (#2957, #3063).
  4932. if blocked_by_ftps_cooloff:
  4933. no_3mf_reason = REASON_FTPS_COOLOFF
  4934. elif storage.reachable and ftp_transfer_failed:
  4935. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  4936. else:
  4937. no_3mf_reason = storage.reason
  4938. # Derive print name from subtask_name or filename. The
  4939. # plate guard's disowned name comes second: it is a real name
  4940. # for a real print, and only the gcode_file path is left
  4941. # otherwise -- which titles the row "plate_1" (#3126).
  4942. print_name = subtask_name or display_name_after_plate_reject or filename
  4943. if print_name:
  4944. # Clean up the name (remove extensions, path parts)
  4945. print_name = print_name.split("/")[-1]
  4946. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  4947. else:
  4948. print_name = "Unknown Print"
  4949. # Recover estimated print time from MQTT (best-effort for notifications)
  4950. fallback_print_time = None
  4951. mqtt_remaining = data.get("remaining_time")
  4952. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  4953. fallback_print_time = int(mqtt_remaining)
  4954. if fallback_print_time is None:
  4955. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  4956. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  4957. fallback_print_time = int(mc_remaining * 60)
  4958. # Best-effort filament metadata from MQTT — see
  4959. # _extract_filament_data_from_mqtt. Without this the fallback
  4960. # archive's filament fields stayed NULL even though the AMS
  4961. # state at print start was sitting right there in `data`.
  4962. # The slicer's ams_mapping (when present) narrows the result
  4963. # to slots actually used by the print (#1533).
  4964. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  4965. # Create minimal archive entry
  4966. fallback_archive = PrintArchive(
  4967. printer_id=printer_id,
  4968. filename=filename or f"{print_name}.3mf",
  4969. file_path="", # Empty - no 3MF file available
  4970. file_size=0,
  4971. print_name=print_name,
  4972. print_time_seconds=fallback_print_time,
  4973. status="printing",
  4974. started_at=datetime.now(timezone.utc),
  4975. subtask_id=subtask_id,
  4976. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  4977. filament_type=mqtt_filament_meta.get("filament_type"),
  4978. filament_color=mqtt_filament_meta.get("filament_color"),
  4979. extra_data={
  4980. "no_3mf_available": True,
  4981. # Why the card is empty, when we know -- see above. The
  4982. # banner reads this to stop telling H2/P2 owners to
  4983. # switch on a setting that is already on and would not
  4984. # have helped (#2780).
  4985. "no_3mf_reason": no_3mf_reason,
  4986. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  4987. "_print_data": data,
  4988. },
  4989. )
  4990. db.add(fallback_archive)
  4991. try:
  4992. await db.commit()
  4993. except IntegrityError:
  4994. # Not "Failed to create fallback archive" below, and no
  4995. # start notification for a printer that is gone.
  4996. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  4997. return
  4998. raise
  4999. await db.refresh(fallback_archive)
  5000. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5001. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5002. return
  5003. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5004. # Track as active print
  5005. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  5006. if filename:
  5007. _active_prints[(printer_id, filename)] = fallback_archive.id
  5008. if subtask_name:
  5009. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  5010. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  5011. # Record starting energy if smart plug available (#941: persisted column)
  5012. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5013. # Send WebSocket notification
  5014. await ws_manager.send_archive_created(
  5015. {
  5016. "id": fallback_archive.id,
  5017. "printer_id": fallback_archive.printer_id,
  5018. "filename": fallback_archive.filename,
  5019. "print_name": fallback_archive.print_name,
  5020. "status": fallback_archive.status,
  5021. }
  5022. )
  5023. # MQTT relay - publish archive created
  5024. try:
  5025. await mqtt_relay.on_archive_created(
  5026. archive_id=fallback_archive.id,
  5027. print_name=fallback_archive.print_name,
  5028. printer_name=printer.name,
  5029. status=fallback_archive.status,
  5030. )
  5031. except Exception:
  5032. pass # Don't fail if MQTT fails
  5033. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5034. try:
  5035. await _store_spoolman_print_data(
  5036. printer_id,
  5037. fallback_archive.id,
  5038. fallback_archive.file_path,
  5039. db,
  5040. printer_manager,
  5041. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  5042. plate_id=_get_start_plate_id(fallback_archive.id),
  5043. )
  5044. except Exception as e:
  5045. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5046. # Both temporary give-ups are worth coming back for, and for
  5047. # the same reason: the file is on the printer and the last look
  5048. # failed at the transport rather than finding nothing. One waits
  5049. # out the handshake block (#2957), the other waits for the
  5050. # printer to stop being busy (#3063). Deliberately not scheduled
  5051. # for a storage verdict: a file on internal eMMC will not appear
  5052. # at any FTPS path however long we wait, and retrying it is
  5053. # exactly the sweep #2780 removed.
  5054. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5055. # `possible_names`, not the raw MQTT strings: it is the exact
  5056. # list this flow just tried, already stripped of any path
  5057. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5058. # some firmware) and deduped.
  5059. _schedule_fallback_3mf_retry(
  5060. printer_id=printer_id,
  5061. archive_id=fallback_archive.id,
  5062. filenames=list(possible_names),
  5063. reason=no_3mf_reason,
  5064. )
  5065. # Send notification without archive data (file not found)
  5066. if not notification_sent:
  5067. await _send_print_start_notification(printer_id, data, logger=logger)
  5068. # The same baseline the other two on_print_start branches take
  5069. # (#2704), and last for the same reason they are: it lists the
  5070. # printer's timelapse directory, so a slow card must not delay
  5071. # the _active_prints registration, the energy reading, the
  5072. # archive-created event or the start notification above it.
  5073. #
  5074. # This branch never took one, so every no-3MF archive reached
  5075. # completion with no baseline in memory and none on the row, and
  5076. # the completion scan fell into its "snapshot now" fallback --
  5077. # which runs after the printer has written the video, so the new
  5078. # file landed inside the baseline and no diff ever matched
  5079. # (#2957 follow-up).
  5080. #
  5081. # Skipped when the FTPS cool-off is what produced this fallback:
  5082. # the listing needs the same connection that just failed, so it
  5083. # could only record that the card was unreadable. The scan
  5084. # handles that case by refusing to choose between candidates.
  5085. if not blocked_by_ftps_cooloff:
  5086. await _capture_timelapse_baseline_at_start(
  5087. printer, printer_id, logger, archive_id=fallback_archive.id
  5088. )
  5089. await _forget_if_printer_gone(printer_id)
  5090. return
  5091. except Exception as e:
  5092. logger.error("Failed to create fallback archive: %s", e)
  5093. # Send notification without archive data (file not found)
  5094. if not notification_sent:
  5095. await _send_print_start_notification(printer_id, data, logger=logger)
  5096. return
  5097. try:
  5098. # Archive the file with status "printing"
  5099. service = ArchiveService(db)
  5100. try:
  5101. archive = await service.archive_print(
  5102. printer_id=printer_id,
  5103. source_file=temp_path,
  5104. print_data={**data, "status": "printing"},
  5105. subtask_id=subtask_id,
  5106. )
  5107. except IntegrityError:
  5108. # archive_print removed the folder it had copied the 3MF into.
  5109. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5110. return
  5111. raise
  5112. if archive:
  5113. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5114. # Set on the row rather than passed to archive_print, which also
  5115. # serves the queue dispatcher — there the queue item decides.
  5116. # Guarded because this branch has no ``except``: an unhandled
  5117. # write error would take the _active_prints registration, the
  5118. # start notification, the energy reading and the timelapse
  5119. # baseline below it with it, and a missing prompt is by far the
  5120. # cheaper failure.
  5121. archive_id = archive.id
  5122. try:
  5123. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5124. archive.confirm_requested = True
  5125. await db.commit()
  5126. except Exception as e:
  5127. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5128. # The rollback expires every loaded object, and on an async
  5129. # session reading one afterwards raises instead of
  5130. # reloading, so the two this branch goes on to use are
  5131. # fetched again. The archive itself was committed by
  5132. # archive_print; only the flag is lost.
  5133. try:
  5134. await db.rollback()
  5135. archive = await db.get(PrintArchive, archive_id)
  5136. printer = await db.get(Printer, printer_id)
  5137. except Exception as reload_error:
  5138. logger.warning(
  5139. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5140. )
  5141. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5142. return
  5143. # Track this active print (use both original filename and downloaded filename)
  5144. _active_prints[(printer_id, downloaded_filename)] = archive.id
  5145. if filename and filename != downloaded_filename:
  5146. _active_prints[(printer_id, filename)] = archive.id
  5147. if subtask_name:
  5148. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  5149. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5150. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5151. # Record starting energy from smart plug if available (#941: persisted column)
  5152. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5153. await ws_manager.send_archive_created(
  5154. {
  5155. "id": archive.id,
  5156. "printer_id": archive.printer_id,
  5157. "filename": archive.filename,
  5158. "print_name": archive.print_name,
  5159. "status": archive.status,
  5160. }
  5161. )
  5162. # MQTT relay - publish archive created
  5163. try:
  5164. await mqtt_relay.on_archive_created(
  5165. archive_id=archive.id,
  5166. print_name=archive.print_name,
  5167. printer_name=printer.name,
  5168. status=archive.status,
  5169. )
  5170. except Exception:
  5171. pass # Don't fail if MQTT fails
  5172. # Send notification with archive data (new archive created)
  5173. if not notification_sent:
  5174. archive_data = {
  5175. "print_time_seconds": archive.print_time_seconds,
  5176. "created_by_id": archive.created_by_id,
  5177. }
  5178. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5179. # Extract printable objects for skip object functionality
  5180. try:
  5181. from backend.app.services.archive import extract_printable_objects_from_3mf
  5182. client = printer_manager.get_client(printer_id)
  5183. if client:
  5184. with open(temp_path, "rb") as f:
  5185. threemf_data = f.read()
  5186. # Extract with positions for UI overlay, scoped to the
  5187. # plate that is printing — an all-plates 3MF carries
  5188. # every plate's objects (#2522).
  5189. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5190. threemf_data,
  5191. plate_number=resolve_plate_id(client.state),
  5192. include_positions=True,
  5193. )
  5194. if printable_objects:
  5195. # Store objects in printer state
  5196. client.state.printable_objects = printable_objects
  5197. client.state.printable_objects_bbox_all = bbox_all
  5198. client.state.skipped_objects = [] # Reset skipped objects for new print
  5199. logger.info(
  5200. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5201. )
  5202. except Exception as e:
  5203. logger.debug("Failed to extract printable objects: %s", e)
  5204. # Store Spoolman tracking data for per-filament usage reporting
  5205. try:
  5206. await _store_spoolman_print_data(
  5207. printer_id,
  5208. archive.id,
  5209. archive.file_path,
  5210. db,
  5211. printer_manager,
  5212. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5213. plate_id=_get_start_plate_id(archive.id),
  5214. )
  5215. except Exception as e:
  5216. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5217. # Price the print from its spools now rather than only at completion (#3261)
  5218. _schedule_archive_cost_estimate(
  5219. printer_id,
  5220. archive.id,
  5221. printer_manager,
  5222. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5223. plate_id=_get_start_plate_id(archive.id),
  5224. session_factory=async_session,
  5225. )
  5226. # Capture timelapse file baseline for snapshot-diff on completion
  5227. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5228. await _forget_if_printer_gone(printer_id)
  5229. finally:
  5230. # Keep temp_path around until print completes so the cover endpoint
  5231. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5232. # the file. If the cache entry was evicted early (file vanished),
  5233. # clean up any stragglers here to avoid leaking disk on retries.
  5234. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5235. if temp_path and temp_path.exists() and cached_now != temp_path:
  5236. temp_path.unlink()
  5237. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5238. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5239. # tests can shrink them without waiting out real delays.
  5240. #
  5241. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  5242. # looking. Across 247 support bundles the attempt that found the video was #1
  5243. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  5244. # decaying one, which is the signature of a budget that expires while files are
  5245. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  5246. # prints make big videos and the printer writes them after the print ends, so
  5247. # the poll now runs for minutes and costs one FTP LIST per round.
  5248. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  5249. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  5250. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  5251. def _timelapse_scan_max_attempts() -> int:
  5252. """Round cap for the poll, derived from the wall-clock budget.
  5253. The deadline alone is not a sufficient bound: it assumes each round really
  5254. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5255. and an FTP list that fails immediately would otherwise spin against the
  5256. printer at full speed for the whole window. Whichever bound is reached
  5257. first ends the poll.
  5258. """
  5259. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5260. # A zero interval makes the wall-clock budget meaningless; fall back to
  5261. # the round count the production interval would have given.
  5262. return 32
  5263. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5264. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  5265. """Video filenames already attached to some other archive of this printer.
  5266. Used to disambiguate when more than one file is new since the baseline —
  5267. which happens when a previous print's video landed after this print's
  5268. baseline was taken. Ordering the candidates would be the obvious fix and is
  5269. the wrong one: it can only be done on mtime or on the filename timestamp,
  5270. both of which come from the printer's own clock, and a LAN-only printer
  5271. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  5272. ``attach_timelapse`` saves the video into the archive directory under the
  5273. printer's original filename, and the later MP4 conversion keeps the stem,
  5274. so the stem of ``timelapse_path`` recovers what was claimed.
  5275. """
  5276. from backend.app.models.archive import PrintArchive
  5277. rows = await db.execute(
  5278. select(PrintArchive.timelapse_path).where(
  5279. PrintArchive.printer_id == printer_id,
  5280. PrintArchive.id != exclude_archive_id,
  5281. PrintArchive.timelapse_path.is_not(None),
  5282. )
  5283. )
  5284. return {Path(p).stem for p in rows.scalars().all() if p}
  5285. def _timelapse_listing_is_trustworthy(printer) -> bool:
  5286. """Whether an *empty* timelapse listing for *printer* can be believed.
  5287. ``list_files_async`` answers ``[]`` when its connect fails rather than
  5288. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  5289. from one holding no videos. Everywhere that only wants to know "is there a
  5290. video yet" the difference does not matter — both mean "not yet, retry".
  5291. It matters where an empty listing is recorded as a *baseline*. Recording
  5292. "the card held nothing" for a card that was never read means every video on
  5293. it counts as new once the cool-off expires, and the completion scan then
  5294. attaches a stale video to this print and deletes it from the printer
  5295. (#2957 follow-up). Those two callers ask this first.
  5296. """
  5297. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  5298. ip_address = getattr(printer, "ip_address", None)
  5299. if not ip_address:
  5300. return True
  5301. return not ftps_handshake_blocked(ip_address)
  5302. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5303. """List video files from printer's timelapse directory.
  5304. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5305. Returns (video_files, found_path) where video_files is a list of file dicts
  5306. and found_path is the directory where they were found, or ([], None).
  5307. An empty return does not distinguish "no videos" from "could not read the
  5308. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  5309. baseline callers consult before believing one.
  5310. """
  5311. from backend.app.services.bambu_ftp import list_files_async
  5312. logger = logging.getLogger(__name__)
  5313. # No card in the slot means no /timelapse to walk — four connections that
  5314. # can only fail, on a path whose failures are swallowed and so would go on
  5315. # costing time silently forever (#2780).
  5316. #
  5317. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5318. # inside the loop's own try/except, so a caller that passed something
  5319. # unexpected used to get an empty listing rather than an exception. Keep
  5320. # that, instead of making this gate the first thing that can raise here.
  5321. printer_id = getattr(printer, "id", None)
  5322. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5323. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5324. return [], None
  5325. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  5326. try:
  5327. found_files = await list_files_async(
  5328. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5329. )
  5330. if found_files:
  5331. video_files = [
  5332. f
  5333. for f in found_files
  5334. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5335. ]
  5336. if video_files:
  5337. return video_files, timelapse_path
  5338. except Exception as e:
  5339. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5340. continue
  5341. return [], None
  5342. async def _capture_timelapse_baseline_at_start(
  5343. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5344. ) -> None:
  5345. """Snapshot the printer's timelapse directory at print start so the
  5346. completion-time scan can pick the new file by set-difference.
  5347. Must be called from every on_print_start path that proceeds to a real
  5348. print — both the new-archive branch and the expected-archive branch (which
  5349. queue / VP-dispatched prints take). Without a baseline,
  5350. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5351. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5352. so the new file ends up in the "baseline" set and no diff ever matches.
  5353. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  5354. unreliable — the snapshot-diff approach sidesteps that entirely.
  5355. When ``archive_id`` is known the baseline is also written to the archive
  5356. row, so it survives a restart and the manual "Scan for Timelapse" button
  5357. can run the same diff instead of falling back to clock-based matching
  5358. (#2704). Only baselines taken at print start are persisted — one taken at
  5359. completion already contains the new video and would poison a later scan.
  5360. """
  5361. names: set[str] | None = None
  5362. try:
  5363. if not _timelapse_listing_is_trustworthy(printer):
  5364. # Recorded anyway, deliberately. An empty baseline taken off a card
  5365. # we could not read is not authoritative, but it is still the right
  5366. # *default*: Bambuddy deletes each video from the printer once it is
  5367. # attached, so the usual card holds exactly one video at completion
  5368. # and an empty baseline resolves it correctly. Persisting NULL
  5369. # instead would send completion to take its own snapshot, by which
  5370. # point this print's video is on the card and would be swallowed by
  5371. # it. The ambiguity is handled where it actually bites — see
  5372. # ``require_unambiguous`` in the scan (#2957 follow-up).
  5373. logger.warning(
  5374. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  5375. "handshake cool-off, so the card could not be read — treating it as empty",
  5376. printer_id,
  5377. )
  5378. baseline_files, _ = await _list_timelapse_videos(printer)
  5379. names = {f.get("name", "") for f in baseline_files}
  5380. _timelapse_baselines[printer_id] = names
  5381. logger.info(
  5382. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  5383. len(names),
  5384. printer_id,
  5385. )
  5386. except Exception as e:
  5387. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  5388. if archive_id is None:
  5389. return
  5390. try:
  5391. async with async_session() as db:
  5392. from backend.app.models.archive import PrintArchive
  5393. archive = await db.get(PrintArchive, archive_id)
  5394. if archive is not None:
  5395. # Written even when the listing failed, and then as NULL. A
  5396. # reprint reuses the archive row, so leaving the previous run's
  5397. # baseline in place would have the scan diff this print against
  5398. # the state of the printer before the *last* one — and a stale
  5399. # baseline reads as authoritative, where NULL correctly falls
  5400. # back to a fresh snapshot.
  5401. archive.timelapse_baseline = sorted(names) if names is not None else None
  5402. await db.commit()
  5403. except Exception as e:
  5404. # In-memory baseline still covers the normal completion path.
  5405. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  5406. async def _scan_for_timelapse_with_retries(
  5407. archive_id: int, baseline_names: set[str] | None = None, *, plate_id: int | None = None
  5408. ):
  5409. """Poll the printer for this print's timelapse and attach it.
  5410. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  5411. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  5412. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  5413. (#2704). Comparing the current listing against the set of filenames that
  5414. existed when the print started needs no clock at all, because the printer
  5415. writes the video only once the print has ended.
  5416. Baseline precedence: the caller's in-memory set, then the one persisted on
  5417. the archive at print start, then a snapshot taken now. The last of those is
  5418. a poor substitute — by completion the new video may already be on the card,
  5419. in which case it lands in the "baseline" and no diff can ever match — but it
  5420. is all that is available for a print that began before Bambuddy started.
  5421. On success the video is deleted from the printer, which keeps ``/timelapse``
  5422. down to the unclaimed files and makes the next diff unambiguous.
  5423. """
  5424. logger = logging.getLogger(__name__)
  5425. # Cleared when the baseline had to be taken off a card we could not read, so
  5426. # the attach step refuses to choose between several candidates (#2957).
  5427. baseline_trusted = True
  5428. # --- Phase 1: establish the baseline -------------------------------------
  5429. try:
  5430. async with async_session() as db:
  5431. from backend.app.models.printer import Printer
  5432. service = ArchiveService(db)
  5433. archive = await service.get_archive(archive_id)
  5434. if not archive:
  5435. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  5436. return
  5437. if archive.timelapse_path:
  5438. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  5439. return
  5440. if not archive.printer_id:
  5441. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  5442. return
  5443. if baseline_names is not None:
  5444. logger.info(
  5445. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  5446. len(baseline_names),
  5447. archive_id,
  5448. )
  5449. elif archive.timelapse_baseline is not None:
  5450. # Persisted at print start — survives a restart mid-print.
  5451. baseline_names = set(archive.timelapse_baseline)
  5452. logger.info(
  5453. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  5454. len(baseline_names),
  5455. archive_id,
  5456. )
  5457. else:
  5458. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5459. printer = result.scalar_one_or_none()
  5460. if not printer:
  5461. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  5462. return
  5463. if not _timelapse_listing_is_trustworthy(printer):
  5464. # The card is unreadable at the one moment a baseline has to
  5465. # be taken, so the empty listing below means "we never
  5466. # looked", not "these are all new". Carry on with it anyway
  5467. # — the usual card holds exactly one video, which resolves
  5468. # correctly — but stop the poll from *choosing* between
  5469. # several, which is how a stale video got attached to this
  5470. # print and then deleted off the printer (#2957 follow-up).
  5471. baseline_trusted = False
  5472. logger.warning(
  5473. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  5474. "handshake cool-off. A single new video still resolves; several will not be "
  5475. "guessed between — use Scan for Timelapse to pick one by hand",
  5476. archive_id,
  5477. archive.printer_id,
  5478. )
  5479. baseline_files, _ = await _list_timelapse_videos(printer)
  5480. baseline_names = {f.get("name", "") for f in baseline_files}
  5481. logger.info(
  5482. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  5483. len(baseline_names),
  5484. archive_id,
  5485. )
  5486. except Exception as e:
  5487. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  5488. return
  5489. # --- Phase 2: poll for a file that was not there when the print began -----
  5490. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  5491. max_attempts = _timelapse_scan_max_attempts()
  5492. seen_names: set[str] = set()
  5493. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  5494. attempt = 0
  5495. while True:
  5496. await asyncio.sleep(delay)
  5497. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  5498. attempt += 1
  5499. try:
  5500. from backend.app.models.printer import Printer
  5501. # Read phase: fetch archive + printer in a short session and release
  5502. # the pooled connection BEFORE the FTP list/download below. Holding it
  5503. # across the FTP round-trips left one connection idle-in-transaction per
  5504. # in-flight scan (issue #2572).
  5505. async with async_session() as db:
  5506. service = ArchiveService(db)
  5507. archive = await service.get_archive(archive_id)
  5508. if not archive:
  5509. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  5510. return
  5511. if archive.timelapse_path:
  5512. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  5513. return
  5514. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5515. printer = result.scalar_one_or_none()
  5516. if not printer:
  5517. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  5518. return
  5519. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  5520. # I/O phase (no DB connection held): FTP list + download.
  5521. video_files, found_path = await _list_timelapse_videos(printer)
  5522. # The poll can run for dozens of rounds, so only narrate a round
  5523. # that saw something change. Repeating the whole listing every 30 s
  5524. # would bury the one interesting line in the support bundle.
  5525. names_now = {f.get("name", "") for f in video_files}
  5526. changed = attempt == 1 or names_now != seen_names
  5527. seen_names = names_now
  5528. speak = logger.info if changed else logger.debug
  5529. if video_files:
  5530. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  5531. if changed:
  5532. for f in video_files[:5]:
  5533. logger.info("[TIMELAPSE] - %s", f.get("name"))
  5534. attached = await _attach_first_unclaimed_timelapse(
  5535. archive_id,
  5536. printer,
  5537. video_files,
  5538. baseline_names,
  5539. claimed,
  5540. attempt,
  5541. logger,
  5542. quiet=not changed,
  5543. require_unambiguous=not baseline_trusted,
  5544. plate_id=plate_id,
  5545. )
  5546. if attached:
  5547. return
  5548. else:
  5549. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  5550. except Exception as e:
  5551. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  5552. if attempt >= max_attempts or time.monotonic() >= deadline:
  5553. break
  5554. # No name-match fallback: it compared the print name against the filename,
  5555. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  5556. # bundles it fired 159 times and matched zero times, so all it added was a
  5557. # misleading log line before giving up.
  5558. logger.warning(
  5559. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  5560. archive_id,
  5561. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  5562. )
  5563. async def _attach_first_unclaimed_timelapse(
  5564. archive_id: int,
  5565. printer,
  5566. video_files: list[dict],
  5567. baseline_names: set[str],
  5568. claimed: set[str],
  5569. attempt: int,
  5570. logger: logging.Logger,
  5571. *,
  5572. quiet: bool = False,
  5573. require_unambiguous: bool = False,
  5574. plate_id: int | None = None,
  5575. ) -> bool:
  5576. """Download and attach the one video that belongs to this print.
  5577. A candidate is any file absent from the print-start baseline. More than one
  5578. can qualify when a previous print's video landed late, after this print's
  5579. baseline was taken — those are filtered out by name, because they are
  5580. already attached to another archive. Sorting the candidates instead would
  5581. mean sorting on mtime or on the filename timestamp, both of which come from
  5582. the printer's unsynced clock.
  5583. Returns True once a video is attached. The printer's copy is deleted only
  5584. after the attach succeeds on bytes whose length matched the listing.
  5585. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  5586. already seen this exact listing — the poll runs for many rounds and only the
  5587. rounds where something changed are worth an INFO line.
  5588. """
  5589. from backend.app.services.bambu_ftp import (
  5590. delete_archived_timelapse,
  5591. download_file_bytes_async,
  5592. remote_file_settled,
  5593. )
  5594. speak = logger.debug if quiet else logger.info
  5595. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  5596. if not new_files:
  5597. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  5598. return False
  5599. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  5600. if not candidates:
  5601. speak(
  5602. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  5603. attempt,
  5604. len(new_files),
  5605. )
  5606. return False
  5607. if len(candidates) > 1:
  5608. if require_unambiguous:
  5609. # The baseline is not evidence -- it was taken off a card that could
  5610. # not be read -- so "new since the baseline" does not narrow these
  5611. # down at all. Taking the first would attach an arbitrary video to
  5612. # this print and then delete it from the printer.
  5613. logger.warning(
  5614. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  5615. "leaving all of them on the printer for manual selection",
  5616. attempt,
  5617. len(candidates),
  5618. ", ".join(str(f.get("name")) for f in candidates),
  5619. )
  5620. return False
  5621. logger.warning(
  5622. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  5623. "the rest stay on the printer for manual selection",
  5624. attempt,
  5625. len(candidates),
  5626. ", ".join(str(f.get("name")) for f in candidates),
  5627. )
  5628. target = candidates[0]
  5629. file_name = target.get("name")
  5630. remote_path = target.get("path") or f"/timelapse/{file_name}"
  5631. logger.info(
  5632. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  5633. attempt,
  5634. file_name,
  5635. archive_id,
  5636. )
  5637. # The listing always carries a size (`list_files` skips entries it can't
  5638. # parse), but read it explicitly: the delete below is destructive and must
  5639. # depend on a size we actually had, not on one we hoped was there.
  5640. expected_size = target.get("size")
  5641. timelapse_data = await download_file_bytes_async(
  5642. printer.ip_address,
  5643. printer.access_code,
  5644. remote_path,
  5645. printer_model=printer.model,
  5646. expected_size=expected_size,
  5647. )
  5648. if not timelapse_data:
  5649. # Short or failed transfer. The printer keeps its copy, so the next
  5650. # round can try again — which is exactly why the delete below is
  5651. # gated on a verified download.
  5652. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  5653. return False
  5654. # The length check above proves we got what the listing said, not that the
  5655. # printer had finished writing. A video still being written can be listed
  5656. # short, served short, and pass — so confirm it has stopped growing before
  5657. # committing to it and deleting the original (#2704).
  5658. if not await remote_file_settled(
  5659. printer.ip_address,
  5660. printer.access_code,
  5661. remote_path,
  5662. len(timelapse_data),
  5663. printer_model=printer.model,
  5664. ):
  5665. return False
  5666. # Write phase: attach in a fresh short-lived session.
  5667. async with async_session() as db:
  5668. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name, plate_id=plate_id)
  5669. if not success:
  5670. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  5671. return False
  5672. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  5673. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  5674. await delete_archived_timelapse(
  5675. printer.ip_address,
  5676. printer.access_code,
  5677. remote_path,
  5678. verified=expected_size is not None,
  5679. printer_model=printer.model,
  5680. printer_name=printer.name,
  5681. )
  5682. return True
  5683. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  5684. # module-level so tests can monkeypatch them down to ~0 without timing out.
  5685. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  5686. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  5687. # How long the *background* upgrade keeps waiting after the notification has
  5688. # already gone out (#2704 follow-up). The short bound above exists so a slow
  5689. # printer can't hold up the print-complete notification; this one exists so the
  5690. # archive still ends up with the better frame afterwards.
  5691. #
  5692. # Measured across 261 attaches in the support bundles, the video lands a median
  5693. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  5694. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  5695. # was 546s. Every other model was inside 26s. The long budget is therefore
  5696. # almost entirely for P1-series users; on everything else the short wait already
  5697. # wins and this task never runs.
  5698. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  5699. async def _capture_finish_photo_from_timelapse(
  5700. archive_id: int,
  5701. archive_dir: Path,
  5702. timeout: float | None = None,
  5703. rotation: int = 0,
  5704. ) -> tuple[str | None, bool]:
  5705. """Wait for the per-print timelapse to land on the archive and extract its
  5706. last frame as the finish photo (#1397).
  5707. Bambu firmware stops timelapse recording after the toolhead parks but
  5708. before the bed-drop end-gcode runs, so the last frame frames the finished
  5709. print correctly. A live camera grab at gcode_state=FINISH captures the
  5710. bed already lowered.
  5711. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  5712. ``archive.timelapse_path`` when the file lands. This function polls for
  5713. that field.
  5714. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  5715. the wait ran out with no video on the archive yet — i.e. the video may
  5716. still be coming and a later attempt could succeed. It is False when the
  5717. video landed (whether or not extraction worked), because in that case
  5718. waiting longer changes nothing. The caller uses that to decide between
  5719. falling back permanently and scheduling a background upgrade.
  5720. ``rotation`` is the printer's camera_rotation, applied to the extracted
  5721. still (#2708) so this source agrees with every other finish-photo source.
  5722. The archived video itself is the printer's own file and is left alone —
  5723. rotating it would mean re-encoding it.
  5724. """
  5725. import uuid
  5726. from backend.app.models.archive import PrintArchive
  5727. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  5728. logger = logging.getLogger(__name__)
  5729. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  5730. deadline = asyncio.get_event_loop().time() + budget
  5731. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  5732. while True:
  5733. async with async_session() as db:
  5734. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5735. archive = result.scalar_one_or_none()
  5736. timelapse_relpath = archive.timelapse_path if archive else None
  5737. if timelapse_relpath:
  5738. video_path = app_settings.base_dir / timelapse_relpath
  5739. if video_path.exists() and video_path.stat().st_size > 0:
  5740. photos_dir = archive_dir / "photos"
  5741. photos_dir.mkdir(parents=True, exist_ok=True)
  5742. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5743. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5744. output_path = photos_dir / filename
  5745. if await extract_video_last_frame(video_path, output_path):
  5746. await apply_camera_rotation_to_file(output_path, rotation, logger)
  5747. logger.info(
  5748. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  5749. video_path.name,
  5750. archive_id,
  5751. )
  5752. return filename, False
  5753. logger.warning(
  5754. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  5755. video_path.name,
  5756. archive_id,
  5757. )
  5758. return None, False
  5759. if asyncio.get_event_loop().time() >= deadline:
  5760. logger.info(
  5761. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  5762. archive_id,
  5763. budget,
  5764. )
  5765. return None, True
  5766. await asyncio.sleep(poll_interval)
  5767. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  5768. """Add the timelapse's last frame to an archive after the fact (#2704).
  5769. The print-complete notification waits only ~60s for the video, because
  5770. holding a notification for minutes is worse than sending it with a live
  5771. camera grab. On a P1-series printer the video often lands well after that,
  5772. so the archive used to be stuck with the live grab — which is taken at
  5773. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  5774. the worse photo of the two.
  5775. This keeps waiting in the background and, when the video arrives, extracts
  5776. the frame and puts it *first* in the archive's photo list, so opening the
  5777. gallery shows it. The live grab is deliberately kept: the notification that
  5778. already went out links to that exact file, and deleting it would leave a
  5779. broken image in Discord or Telegram.
  5780. """
  5781. logger = logging.getLogger(__name__)
  5782. filename, _ = await _capture_finish_photo_from_timelapse(
  5783. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  5784. )
  5785. if not filename:
  5786. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  5787. return
  5788. try:
  5789. async with async_session() as db:
  5790. from backend.app.models.archive import PrintArchive
  5791. archive = await db.get(PrintArchive, archive_id)
  5792. if archive is None:
  5793. return
  5794. photos = list(archive.photos or [])
  5795. if filename in photos:
  5796. return
  5797. # Front of the list: PhotoGalleryModal opens at index 0.
  5798. archive.photos = [filename, *photos]
  5799. await db.commit()
  5800. except Exception as e:
  5801. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  5802. return
  5803. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  5804. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  5805. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  5806. """Put the filament-attribution context back after a restart mid-print.
  5807. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  5808. both die with the process. The print keeps running, so at completion the
  5809. tracker would fall back to whatever the printer reports *now* — and AMS
  5810. filament backup makes "now" the substitute tray, charging the whole print
  5811. to the spool that only finished it.
  5812. The persisted row is only trusted when its print name still matches what
  5813. the printer says it is running: a row left behind by a completion we never
  5814. saw must not attach itself to the next print.
  5815. """
  5816. try:
  5817. from backend.app.api.routes.settings import get_setting
  5818. from backend.app.services.usage_tracker import (
  5819. clear_persisted_session,
  5820. get_persisted_print_name,
  5821. restore_session,
  5822. )
  5823. persisted_name = await get_persisted_print_name(db, printer_id)
  5824. current_name = (state.subtask_name or "").strip()
  5825. if persisted_name and current_name and persisted_name.strip() != current_name:
  5826. logger.info(
  5827. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  5828. printer_id,
  5829. persisted_name,
  5830. current_name,
  5831. )
  5832. await clear_persisted_session(db, printer_id)
  5833. # Fall through to seeding: the print on the printer is real, it just
  5834. # isn't the one the row described.
  5835. persisted_log = None
  5836. else:
  5837. # Spoolman users get the tray-change log back but no in-memory
  5838. # session — see ``on_print_start`` on why that dict is load-bearing
  5839. # for the remain%-sync guard.
  5840. _spoolman_on = await get_setting(db, "spoolman_enabled")
  5841. persisted_log = await restore_session(
  5842. db,
  5843. printer_id,
  5844. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  5845. )
  5846. if persisted_log:
  5847. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  5848. # Anything this process already observed goes after the persisted
  5849. # history — the log is ordered by layer, and a fresh process can
  5850. # only have seen changes from later in the print.
  5851. for entry in state.tray_change_log or []:
  5852. if tuple(entry) not in restored:
  5853. restored.append(tuple(entry))
  5854. state.tray_change_log = restored
  5855. tray_now = state.tray_now
  5856. if 0 <= tray_now <= 254:
  5857. if not state.tray_change_log:
  5858. # No persisted history — a print that started before this build,
  5859. # or before the row existed. Seed with the tray feeding right
  5860. # now so the remainder of the print is at least attributable to
  5861. # the right spool.
  5862. state.tray_change_log = [(tray_now, state.layer_num)]
  5863. logger.info(
  5864. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  5865. printer_id,
  5866. tray_now,
  5867. state.layer_num,
  5868. )
  5869. # The tray handler updates ``last_loaded_tray`` on every push
  5870. # regardless of whether it logged a change, so re-align it to avoid
  5871. # a duplicate entry on the next push. Only ever with a real tray:
  5872. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  5873. # 255" fallback, and writing 255 into it would defeat that.
  5874. state.last_loaded_tray = tray_now
  5875. except Exception:
  5876. # Never let attribution recovery cost the caller its timelapse
  5877. # baseline — that capture has to happen before the printer uploads
  5878. # the in-flight MP4 and there is no second chance at it.
  5879. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  5880. async def on_print_running_observed(printer_id: int, data: dict):
  5881. """Restart-recovery for a print that started before Bambuddy came up.
  5882. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  5883. after Bambuddy startup (#1304 guard, prevents duplicate archive
  5884. creation). This hook restores the persisted archive into ``_active_prints``
  5885. and captures the timelapse baseline that normally hangs off print start.
  5886. Fires once per session, in lieu of on_print_start when restart-recovery
  5887. kicks in. The printer doesn't upload the timelapse until after PRINT
  5888. COMPLETE, so a baseline captured any time during the print is still
  5889. pre-upload.
  5890. """
  5891. logger = logging.getLogger(__name__)
  5892. async with async_session() as db:
  5893. from backend.app.models.printer import Printer
  5894. state = printer_manager.get_status(printer_id)
  5895. if state is not None:
  5896. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  5897. if authorization is True:
  5898. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  5899. await _restore_usage_tracking_session(printer_id, state, db, logger)
  5900. await _restore_printable_objects(printer_id, state, db, logger)
  5901. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5902. printer = result.scalar_one_or_none()
  5903. if not printer:
  5904. logger.warning(
  5905. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  5906. printer_id,
  5907. )
  5908. return
  5909. # Avoid double-capture: ownership reconciliation above must still run when
  5910. # a baseline already exists, but the camera work itself is one-shot.
  5911. if printer_id in _timelapse_baselines:
  5912. logger.debug(
  5913. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  5914. printer_id,
  5915. )
  5916. return
  5917. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  5918. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  5919. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  5920. against the printer's current MQTT state.
  5921. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  5922. COMPLETE events, typically a print finishing during an MQTT disconnect
  5923. window followed by a smart-plug power cycle):
  5924. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  5925. provably not running anymore — only branch that should fire under
  5926. normal disconnect-then-reconnect timing.
  5927. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  5928. firmware mints a fresh ``subtask_id`` for each print, including the
  5929. ghost replay it runs after a power cycle from a leftover SD file —
  5930. so a mismatch unambiguously means the in-DB archive is no longer
  5931. the print on the printer.
  5932. 3. Printer is running but ``subtask_name`` is empty. The printer
  5933. doesn't know what it's running; the archive's reference to it is
  5934. already broken.
  5935. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  5936. with matching subtask_id+subtask_name is left alone. The cost of a false
  5937. positive is a duplicate archive on the next real PRINT COMPLETE — the
  5938. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  5939. clears on synthesis, so the real completion creates a fresh row instead
  5940. of overwriting the synthesised one (#1679). The cost of a false negative
  5941. is the ghost-print loop in #1542.
  5942. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  5943. MQTT has connected but the first ``push_status`` response hasn't been
  5944. applied yet — ``PrinterState`` is sitting on its construction defaults.
  5945. The reconcile caller in ``on_printer_status_change`` is already gated
  5946. on a real ``state.state``, so in normal operation this branch is
  5947. unreachable; it's kept as belt-and-braces for future callers and for
  5948. the narrow window where a partial state update could arrive
  5949. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  5950. ``not stale`` on degenerate input is strictly conservative: a real
  5951. stale archive will still be caught by the next push_status arriving
  5952. with terminal state.
  5953. """
  5954. current_state = (state.state or "").upper()
  5955. if current_state in ("", "UNKNOWN"):
  5956. # No real push_status yet — PrinterState defaults are not evidence.
  5957. return False, ""
  5958. if current_state in ("IDLE", "FINISH", "FAILED"):
  5959. return True, f"printer state {current_state}"
  5960. # Below here the printer is in a running / pre-running state (RUNNING /
  5961. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  5962. current_subtask_id = (state.subtask_id or "").strip()
  5963. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  5964. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  5965. current_subtask_name = (state.subtask_name or "").strip()
  5966. if not current_subtask_name:
  5967. return True, "printer subtask_name empty"
  5968. return False, ""
  5969. async def prime_kprofile_table(printer_id: int) -> int:
  5970. """Read the printer's calibration table once per connection.
  5971. The AMS slot card shows a K value per slot (#2854). On the printers whose
  5972. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  5973. report ``cali_idx`` and nothing else -- that number can only come from
  5974. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  5975. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  5976. backup, or the printer answering a query BambuStudio made on the report
  5977. topic we share. A Bambuddy that nobody visited showed a card with no K
  5978. values at all.
  5979. Only the diameters actually fitted are asked for, which is one request on a
  5980. single-nozzle printer and two on a dual. Probing the four sizes blind is
  5981. what the backup does, and it is both wasteful and the thing that used to
  5982. blank the table.
  5983. Returns the number of nozzles whose table was read.
  5984. """
  5985. client = printer_manager.get_client(printer_id)
  5986. state = printer_manager.get_status(printer_id)
  5987. if client is None or state is None or not state.connected:
  5988. return 0
  5989. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  5990. # ask once, and both entries are empty until the first push_status lands.
  5991. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  5992. if not diameters:
  5993. logging.getLogger(__name__).debug(
  5994. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  5995. printer_id,
  5996. )
  5997. return 0
  5998. primed = 0
  5999. for diameter in diameters:
  6000. try:
  6001. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  6002. except Exception as exc: # noqa: BLE001
  6003. # A printer that won't answer costs the card its K values, nothing
  6004. # more — never the connection this runs on the back of.
  6005. logging.getLogger(__name__).warning(
  6006. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  6007. )
  6008. continue
  6009. primed += 1
  6010. logging.getLogger(__name__).info(
  6011. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  6012. )
  6013. return primed
  6014. def _sd_files_in_use(state) -> set[str]:
  6015. """Names of the SD-card files the printer may be printing right now (#3009).
  6016. The post-print cleanup works out what to delete from the finished archive,
  6017. not from the printer. When reconciliation closes an old archive because the
  6018. printer has moved on to a new job, and that job is the same file reprinted
  6019. from the printer's screen, the cleanup would delete the file mid-print.
  6020. Empty unless the printer is busy: on an ordinary completion the state is
  6021. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  6022. name, a path or a URL depending on firmware, and some report only the
  6023. plate's G-code, so the job name is matched as well, in the same spellings
  6024. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  6025. ignores case.
  6026. """
  6027. def _text(value) -> str:
  6028. return value.strip() if isinstance(value, str) else ""
  6029. if state is None:
  6030. return set()
  6031. current_state = _text(getattr(state, "state", None)).upper()
  6032. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  6033. return set()
  6034. in_use: set[str] = set()
  6035. gcode_file = _text(getattr(state, "gcode_file", None))
  6036. if gcode_file:
  6037. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  6038. # both legal in a file name, and raises on some inputs.
  6039. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  6040. if name:
  6041. in_use.add(name.lower())
  6042. subtask_name = _text(getattr(state, "subtask_name", None))
  6043. if subtask_name:
  6044. for name in (subtask_name, subtask_name.replace(" ", "_")):
  6045. for ext in (".3mf", ".gcode"):
  6046. in_use.add(f"{name}{ext}".lower())
  6047. return in_use
  6048. async def reconcile_stale_active_prints(printer_id: int) -> int:
  6049. """Synthesise ``on_print_complete`` for archives whose print can't be
  6050. running on the printer anymore.
  6051. Called once per MQTT (re)connection (from on_printer_status_change when
  6052. the connected edge flips False → True) and at Bambuddy startup (from
  6053. the FastAPI lifespan). Without this, a print that completes during a
  6054. disconnect window — followed by a smart-plug-driven power cycle — leaves
  6055. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  6056. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  6057. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  6058. power cycle until the operator notices (#1542 follow-up). Reconciliation
  6059. closes the loop by faking the missed PRINT COMPLETE — the existing
  6060. cleanup chain handles SD-file deletion, status updates, usage tracking,
  6061. and notifications.
  6062. Synthesised ``status="aborted"`` is the conservative label: we have no
  6063. proof the print finished successfully (and no progress evidence to
  6064. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  6065. fires later, overwrites the status with the correct value.
  6066. Returns the number of archives reconciled.
  6067. """
  6068. state = printer_manager.get_status(printer_id)
  6069. if not state:
  6070. return 0
  6071. # Don't reconcile while disconnected — we'd be making a decision against
  6072. # stale cached state. The connected → reconcile edge handles this.
  6073. if not state.connected:
  6074. return 0
  6075. from backend.app.models.archive import PrintArchive
  6076. reconciled = 0
  6077. async with async_session() as db:
  6078. result = await db.execute(
  6079. select(PrintArchive).where(
  6080. PrintArchive.printer_id == printer_id,
  6081. PrintArchive.status == "printing",
  6082. )
  6083. )
  6084. active = list(result.scalars().all())
  6085. if not active:
  6086. return 0
  6087. logger = logging.getLogger(__name__)
  6088. for archive in active:
  6089. is_stale, reason = _is_active_archive_stale(archive, state)
  6090. if not is_stale:
  6091. continue
  6092. logger.info(
  6093. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  6094. printer_id,
  6095. archive.id,
  6096. archive.filename,
  6097. reason,
  6098. )
  6099. # Synthesised payload: minimal fields the on_print_complete chain
  6100. # needs. `_reconciled` marker lets downstream code distinguish this
  6101. # from a real MQTT-driven completion if it ever needs to (e.g. for
  6102. # metrics / debug logging). raw_data is the live printer state so
  6103. # the usage tracker can compare end-of-print remain% against the
  6104. # captured start values.
  6105. try:
  6106. await on_print_complete(
  6107. printer_id,
  6108. {
  6109. "status": "aborted",
  6110. "filename": archive.filename,
  6111. "subtask_name": archive.print_name or "",
  6112. "subtask_id": archive.subtask_id or "",
  6113. "raw_data": state.raw_data or {},
  6114. "_reconciled": True,
  6115. },
  6116. )
  6117. reconciled += 1
  6118. except Exception as e:
  6119. # Catch-all: a reconciliation failure must not block the
  6120. # printer's normal status flow. The archive stays in
  6121. # ``status="printing"`` and the next reconnect retries.
  6122. logger.warning(
  6123. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  6124. archive.id,
  6125. e,
  6126. )
  6127. return reconciled
  6128. # #2547: clearance left between the nozzle and the top of the print when the
  6129. # plate is commanded back into camera framing. The nozzle is parked away from
  6130. # the part by then, so this is belt-and-braces against a max_z_height that
  6131. # under-reports (e.g. a slicer that excludes a final Z hop).
  6132. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  6133. # How far below the restored position to drop the plate again afterwards, so
  6134. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  6135. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  6136. # on machines with less headroom.
  6137. _PLATE_PARK_DROP_MM = 100.0
  6138. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  6139. # this axis, so it is a proven-safe speed for the full travel.
  6140. _PLATE_RESTORE_FEEDRATE = 600
  6141. # Time allowed for the plate to reach the restored position before the camera
  6142. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  6143. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  6144. # How long `_background_finish_photo` waits for this producer. Must cover the
  6145. # settle window plus a worst-case RTSP grab (15s), and stay below the
  6146. # notification path's own photo wait so a slow producer degrades to a
  6147. # photo-less notification rather than a missed one. The chamber light's
  6148. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  6149. # camera_light.MAX_DELAY_SECONDS stays below it.
  6150. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  6151. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  6152. """The ``_active_prints`` keys a finished print may be registered under.
  6153. Matching how they were registered in on_print_start. Shared by
  6154. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  6155. to find the same binding.
  6156. """
  6157. possible_keys = []
  6158. # Try subtask_name variations first (most reliable for matching)
  6159. if subtask_name:
  6160. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  6161. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  6162. possible_keys.append((printer_id, subtask_name))
  6163. # Try filename variations
  6164. if filename:
  6165. # Extract just the filename if it's a path
  6166. fname = filename.split("/")[-1] if "/" in filename else filename
  6167. if fname.endswith(".3mf"):
  6168. possible_keys.append((printer_id, fname))
  6169. elif fname.endswith(".gcode"):
  6170. base_name = fname.rsplit(".", 1)[0]
  6171. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  6172. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6173. possible_keys.append((printer_id, fname))
  6174. else:
  6175. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  6176. possible_keys.append((printer_id, f"{fname}.3mf"))
  6177. possible_keys.append((printer_id, fname))
  6178. # Also try full path versions
  6179. if filename.endswith(".3mf"):
  6180. possible_keys.append((printer_id, filename))
  6181. elif filename.endswith(".gcode"):
  6182. base_name = filename.rsplit(".", 1)[0]
  6183. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6184. possible_keys.append((printer_id, filename))
  6185. else:
  6186. possible_keys.append((printer_id, f"{filename}.3mf"))
  6187. possible_keys.append((printer_id, filename))
  6188. return possible_keys
  6189. def _archive_name_forms(archive) -> set[str]:
  6190. """The names an archive could be echoed back as, in normalised form (#3240).
  6191. Its print name, and its filename with and without the 3MF extension.
  6192. """
  6193. forms = set()
  6194. if archive.print_name:
  6195. forms.add(_normalise_subtask_name(archive.print_name))
  6196. if archive.filename:
  6197. forms.add(_normalise_subtask_name(archive.filename))
  6198. for suffix in (".gcode.3mf", ".3mf"):
  6199. if archive.filename.lower().endswith(suffix):
  6200. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  6201. forms.discard("")
  6202. return forms
  6203. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  6204. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  6205. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  6206. from the plate recorded when the job was dispatched. Neither is touched:
  6207. ``on_print_complete`` pops both, which is why the finish-photo producer
  6208. calls this before its first await, while they are still there.
  6209. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  6210. archive, or that it only knows by a name -- and on any error: the producer
  6211. calls this before the ``try`` that always releases the photo consumer, so
  6212. it must not raise.
  6213. """
  6214. try:
  6215. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  6216. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  6217. if archive_id is None:
  6218. return None, None
  6219. return archive_id, _print_plate_ids.get(archive_id)
  6220. except Exception:
  6221. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  6222. return None, None
  6223. async def _max_z_for_current_print(
  6224. printer_id: int,
  6225. data: dict,
  6226. logger,
  6227. archive_id: int | None,
  6228. plate_id: int | None = None,
  6229. ) -> float | None:
  6230. """Height of the print that just finished on ``printer_id``, or None (#2547).
  6231. This number becomes the target of a real Z move, so every step here refuses
  6232. rather than guesses. A height belonging to some *other* print is the one
  6233. failure that could drive the nozzle into the model: 20 mm carried onto a
  6234. 200 mm print would command the plate up through the part.
  6235. Three independent things therefore have to agree before a height is
  6236. returned:
  6237. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  6238. when it started (see ``_bound_print``), never one found by name. A name
  6239. is not an identity: every plate of a multi-plate file shares one, and a
  6240. reprint reuses its archive row, so the newest archive with the right
  6241. name can be another plate of the same file. Support bundles show the
  6242. old name lookup doing exactly that (archive 288 for a print bound to
  6243. 169, 313 layers against 125), stopped only by the layer check below.
  6244. No binding, no move.
  6245. 2. **Identity.** The bound archive's name still has to be the finished
  6246. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  6247. because the printer echoes spaces as underscores (#3240). Exact: not a
  6248. substring, and not the completion check's tolerance for a truncated
  6249. echo.
  6250. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  6251. match the layer count the printer itself reported over MQTT for the print
  6252. that just ended. These come from genuinely different sources, so a
  6253. mismatch means the row is not this print, whatever its name says.
  6254. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  6255. plate of a multi-plate file reuses the archive row without updating its
  6256. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  6257. ``on_print_complete`` may already have flipped the status by the time we
  6258. run.
  6259. """
  6260. subtask_name = (data.get("subtask_name") or "").strip()
  6261. if not subtask_name:
  6262. # Nothing to identify the print by — refuse rather than fall back to
  6263. # "whatever ran last on this printer".
  6264. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  6265. return None
  6266. if archive_id is None:
  6267. logger.info(
  6268. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  6269. printer_id,
  6270. subtask_name,
  6271. )
  6272. return None
  6273. try:
  6274. from backend.app.models.archive import PrintArchive
  6275. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  6276. async with async_session() as db:
  6277. result = await db.execute(
  6278. select(PrintArchive).where(
  6279. PrintArchive.id == archive_id,
  6280. PrintArchive.printer_id == printer_id,
  6281. PrintArchive.status.in_(("printing", "completed")),
  6282. PrintArchive.deleted_at.is_(None),
  6283. )
  6284. )
  6285. archive = result.scalar_one_or_none()
  6286. if archive is None or not archive.file_path:
  6287. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  6288. return None
  6289. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  6290. logger.warning(
  6291. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  6292. printer_id,
  6293. archive_id,
  6294. subtask_name,
  6295. )
  6296. return None
  6297. client = printer_manager.get_client(printer_id)
  6298. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  6299. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  6300. logger.warning(
  6301. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  6302. "— refusing to move the plate on a height that may not be this print's",
  6303. printer_id,
  6304. archive.id,
  6305. archive.total_layers,
  6306. reported_layers,
  6307. )
  6308. return None
  6309. # Stored relative to the data directory, like every other archive path
  6310. # (#3240: this read a `data_dir` setting that does not exist).
  6311. path = app_settings.base_dir / archive.file_path
  6312. plate = plate_id or archive.plate_id or 1
  6313. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  6314. except Exception as e:
  6315. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  6316. return None
  6317. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  6318. """Raise the plate back into camera framing before the finish photo (#2547).
  6319. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  6320. the time ``gcode_state`` reaches FINISH the finished print sits far below
  6321. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  6322. This commands an absolute ``G1 Z`` back to just above the last printed
  6323. layer.
  6324. Absolute, not relative, is the whole safety argument. ``max_z_height +
  6325. clearance`` is a height the toolhead was physically at seconds earlier, so
  6326. it is inside the travel limits by construction and leaves the nozzle above
  6327. the part. It is also unambiguous across model families: Z is the
  6328. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  6329. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  6330. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  6331. (#2579).
  6332. Returns True if the move was sent and waited out, False if it was skipped.
  6333. """
  6334. client = printer_manager.get_client(printer_id)
  6335. if client is None:
  6336. return False
  6337. # Re-read state immediately before commanding motion. If the queue has
  6338. # already started the next print, the printer is no longer ours to move.
  6339. state = getattr(client, "state", None)
  6340. if state is None or state.state != "FINISH":
  6341. logger.info(
  6342. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  6343. printer_id,
  6344. getattr(state, "state", "unknown"),
  6345. )
  6346. return False
  6347. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  6348. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  6349. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  6350. return False
  6351. logger.info(
  6352. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  6353. printer_id,
  6354. target_z,
  6355. max_z_height,
  6356. _PLATE_RESTORE_CLEARANCE_MM,
  6357. _PLATE_RESTORE_SETTLE_SECONDS,
  6358. )
  6359. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  6360. return True
  6361. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  6362. """Drop the plate again after the finish photo (#2547).
  6363. Without this the user walks up to a finished print sitting just under the
  6364. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  6365. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  6366. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  6367. print homes anyway.
  6368. """
  6369. client = printer_manager.get_client(printer_id)
  6370. state = getattr(client, "state", None) if client else None
  6371. if client is None or state is None or state.state != "FINISH":
  6372. return
  6373. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  6374. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  6375. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  6376. """True if a queue item is about to take this printer (#2547).
  6377. The scheduler dispatches the next job the moment a print completes, and a
  6378. plate move interleaved with a print start is not a race worth having. The
  6379. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  6380. this window; this closes the head of it.
  6381. """
  6382. try:
  6383. from backend.app.models.print_queue import PrintQueueItem
  6384. async with async_session() as db:
  6385. result = await db.execute(
  6386. select(PrintQueueItem.id)
  6387. .where(
  6388. PrintQueueItem.printer_id == printer_id,
  6389. PrintQueueItem.status.in_(("pending", "printing")),
  6390. )
  6391. .limit(1)
  6392. )
  6393. return result.scalar_one_or_none() is not None
  6394. except Exception as e:
  6395. # Fail closed: if we can't tell, don't move the plate.
  6396. logging.getLogger(__name__).debug(
  6397. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  6398. )
  6399. return True
  6400. async def on_finish_photo_moment(printer_id: int, data: dict):
  6401. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  6402. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  6403. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  6404. fallback for prints that skip stage 22 (cancel, external-spool-only,
  6405. HMS halt, firmware variants). Grabs one frame via the same
  6406. external-camera / RTSP path the post-completion fallback uses, stores
  6407. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  6408. ``_background_finish_photo`` consume the cached bytes when it runs.
  6409. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  6410. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  6411. set to Smooth (#1721). No force-on now means the user's explicit
  6412. timelapse=off in the slicer send dialog is respected.
  6413. """
  6414. logger = logging.getLogger(__name__)
  6415. trigger = data.get("trigger", "unknown")
  6416. timelapse_was_active = bool(data.get("timelapse_was_active"))
  6417. logger.info(
  6418. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  6419. printer_id,
  6420. trigger,
  6421. timelapse_was_active,
  6422. )
  6423. # If a timelapse is actively recording, skip the pre-capture — the
  6424. # post-completion path will extract the last frame from the recorded
  6425. # video, which still provides the best framing (toolhead parked,
  6426. # before bed drop) without the per-layer parking side effects.
  6427. if timelapse_was_active:
  6428. logger.info(
  6429. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  6430. printer_id,
  6431. )
  6432. return
  6433. # #1790: register the producer-done event BEFORE the first await so the
  6434. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  6435. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  6436. # The `finally` below guarantees `set()` runs on every exit, including
  6437. # early returns and exceptions, so the consumer's bounded wait can't hang.
  6438. producer_done = asyncio.Event()
  6439. _stage22_finish_in_flight[printer_id] = producer_done
  6440. # #3240: also before the first await. On the FINISH-state path
  6441. # `on_print_complete` is dispatched right behind us and pops both the
  6442. # print's archive binding and its plate; read here, they are still there.
  6443. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  6444. # #2547: set once the plate has actually been raised, and read by the
  6445. # `finally` below. Declared out here so a failure anywhere after the move —
  6446. # a camera timeout, a DB error — still lowers the plate again.
  6447. restore_max_z: float | None = None
  6448. try:
  6449. async with async_session() as db:
  6450. from backend.app.api.routes.settings import get_setting
  6451. from backend.app.models.printer import Printer
  6452. capture_setting = await get_setting(db, "capture_finish_photo")
  6453. if capture_setting is not None and capture_setting.lower() != "true":
  6454. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  6455. return
  6456. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6457. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  6458. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6459. printer = result.scalar_one_or_none()
  6460. if printer is None:
  6461. logger.warning(
  6462. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  6463. printer_id,
  6464. )
  6465. return
  6466. frame_bytes: bytes | None = None
  6467. # #2708: the banked frame arrives already rotated — it comes from
  6468. # `_capture_snapshot_for_notification`, which rotates before returning.
  6469. # Every other source below is a raw grab. Tracking which lets us store
  6470. # exactly one rotation in `_stage22_finish_frames` either way.
  6471. frame_already_rotated = False
  6472. # On the FINISH-state path the End G-code has already run, and two very
  6473. # different situations arrive here needing opposite answers.
  6474. #
  6475. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  6476. # snippet may have ejected the plate — the scene in front of the camera
  6477. # is no longer the finished print, and no amount of moving the plate
  6478. # brings it back. Use the banked in-print frame instead.
  6479. #
  6480. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  6481. # than the camera frames well, and the toolhead is parked out of the
  6482. # way. That is the *best* moment available on firmware that never emits
  6483. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  6484. # back. Preferring the bank here unconditionally, as this code used to,
  6485. # is what shipped a mid-print photo with the toolhead over the part.
  6486. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  6487. banked = _inprint_frame_bank.get(printer_id)
  6488. if banked:
  6489. frame_bytes = banked
  6490. frame_already_rotated = True
  6491. logger.info(
  6492. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  6493. "frame (%d bytes) instead of a post-swap live grab",
  6494. len(banked),
  6495. )
  6496. else:
  6497. logger.warning(
  6498. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  6499. "in-print bank is empty — falling back to a live grab, which may show a "
  6500. "swapped or empty plate",
  6501. printer_id,
  6502. )
  6503. # `restore_max_z` is set only once the plate is actually up, because the
  6504. # `finally` reads it to decide whether it owes a move back down.
  6505. #
  6506. # Never on a print whose End G-code Bambuddy injected, even when the bank
  6507. # came up empty above: that machine may have just ejected its plate, and
  6508. # driving Z into whatever a swap mechanism is doing is not a risk worth
  6509. # taking for a photo of a bed we already know may be bare.
  6510. if (
  6511. frame_bytes is None
  6512. and trigger == "finish_state"
  6513. and restore_plate_enabled
  6514. and not print_dispatch_context.end_gcode_injected(printer_id)
  6515. ):
  6516. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  6517. if wants_restore is None:
  6518. logger.info(
  6519. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  6520. printer_id,
  6521. )
  6522. elif await _plate_restore_is_blocked_by_queue(printer_id):
  6523. logger.info(
  6524. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  6525. printer_id,
  6526. )
  6527. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  6528. restore_max_z = wants_restore
  6529. # Chamber light for the live capture below (#1655). The banked frame
  6530. # above was taken without it, like every in-print bank.
  6531. async with camera_light(printer if frame_bytes is None else None):
  6532. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  6533. from backend.app.api.routes.camera import live_frame_for_capture
  6534. from backend.app.services.external_camera import capture_frame
  6535. # #2707: this used to collide with the live view and fail, which is
  6536. # how finish-photo notifications went out with no image attached.
  6537. # Leaving frame_bytes None keeps the rest of the fallback chain.
  6538. defer, buffered = live_frame_for_capture(printer_id)
  6539. if defer:
  6540. frame_bytes = buffered
  6541. else:
  6542. frame_bytes = await capture_frame(
  6543. printer.external_camera_url,
  6544. printer.external_camera_type or "mjpeg",
  6545. snapshot_url=printer.external_camera_snapshot_url,
  6546. )
  6547. if frame_bytes:
  6548. logger.info(
  6549. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  6550. len(frame_bytes),
  6551. )
  6552. elif frame_bytes is None:
  6553. from backend.app.api.routes.camera import get_buffered_frame
  6554. buffered = get_buffered_frame(printer_id)
  6555. if buffered:
  6556. frame_bytes = buffered
  6557. logger.info(
  6558. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  6559. len(frame_bytes),
  6560. )
  6561. else:
  6562. from backend.app.services.camera import capture_camera_frame_bytes
  6563. frame_bytes = await capture_camera_frame_bytes(
  6564. ip_address=printer.ip_address,
  6565. access_code=printer.access_code,
  6566. model=printer.model,
  6567. timeout=15,
  6568. )
  6569. if frame_bytes:
  6570. logger.info(
  6571. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  6572. len(frame_bytes),
  6573. )
  6574. if frame_bytes:
  6575. if not frame_already_rotated:
  6576. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  6577. _stage22_finish_frames[printer_id] = frame_bytes
  6578. else:
  6579. logger.warning(
  6580. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  6581. printer_id,
  6582. )
  6583. except Exception as e:
  6584. logger.warning(
  6585. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  6586. printer_id,
  6587. e,
  6588. )
  6589. finally:
  6590. # #2547: we raised the plate, so we own lowering it — including when the
  6591. # capture above failed or threw partway through.
  6592. if restore_max_z is not None:
  6593. try:
  6594. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  6595. except Exception as e:
  6596. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6597. # #1790: always unblock the consumer's bounded wait — whether we stored
  6598. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  6599. # dict entry by the consumer doesn't affect signalling.
  6600. producer_done.set()
  6601. def _subtask_name_from_filename(filename: str) -> str:
  6602. """Recover the subtask name a print command would have carried for *filename*.
  6603. The dispatcher derives the printer-facing subtask name from the archive's
  6604. file name, so stripping the extensions back off gives the value MQTT echoes
  6605. on completion. Only the two extensions Bambuddy actually stores are removed,
  6606. and in the order they nest (``.gcode.3mf``), so a model whose own name
  6607. contains a dot -- ``My.Model.3mf`` -- keeps it.
  6608. """
  6609. name = PurePosixPath(filename).name
  6610. for suffix in (".3mf", ".gcode"):
  6611. if name.lower().endswith(suffix):
  6612. name = name[: -len(suffix)]
  6613. return name
  6614. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  6615. """Whether the subtask name is the printed 3MF's own file name.
  6616. A print started from the printer's screen reports the same full name, with
  6617. its extension, as both subtask and file (#3009). A dispatched print reports
  6618. a bare subtask name; one that merely ends in ".3mf" can be a model named
  6619. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  6620. """
  6621. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  6622. return False
  6623. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  6624. # How the printer marks a subtask name it had to cut short. Observed on real
  6625. # hardware at ~100 characters, but the cut-off is not a fixed character count
  6626. # (a name with multibyte characters came back at 98), so match the marker
  6627. # rather than a length.
  6628. _SUBTASK_TRUNCATION_MARKER = "..."
  6629. def _normalise_subtask_name(name: str) -> str:
  6630. """Canonical form for comparing a dispatched name against MQTT's echo.
  6631. The printer does not echo the name back verbatim: it substitutes
  6632. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  6633. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  6634. The 3MF lookup in this module has always known that -- it builds
  6635. space-to-underscore variants of every candidate filename, and its
  6636. directory search normalises both sides before comparing. This exists so
  6637. the completion check reads the same rule from the same place instead of
  6638. growing its own, which is exactly how it came to disagree (#2829).
  6639. A space at either end is substituted too: ``Part .gcode.3mf`` is
  6640. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  6641. are dropped after the substitution so both sides agree (#3241).
  6642. """
  6643. return name.strip().replace(" ", "_").strip("_").casefold()
  6644. def _subtask_names_match(expected: str, observed: str) -> bool:
  6645. """Whether two subtask names describe the same print.
  6646. Beyond the space/underscore substitution, the printer truncates long names
  6647. and marks the cut with ``...``. A truncated echo has to count as a match or
  6648. every print with a long name strands its queue item the same way.
  6649. """
  6650. expected_n = _normalise_subtask_name(expected)
  6651. observed_n = _normalise_subtask_name(observed)
  6652. if expected_n == observed_n:
  6653. return True
  6654. # Either side can be the truncated one: the printer truncates what it
  6655. # echoes, and an archive whose own filename was recorded from a previous
  6656. # truncated echo carries the marker too.
  6657. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  6658. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  6659. continue
  6660. # The full side has lost its edge underscores; a cut that lands right
  6661. # after one keeps it, so drop it here too (#3241). Nothing left before
  6662. # the marker is no evidence of anything, and must not match every name.
  6663. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  6664. if kept and full.startswith(kept):
  6665. return True
  6666. return False
  6667. async def _queue_item_dispatched_name(db, item) -> str:
  6668. """The subtask name *item* was dispatched under, or "" when unknowable.
  6669. A row with no archive, or an archive with no file name, is unverifiable
  6670. rather than wrong; every caller answers that with its permissive branch.
  6671. """
  6672. if item.archive_id is None:
  6673. return ""
  6674. from backend.app.models.archive import PrintArchive
  6675. archive = await db.get(PrintArchive, item.archive_id)
  6676. if archive is None or not archive.filename:
  6677. return ""
  6678. return _subtask_name_from_filename(archive.filename)
  6679. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  6680. """Whether this completion event is plausibly about *item*'s print.
  6681. The caller finds its queue row by printer and ``status='printing'`` alone,
  6682. which is all a completion event gives it -- there is no run identifier in
  6683. the MQTT payload to match on. That makes the lookup indiscriminate: any
  6684. completion delivered for this printer closes whichever row happens to be
  6685. printing, however unrelated. Comparing the subtask name against the archive
  6686. the row was dispatched with costs one primary-key load and rules that out.
  6687. Deliberately permissive: it answers False only on a positive disagreement
  6688. between two names we actually have. A row with no archive, an archive with
  6689. no file name, or an event with no subtask name is unverifiable rather than
  6690. wrong, and refusing those would strand the item in ``printing`` and wedge
  6691. the printer's queue -- a worse failure than the one being prevented.
  6692. """
  6693. observed = (data.get("subtask_name") or "").strip()
  6694. if not observed or item.archive_id is None:
  6695. return True
  6696. from backend.app.models.archive import PrintArchive
  6697. archive = await db.get(PrintArchive, item.archive_id)
  6698. if archive is None or not archive.filename:
  6699. return True
  6700. expected = _subtask_name_from_filename(archive.filename)
  6701. if not expected or _subtask_names_match(expected, observed):
  6702. return True
  6703. logging.getLogger(__name__).warning(
  6704. "Ignoring print completion for queue item %s: it was dispatched as %r "
  6705. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  6706. "printing rather than closing a run this event is not about.",
  6707. item.id,
  6708. expected,
  6709. archive.id,
  6710. archive.filename,
  6711. observed,
  6712. )
  6713. return False
  6714. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  6715. """Spend the 3MF download cache on a still-empty fallback archive.
  6716. ``on_print_complete`` drops the cache as its first act, which deletes the
  6717. file. If the cover endpoint (or anything else) pulled the 3MF while the
  6718. print ran and the archive never got one, this is the last moment those bytes
  6719. exist (#2957).
  6720. """
  6721. logger = logging.getLogger(__name__)
  6722. names = [
  6723. n
  6724. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  6725. if n
  6726. ]
  6727. for name in names:
  6728. try:
  6729. cached = get_cached_3mf(printer_id, name)
  6730. if cached and await try_recover_fallback_archive(printer_id, name, cached):
  6731. return
  6732. except Exception as e:
  6733. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  6734. async def _cleanup_sd_card_after_print(
  6735. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  6736. ) -> None:
  6737. """Delete a finished print's file from the printer's SD card."""
  6738. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  6739. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  6740. # auto-start files found in root on power cycle, causing ghost prints.
  6741. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  6742. try:
  6743. if subtask_name:
  6744. archive_filename: str | None = None
  6745. async with async_session() as db:
  6746. from backend.app.models.archive import PrintArchive
  6747. from backend.app.models.printer import Printer
  6748. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6749. printer = result.scalar_one_or_none()
  6750. if archive_id:
  6751. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  6752. archive_filename = archive_row.scalar_one_or_none()
  6753. if printer:
  6754. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  6755. from backend.app.utils.filename import derive_remote_filename
  6756. # Primary candidate: the exact path the dispatcher uploaded to
  6757. # (derived from archive.filename via the same rule as upload).
  6758. # Without it, a library row that ended up with a doubled
  6759. # .gcode.3mf (#1542) leaves the real file behind because the
  6760. # subtask_name + ext fallbacks below don't match what's on the
  6761. # SD card. Fallbacks remain for archive-less prints (subtask
  6762. # never resolved to an archive) and for older naming variants.
  6763. candidate_paths: list[str] = []
  6764. if archive_filename:
  6765. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  6766. for ext in (".3mf", ".gcode"):
  6767. fallback = f"/{subtask_name}{ext}"
  6768. if fallback not in candidate_paths:
  6769. candidate_paths.append(fallback)
  6770. # Three outcomes track across all candidates so the final log
  6771. # line reflects what actually happened. The A1 in #1721 always
  6772. # ends here with ``any_not_found=True`` and the others False
  6773. # — its firmware auto-cleans the SD card before our cleanup
  6774. # runs, every candidate FTP-DELE returns 550, and the old
  6775. # code burned 3 retries × 2 s × 3 candidates per print
  6776. # logging a misleading "may linger" WARNING on a successful
  6777. # print.
  6778. any_deleted = False
  6779. any_real_failure = False
  6780. any_not_found = False
  6781. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  6782. for remote_path in candidate_paths:
  6783. if PurePosixPath(remote_path).name.lower() in files_in_use:
  6784. logger.info(
  6785. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  6786. remote_path,
  6787. printer.name,
  6788. )
  6789. continue
  6790. # Retry only the FAILED case — 550 NOT_FOUND will never
  6791. # recover by waiting, so a "file isn't here" answer
  6792. # advances immediately to the next candidate without
  6793. # consuming the retry budget.
  6794. for attempt in range(1, 4):
  6795. try:
  6796. delete_result = await delete_file_async(
  6797. printer.ip_address,
  6798. printer.access_code,
  6799. remote_path,
  6800. printer_model=printer.model,
  6801. )
  6802. except Exception as e:
  6803. delete_result = DeleteResult.FAILED
  6804. logger.warning(
  6805. "SD card cleanup attempt %d/3 raised for %s: %s",
  6806. attempt,
  6807. remote_path,
  6808. e,
  6809. )
  6810. if delete_result == DeleteResult.DELETED:
  6811. any_deleted = True
  6812. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  6813. break
  6814. if delete_result == DeleteResult.NOT_FOUND:
  6815. any_not_found = True
  6816. break # 550 will not recover; try next candidate
  6817. # FAILED: real error — retry with backoff, then give up
  6818. if attempt < 3:
  6819. await asyncio.sleep(2)
  6820. else:
  6821. any_real_failure = True
  6822. logger.warning(
  6823. "SD card cleanup failed after 3 attempts for %s "
  6824. "(network/auth/transient error — file may linger on SD card)",
  6825. remote_path,
  6826. )
  6827. if not any_deleted and not any_real_failure and any_not_found:
  6828. # Every candidate said "not here." Either the printer
  6829. # firmware swept the SD card itself (common on A1) or the
  6830. # dispatcher's upload path doesn't match our candidate
  6831. # rule. Either way: nothing to clean up, no warning.
  6832. logger.debug(
  6833. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  6834. "(printer likely self-cleaned)",
  6835. printer.name,
  6836. )
  6837. except Exception as e:
  6838. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  6839. async def on_print_complete(printer_id: int, data: dict):
  6840. """Handle print completion - update the archive status."""
  6841. import time
  6842. logger = logging.getLogger(__name__)
  6843. start_time = time.time()
  6844. def log_timing(section: str):
  6845. elapsed = time.time() - start_time
  6846. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  6847. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  6848. # A kill-switch stop sends its provider notification immediately. Keep the
  6849. # task so the later notification path can await it and avoid a duplicate;
  6850. # if that immediate attempt failed, the regular completion path retries.
  6851. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  6852. # Last chance before the bytes go: if this print's archive is still an empty
  6853. # fallback and something downloaded the 3MF while it ran, fill the archive in
  6854. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  6855. # below deletes the file (#2957).
  6856. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  6857. # A pending cool-off retry has nothing left to recover for — the cache is
  6858. # about to be dropped and the print is over.
  6859. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  6860. if retry_task and not retry_task.done():
  6861. retry_task.cancel()
  6862. # Drop the 3MF download cache for this printer (#972). The print is over,
  6863. # nothing else legitimately needs the bytes; keeping them would only risk
  6864. # handing a stale file to the next print if it reuses the same name.
  6865. clear_3mf_cache(printer_id)
  6866. try:
  6867. ws_data = {
  6868. "status": data.get("status"),
  6869. "filename": data.get("filename"),
  6870. "subtask_name": data.get("subtask_name"),
  6871. "timelapse_was_active": data.get("timelapse_was_active"),
  6872. }
  6873. await ws_manager.send_print_complete(printer_id, ws_data)
  6874. log_timing("WebSocket send_print_complete")
  6875. except Exception as e:
  6876. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  6877. # Capture user info before clearing (needed for print log entry)
  6878. _print_user_info = printer_manager.get_current_print_user(printer_id)
  6879. # Clear current print user tracking (Issue #206)
  6880. printer_manager.clear_current_print_user(printer_id)
  6881. # If the user explicitly stopped this print from the queue UI the printer will
  6882. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  6883. # correct "print stopped" notification/email is sent instead of a failure alert.
  6884. _raw_status = data.get("status", "completed")
  6885. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  6886. logger.info(
  6887. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  6888. _raw_status,
  6889. printer_id,
  6890. )
  6891. data = {**data, "status": "cancelled"}
  6892. _user_stopped_printers.discard(printer_id)
  6893. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  6894. # may have left material on the bed: a user can cancel ten hours into a
  6895. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  6896. # touchscreen-stop reports `aborted` rather than `cancelled` because
  6897. # `_user_stopped_printers` is only populated when the user stops via the
  6898. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  6899. # which auto-dispatched the next queued print onto a fouled bed two seconds
  6900. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  6901. # Auto Off power cycles and Bambuddy restarts.
  6902. try:
  6903. notify_live_activities.print_finished(printer_id, data)
  6904. except Exception:
  6905. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  6906. _final_status = data.get("status", "completed")
  6907. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  6908. printer_manager.set_awaiting_plate_clear(printer_id, True)
  6909. # MQTT relay - publish print complete
  6910. try:
  6911. printer_info = printer_manager.get_printer(printer_id)
  6912. if printer_info:
  6913. await mqtt_relay.on_print_complete(
  6914. printer_id,
  6915. printer_info.name,
  6916. printer_info.serial_number,
  6917. data.get("filename", ""),
  6918. data.get("subtask_name", ""),
  6919. data.get("status", "completed"),
  6920. )
  6921. except Exception:
  6922. pass # Don't fail print complete callback if MQTT fails
  6923. filename = data.get("filename", "")
  6924. subtask_name = data.get("subtask_name", "")
  6925. if not filename and not subtask_name:
  6926. logger.warning("Print complete without filename or subtask_name")
  6927. return
  6928. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  6929. # Build list of possible keys to try (matching how they were registered in on_print_start)
  6930. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  6931. # Find the archive for this print
  6932. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  6933. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  6934. archive_id = None
  6935. for key in possible_keys:
  6936. archive_id = _active_prints.pop(key, None)
  6937. if archive_id:
  6938. logger.info("Found archive %s with key %s", archive_id, key)
  6939. # Also clean up any other keys pointing to this archive
  6940. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  6941. for k in keys_to_remove:
  6942. _active_prints.pop(k, None)
  6943. break
  6944. # The archive bound when the print started, before the name search below.
  6945. # Only this one may give the finish-photo plate restore a height (#3240):
  6946. # the search matches names by substring.
  6947. bound_archive_id = archive_id
  6948. if not archive_id:
  6949. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  6950. async with async_session() as db:
  6951. from backend.app.models.archive import PrintArchive
  6952. # Try matching by subtask_name (stored as print_name) first
  6953. if subtask_name:
  6954. result = await db.execute(
  6955. select(PrintArchive)
  6956. .where(PrintArchive.printer_id == printer_id)
  6957. .where(PrintArchive.status == "printing")
  6958. .where(
  6959. or_(
  6960. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  6961. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  6962. )
  6963. )
  6964. .order_by(PrintArchive.created_at.desc())
  6965. .limit(1)
  6966. )
  6967. archive = result.scalar_one_or_none()
  6968. if archive:
  6969. archive_id = archive.id
  6970. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  6971. # Also try by filename
  6972. if not archive_id and filename:
  6973. result = await db.execute(
  6974. select(PrintArchive)
  6975. .where(PrintArchive.printer_id == printer_id)
  6976. .where(PrintArchive.filename == filename)
  6977. .where(PrintArchive.status == "printing")
  6978. .order_by(PrintArchive.created_at.desc())
  6979. .limit(1)
  6980. )
  6981. archive = result.scalar_one_or_none()
  6982. if archive:
  6983. archive_id = archive.id
  6984. await _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger)
  6985. log_timing("SD card cleanup")
  6986. # Update queue item status early — must run before the archive_id early-return
  6987. # so queue items don't get stuck in "printing" when archive lookup fails.
  6988. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  6989. queue_item_id = None
  6990. billing_run_id: str | None = None
  6991. billing_user_id: int | None = None
  6992. billing_cost_center_id: int | None = None
  6993. billing_plate_id: int | None = None
  6994. queue_status = None
  6995. queue_auto_off = False
  6996. try:
  6997. from backend.app.core.database import run_with_retry
  6998. from backend.app.models.print_queue import PrintQueueItem
  6999. async def _update_queue_status(db):
  7000. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  7001. nonlocal queue_item_id, queue_status, queue_auto_off
  7002. result = await db.execute(
  7003. select(PrintQueueItem)
  7004. .where(PrintQueueItem.printer_id == printer_id)
  7005. .where(PrintQueueItem.status == "printing")
  7006. )
  7007. printing_items = list(result.scalars().all())
  7008. if len(printing_items) > 1:
  7009. logger.warning(
  7010. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  7011. printer_id,
  7012. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  7013. )
  7014. item = printing_items[0] if printing_items else None
  7015. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  7016. return
  7017. if item:
  7018. queue_status = data.get("status", "completed")
  7019. # MQTT sends "aborted" for cancelled prints; normalise to
  7020. # "cancelled" so it matches the queue schema Literal.
  7021. if queue_status == "aborted":
  7022. queue_status = "cancelled"
  7023. item.status = queue_status
  7024. item.completed_at = datetime.now(timezone.utc)
  7025. if queue_status == "failed" and not item.error_message:
  7026. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  7027. # Bump usage counters on the source library file so admins can
  7028. # sort by "last printed" and (eventually) auto-purge stale
  7029. # files — #1008.
  7030. await _bump_library_file_usage_if_completed(db, item, queue_status)
  7031. await db.commit()
  7032. queue_item_id = item.id
  7033. billing_run_id = item.billing_run_id
  7034. billing_user_id = item.created_by_id
  7035. billing_cost_center_id = item.cost_center_id
  7036. billing_plate_id = item.plate_id
  7037. queue_auto_off = item.auto_off_after
  7038. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  7039. await run_with_retry(_update_queue_status, label="queue status update")
  7040. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  7041. # their own sessions and have their own error handling — no retry needed.
  7042. if queue_item_id is not None:
  7043. # Batch orders (#342): this run may have been the last one an order
  7044. # owed. Re-evaluate here rather than lazily on read, so a finished
  7045. # order reports itself complete without someone opening the page.
  7046. try:
  7047. from backend.app.services.print_batch import refresh_batch_status_for_item
  7048. async with async_session() as db:
  7049. await refresh_batch_status_for_item(db, queue_item_id)
  7050. await db.commit()
  7051. except Exception as e:
  7052. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  7053. # MQTT relay - publish queue job completed
  7054. try:
  7055. printer_info = printer_manager.get_printer(printer_id)
  7056. await mqtt_relay.on_queue_job_completed(
  7057. job_id=queue_item_id,
  7058. filename=filename or subtask_name,
  7059. printer_id=printer_id,
  7060. printer_name=printer_info.name if printer_info else "Unknown",
  7061. status=queue_status,
  7062. )
  7063. except Exception:
  7064. pass # Don't fail if MQTT fails
  7065. # Check if queue is now empty and send notification
  7066. try:
  7067. from sqlalchemy import func as sa_func
  7068. async with async_session() as db:
  7069. count_result = await db.execute(
  7070. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  7071. )
  7072. pending_count = count_result.scalar() or 0
  7073. if pending_count == 0:
  7074. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  7075. completed_result = await db.execute(
  7076. select(sa_func.count(PrintQueueItem.id)).where(
  7077. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  7078. PrintQueueItem.completed_at >= today_start,
  7079. )
  7080. )
  7081. completed_count = completed_result.scalar() or 1
  7082. await notification_service.on_queue_completed(
  7083. completed_count=completed_count,
  7084. db=db,
  7085. )
  7086. except Exception:
  7087. pass # Don't fail if notification fails
  7088. # Handle auto_off_after - power off printer if the queue item opted
  7089. # in. Delegates to the smart-plug manager so the off honours each
  7090. # plug's configured strategy (time delay or temperature threshold),
  7091. # is cancelled if the printer starts printing again, and never cuts
  7092. # power on a loaded print (#1890). Previously an inline block here
  7093. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  7094. # timeout regardless of print state — cutting a touchscreen reprint.
  7095. if queue_auto_off:
  7096. try:
  7097. async with async_session() as db:
  7098. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  7099. except Exception as e:
  7100. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  7101. except Exception as e:
  7102. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  7103. log_timing("Queue item update")
  7104. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  7105. # Must run before archive_id early-return so it fires for all prints (including
  7106. # prints started from BambuStudio/touchscreen that have no archive).
  7107. if data.get("status") == "completed":
  7108. try:
  7109. from backend.app.api.routes.settings import get_setting
  7110. async with async_session() as db:
  7111. threshold_str = await get_setting(db, "bed_cooled_threshold")
  7112. threshold = float(threshold_str) if threshold_str else 35.0
  7113. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  7114. async with async_session() as db:
  7115. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  7116. if providers:
  7117. _bed_cool_waiters[printer_id] = {
  7118. "threshold": threshold,
  7119. "filename": filename or subtask_name or "",
  7120. "registered_at": time.time(),
  7121. }
  7122. logger.info(
  7123. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  7124. printer_id,
  7125. threshold,
  7126. )
  7127. else:
  7128. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  7129. except Exception as e:
  7130. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  7131. # Capture the slicer estimate before usage tracking runs. The tracker may
  7132. # update archive.cost with this run's measured cost; billing partial runs
  7133. # against that already-partial value would discount the charge twice.
  7134. billing_planned_grams: float | None = None
  7135. billing_base_cost: float | None = None
  7136. if archive_id:
  7137. try:
  7138. async with async_session() as db:
  7139. from backend.app.models.archive import PrintArchive
  7140. billing_archive = await db.get(PrintArchive, archive_id)
  7141. if billing_archive:
  7142. billing_path = (
  7143. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  7144. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7145. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  7146. billing_archive,
  7147. billing_path,
  7148. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  7149. )
  7150. except Exception as e:
  7151. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  7152. # --- Track filament consumption (must run before archive_id early-return so usage
  7153. # is recorded even when auto-archive is disabled) ---
  7154. usage_results: list[dict] = []
  7155. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  7156. stored_ams_mapping = data.get("ams_mapping")
  7157. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  7158. if not stored_ams_mapping and archive_id:
  7159. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  7160. # Always drain the plate_id register on completion — the session already
  7161. # consumed it at print-start injection; leaving it would leak into the next
  7162. # print on the same archive_id (rare but possible with reprints) (#1697).
  7163. # Capture the popped value so the completion notification can scope the
  7164. # archive-level (summed-across-plates per #1593) filament + time totals
  7165. # down to the single plate that was actually printed (#1785).
  7166. notify_plate_id: int | None = None
  7167. if archive_id:
  7168. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  7169. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  7170. try:
  7171. async with async_session() as db:
  7172. from backend.app.api.routes.settings import get_setting
  7173. _spoolman_on = await get_setting(db, "spoolman_enabled")
  7174. if not _spoolman_on or _spoolman_on.lower() != "true":
  7175. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  7176. async with async_session() as db:
  7177. usage_results = await usage_on_print_complete(
  7178. printer_id,
  7179. data,
  7180. printer_manager,
  7181. db,
  7182. archive_id=archive_id,
  7183. ams_mapping=stored_ams_mapping,
  7184. )
  7185. if usage_results:
  7186. await ws_manager.broadcast(
  7187. {
  7188. "type": "spool_usage_logged",
  7189. "printer_id": printer_id,
  7190. "usage": usage_results,
  7191. }
  7192. )
  7193. log_timing("Usage tracker")
  7194. except Exception as e:
  7195. logger.warning("Usage tracker on_print_complete failed: %s", e)
  7196. # Drop the print-start context unconditionally — the Spoolman branch above
  7197. # skips the internal tracker entirely, so nothing else would clear what
  7198. # print start captured, and a row surviving its print would be restored
  7199. # onto the next one after a restart.
  7200. try:
  7201. from backend.app.services.usage_tracker import discard_session
  7202. async with async_session() as db:
  7203. await discard_session(db, printer_id)
  7204. except Exception as e:
  7205. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  7206. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  7207. if archive_id:
  7208. if data.get("status") == "completed":
  7209. try:
  7210. await _report_spoolman_usage(printer_id, archive_id)
  7211. log_timing("Spoolman usage report")
  7212. except Exception as e:
  7213. logger.warning("Spoolman usage reporting failed: %s", e)
  7214. else:
  7215. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  7216. try:
  7217. async with async_session() as db:
  7218. await _cleanup_spoolman_tracking(
  7219. printer_id,
  7220. archive_id,
  7221. db,
  7222. last_layer_num=data.get("last_layer_num"),
  7223. last_progress=data.get("last_progress"),
  7224. )
  7225. except Exception as e:
  7226. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  7227. log_timing("Filament usage tracking")
  7228. if not archive_id:
  7229. # The printer's own calibration run has no archive by design, so this
  7230. # arrives here every time one finishes. Returning before the no-archive
  7231. # notification keeps a calibration from being announced as a finished
  7232. # print. Everything above this point has already run — the plate-clear
  7233. # gate, the queue reconciliation, the SD-card cleanup — so only the
  7234. # notification is skipped.
  7235. if is_internal_printer_job(filename, subtask_name):
  7236. logger.info(
  7237. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  7238. filename,
  7239. subtask_name,
  7240. )
  7241. return
  7242. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  7243. # Still send print-complete/failed/stopped notifications even without an archive.
  7244. # Try to enrich with queue/library-file data so user-specific emails work too.
  7245. async def _notify_no_archive():
  7246. try:
  7247. async with async_session() as db:
  7248. from backend.app.models.library import LibraryFile
  7249. from backend.app.models.print_queue import PrintQueueItem
  7250. from backend.app.models.printer import Printer
  7251. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7252. printer_obj = result.scalar_one_or_none()
  7253. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  7254. # Only the queue item this completion itself closed (the
  7255. # reconciliation above, which checks the run belongs to it).
  7256. # A print started outside Bambuddy closed none, and must not
  7257. # borrow an earlier job's owner, email or times.
  7258. no_archive_data: dict | None = None
  7259. try:
  7260. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  7261. if queue_item:
  7262. no_archive_data = {"created_by_id": queue_item.created_by_id}
  7263. # How long it really ran, as the archive path reports it (#1198).
  7264. started = to_naive_utc(queue_item.started_at)
  7265. ended = to_naive_utc(queue_item.completed_at)
  7266. if started and ended and (ended - started).total_seconds() > 0:
  7267. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  7268. # Estimated time: the queue item caches it from its
  7269. # archive or library file; otherwise read the library
  7270. # file's metadata (LibraryFile has no column for it).
  7271. if queue_item.print_time_seconds:
  7272. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  7273. elif queue_item.library_file_id:
  7274. lib_result = await db.execute(
  7275. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  7276. )
  7277. lib_file = lib_result.scalar_one_or_none()
  7278. estimate = (
  7279. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  7280. )
  7281. if estimate:
  7282. no_archive_data["print_time_seconds"] = estimate
  7283. except Exception as lookup_err:
  7284. logger.debug(
  7285. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  7286. )
  7287. # Enrich with usage tracker results (captured in enclosing scope)
  7288. if usage_results:
  7289. if no_archive_data is None:
  7290. no_archive_data = {}
  7291. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7292. if total_from_usage > 0:
  7293. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7294. no_archive_data["usage_results"] = usage_results
  7295. # Try MQTT remaining_time for print duration when no queue/library data
  7296. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  7297. mqtt_remaining = data.get("remaining_time")
  7298. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  7299. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  7300. ps = data.get("status", "completed")
  7301. logger.info(
  7302. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  7303. )
  7304. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7305. await notification_service.on_print_complete(
  7306. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  7307. )
  7308. else:
  7309. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7310. # Send user-specific email if we have a created_by_id
  7311. if no_archive_data and no_archive_data.get("created_by_id"):
  7312. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7313. await _dispatch_user_print_email(
  7314. ps,
  7315. no_archive_data["created_by_id"],
  7316. p_name,
  7317. raw_filename,
  7318. db,
  7319. )
  7320. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  7321. except Exception as e:
  7322. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  7323. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  7324. return
  7325. log_timing("Archive lookup")
  7326. # Update archive status
  7327. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  7328. try:
  7329. async with async_session() as db:
  7330. service = ArchiveService(db)
  7331. status = data.get("status", "completed")
  7332. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  7333. if hms_errors:
  7334. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  7335. failure_reason = derive_failure_reason(status, hms_errors)
  7336. if data.get("_reconciled"):
  7337. # A reconciled completion closes out a stale archive at
  7338. # reconnect — it is not a user action, so don't mislabel it
  7339. # "userCancelled". It shares the stale-cleanup path's key
  7340. # (issue #2974) and records that the real end time is unknown,
  7341. # which is also why its logged duration is 0 (#2592).
  7342. failure_reason = "noStatusUpdate"
  7343. if failure_reason:
  7344. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  7345. elif status == "failed" and hms_errors:
  7346. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  7347. await service.update_archive_status(
  7348. archive_id,
  7349. status=status,
  7350. completed_at=(
  7351. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  7352. ),
  7353. failure_reason=failure_reason,
  7354. )
  7355. logger.info(
  7356. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  7357. )
  7358. await ws_manager.send_archive_updated(
  7359. {
  7360. "id": archive_id,
  7361. "status": status,
  7362. }
  7363. )
  7364. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  7365. # MQTT relay - publish archive updated
  7366. try:
  7367. await mqtt_relay.on_archive_updated(
  7368. archive_id=archive_id,
  7369. print_name=filename or subtask_name,
  7370. status=status,
  7371. )
  7372. except Exception:
  7373. pass # Don't fail if MQTT fails
  7374. except Exception as e:
  7375. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  7376. # Continue with other operations even if archive update fails
  7377. log_timing("Archive status update")
  7378. # Apply finance wallet charge or release reservations once. For all partial
  7379. # terminal states (failed, aborted at the printer display, or cancelled via
  7380. # Bambuddy) use this run's measured spool delta, falling back to the last
  7381. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  7382. # estimate and therefore cannot represent an interrupted run.
  7383. try:
  7384. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  7385. async with async_session() as db:
  7386. from backend.app.models.archive import PrintArchive
  7387. from backend.app.services.finance_billing import apply_print_charge_for_archive
  7388. archive = await db.get(PrintArchive, archive_id)
  7389. if archive and billing_run_id is None:
  7390. billing_run_id = getattr(archive, "billing_run_id", None)
  7391. if archive and archive.created_by_id is None and _print_user_info:
  7392. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  7393. await db.flush()
  7394. run_status = data.get("status", "completed")
  7395. last_progress = data.get("last_progress")
  7396. if last_progress is None:
  7397. last_progress = data.get("progress")
  7398. actual_run_grams = _compute_run_filament_grams(
  7399. run_status,
  7400. billing_planned_grams,
  7401. last_progress,
  7402. usage_results,
  7403. )
  7404. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  7405. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  7406. charged = await apply_print_charge_for_archive(
  7407. db,
  7408. archive_id,
  7409. charged_user_id=billing_user_id,
  7410. cost_center_id=(
  7411. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  7412. ),
  7413. print_queue_id=queue_item_id,
  7414. print_run_id=billing_run_id,
  7415. base_cost_override=billing_base_cost,
  7416. filament_usage=filament_usage,
  7417. )
  7418. await db.commit()
  7419. if charged:
  7420. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  7421. except Exception as e:
  7422. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  7423. printer_info = printer_manager.get_printer(printer_id)
  7424. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7425. billing_filename = filename or subtask_name or "Unknown"
  7426. billing_error = str(e)
  7427. try:
  7428. await ws_manager.broadcast(
  7429. {
  7430. "type": "billing_charge_failed",
  7431. "printer_id": printer_id,
  7432. "printer_name": billing_printer_name,
  7433. "filename": billing_filename,
  7434. "archive_id": archive_id,
  7435. }
  7436. )
  7437. except Exception as notification_error:
  7438. logger.error(
  7439. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  7440. archive_id,
  7441. notification_error,
  7442. )
  7443. async def _notify_billing_charge_failed() -> None:
  7444. try:
  7445. async with async_session() as notification_db:
  7446. await notification_service.on_billing_charge_failed(
  7447. printer_id,
  7448. billing_printer_name,
  7449. billing_filename,
  7450. archive_id,
  7451. billing_error,
  7452. notification_db,
  7453. )
  7454. except Exception as provider_error:
  7455. logger.error(
  7456. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  7457. archive_id,
  7458. provider_error,
  7459. exc_info=True,
  7460. )
  7461. spawn_background_task(
  7462. _notify_billing_charge_failed(),
  7463. name=f"billing-charge-failed-{archive_id}",
  7464. )
  7465. log_timing("Finance charge update")
  7466. # Write independent print log entry (separate table, never touches archives)
  7467. try:
  7468. async with async_session() as db:
  7469. from backend.app.models.archive import PrintArchive
  7470. from backend.app.services.print_log import record_archive_wear, write_log_entry
  7471. archive = await db.get(PrintArchive, archive_id)
  7472. if archive:
  7473. # Back-fill created_by_id on reprint (#730): reprint reuses the
  7474. # source archive row rather than creating a new one, so an
  7475. # archive that was auto-created from a printer-initiated
  7476. # print (created_by_id=NULL) would otherwise stay unattributed
  7477. # forever. When we have a print-session user AND the archive
  7478. # has no attribution yet, credit the current user. Never
  7479. # overwrite an existing attribution — the original uploader
  7480. # keeps ownership.
  7481. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  7482. if archive.created_by_id is None and _print_user_id is not None:
  7483. archive.created_by_id = _print_user_id
  7484. p_info = printer_manager.get_printer(printer_id)
  7485. # Per-run actuals — written to PrintLogEntry so stats reflect
  7486. # what THIS print actually used, not the source archive's
  7487. # first-run values (#1378). Helper handles the partial-print
  7488. # math (failed / cancelled / stopped get scaled to progress
  7489. # or to tracked spool deltas).
  7490. _run_status = data.get("status", "completed")
  7491. # #2614: scope the per-run estimate to the printed plate. For a
  7492. # multi-plate 3MF dispatched one plate at a time, the archive's
  7493. # filament/cost are the whole-file totals; the PrintLogEntry must
  7494. # reflect only this plate. No effect on single-plate archives (the
  7495. # plate estimate equals the whole-file value) or on the tracker
  7496. # path (measured spool deltas win in _compute_run_filament_grams).
  7497. _est_full_path = (
  7498. app_settings.base_dir / archive.file_path if archive.file_path else None
  7499. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7500. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path)
  7501. _run_grams = _compute_run_filament_grams(
  7502. _run_status,
  7503. _est_grams,
  7504. data.get("last_progress", data.get("progress")),
  7505. usage_results,
  7506. )
  7507. # Per-run cost — prefer usage_results sum. For partial prints
  7508. # we deliberately skip the topup-to-estimate logic in
  7509. # usage_tracker (which assumes the print completed); the raw
  7510. # tracked-spool sum is closer to what THIS run actually cost.
  7511. _run_cost: float | None = None
  7512. if usage_results:
  7513. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  7514. if _run_cost is None and _run_status == "completed":
  7515. _run_cost = _est_cost
  7516. from backend.app.models.printer import Printer as _Printer
  7517. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  7518. run_entry = await write_log_entry(
  7519. db,
  7520. archive_id=archive.id,
  7521. # Captured by _update_queue_status above; None for
  7522. # printer-initiated prints with no queue row. Batch
  7523. # cost/energy roll-up joins on it (#342).
  7524. queue_item_id=queue_item_id,
  7525. status=_run_status,
  7526. print_name=archive.print_name,
  7527. printer_name=p_info.name if p_info else None,
  7528. printer_id=printer_id,
  7529. started_at=archive.started_at,
  7530. completed_at=archive.completed_at,
  7531. filament_type=archive.filament_type,
  7532. filament_color=archive.filament_color,
  7533. filament_used_grams=_run_grams,
  7534. cost=_run_cost,
  7535. wear_cost_per_hour=_wear_rate,
  7536. failure_reason=archive.failure_reason,
  7537. thumbnail_path=archive.thumbnail_path,
  7538. created_by_id=archive.created_by_id,
  7539. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  7540. # Reconciled completions have an unknown real end time —
  7541. # log 0 duration instead of the whole disconnect gap (#2592).
  7542. reconciled=bool(data.get("_reconciled")),
  7543. )
  7544. await record_archive_wear(db, archive, run_entry)
  7545. await db.commit()
  7546. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  7547. except Exception as e:
  7548. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  7549. log_timing("Print log entry")
  7550. # Run slow operations as background tasks to avoid blocking the event loop
  7551. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  7552. async def _background_energy_calculation():
  7553. """Calculate and save energy usage in background.
  7554. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  7555. backend restart no longer loses per-print energy data).
  7556. """
  7557. try:
  7558. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  7559. async with async_session() as db:
  7560. from backend.app.models.archive import PrintArchive
  7561. archive = await db.get(PrintArchive, archive_id)
  7562. if archive is None:
  7563. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  7564. return
  7565. starting_kwh = archive.energy_start_kwh
  7566. if starting_kwh is None:
  7567. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  7568. return
  7569. candidates = await energy_plug_candidates(db, printer_id)
  7570. if not candidates:
  7571. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  7572. return
  7573. # Same ordering as the start reading, so the delta below is
  7574. # against the counter that produced `starting_kwh` (#2859).
  7575. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  7576. if selected is None:
  7577. logger.warning(
  7578. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  7579. printer_id,
  7580. ", ".join(plug.name for plug in candidates),
  7581. )
  7582. return
  7583. plug, energy = selected
  7584. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  7585. energy_used = round(energy["total"] - starting_kwh, 4)
  7586. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  7587. if energy_used < 0:
  7588. logger.warning(
  7589. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  7590. archive_id,
  7591. starting_kwh,
  7592. energy["total"],
  7593. )
  7594. return
  7595. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  7596. # Each hour of the print at the price of that hour (#1251). If
  7597. # that fails, the last price known, as before, rather than no
  7598. # energy at all. Read first: the session may be unusable after.
  7599. last_price = await stored_price(db)
  7600. try:
  7601. energy_cost_value = round(
  7602. await print_energy_cost(
  7603. db,
  7604. plug_id=archive.energy_start_plug_id,
  7605. start_at=archive.energy_start_at,
  7606. start_kwh=starting_kwh,
  7607. start_price=archive.energy_start_price,
  7608. end_kwh=energy["total"],
  7609. end_plug_id=plug.id,
  7610. price_now=await current_price(db),
  7611. ),
  7612. 3,
  7613. )
  7614. except Exception as e:
  7615. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  7616. energy_cost_value = round(energy_used * last_price, 3)
  7617. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  7618. # reprint doesn't visually clobber the source archive's energy data
  7619. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  7620. from sqlalchemy import func
  7621. from backend.app.models.print_log import PrintLogEntry
  7622. existing_runs = await db.scalar(
  7623. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  7624. )
  7625. if (existing_runs or 0) <= 1:
  7626. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  7627. # we just wrote for THIS print. Either way it's the first run.
  7628. archive.energy_kwh = energy_used
  7629. archive.energy_cost = energy_cost_value
  7630. # Backfill the latest PrintLogEntry for this archive with energy
  7631. # (write_log_entry above ran before this background task completed,
  7632. # so energy fields are still NULL on that row).
  7633. latest_run = await db.execute(
  7634. select(PrintLogEntry)
  7635. .where(PrintLogEntry.archive_id == archive_id)
  7636. .order_by(PrintLogEntry.id.desc())
  7637. .limit(1)
  7638. )
  7639. run_row = latest_run.scalar_one_or_none()
  7640. if run_row is not None:
  7641. run_row.energy_kwh = energy_used
  7642. run_row.energy_cost = energy_cost_value
  7643. await db.commit()
  7644. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  7645. except Exception as e:
  7646. logger.warning("[ENERGY-BG] Failed: %s", e)
  7647. async def _background_finish_photo() -> str | None:
  7648. """Capture finish photo in background. Returns photo filename if captured."""
  7649. # #2547: set once this function has raised the plate itself (the
  7650. # timelapse path, where the moment producer returned without doing it).
  7651. # Declared out here so the `finally` can lower it again no matter where
  7652. # the capture below fails.
  7653. plate_restored_z: float | None = None
  7654. try:
  7655. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  7656. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  7657. # Read phase: settings + printer + archive in a short session, released
  7658. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  7659. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  7660. # tens of seconds; holding this session across it pinned one pooled
  7661. # connection idle-in-transaction per finishing print (issue #2572).
  7662. async with async_session() as db:
  7663. from backend.app.api.routes.settings import get_setting
  7664. from backend.app.models.archive import PrintArchive
  7665. from backend.app.models.printer import Printer
  7666. capture_enabled = await get_setting(db, "capture_finish_photo")
  7667. if capture_enabled is not None and capture_enabled.lower() != "true":
  7668. return None
  7669. if not archive_id:
  7670. return None
  7671. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  7672. archive = (
  7673. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7674. ).scalar_one_or_none()
  7675. if not printer or not archive:
  7676. return None
  7677. import uuid
  7678. from datetime import datetime
  7679. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  7680. if not archive.file_path:
  7681. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  7682. archive_dir = resolve_archive_dir(archive)
  7683. photo_filename = None
  7684. # Prefer the timelapse last-frame source when a timelapse was
  7685. # recording — it captures the moment after the toolhead parks
  7686. # but before the bed drops, which the live-camera grab below
  7687. # would miss (#1397). Skipped for external cameras (those have
  7688. # their own framing and don't see a Bambu timelapse). Only
  7689. # runs when the USER explicitly enabled timelapse for this
  7690. # print — #1721 removed Bambuddy's force-on at dispatch
  7691. # because it caused per-layer nozzle parking on Smooth-mode
  7692. # slicer profiles.
  7693. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  7694. printer.external_camera_enabled and printer.external_camera_url
  7695. )
  7696. timelapse_still_pending = False
  7697. if prefer_timelapse_source:
  7698. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  7699. archive_id=archive_id,
  7700. archive_dir=archive_dir,
  7701. rotation=getattr(printer, "camera_rotation", 0),
  7702. )
  7703. # #1721: replacement framing path — on_finish_photo_moment
  7704. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  7705. # parked, bed not yet dropped) and cached the JPEG bytes in
  7706. # _stage22_finish_frames. Consume them now so the saved photo
  7707. # has the better framing instead of the post-bed-drop angle
  7708. # the live-camera fallback below would give.
  7709. if not photo_filename:
  7710. # #1790: on the FINISH-state fallback path the producer
  7711. # task is dispatched back-to-back with this consumer, so
  7712. # a bare pop would race past with an empty result and
  7713. # the RTSP fallback below would collide with the
  7714. # producer's still-in-flight grab (single-client RTSP
  7715. # on Bambu printers). Wait for the producer to finish
  7716. # or give up before touching the cache.
  7717. #
  7718. # #2547: 20s was enough when the producer only ever grabbed a
  7719. # frame. It now also raises the plate first, which costs the
  7720. # settle window before the grab even starts — so the budget has
  7721. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  7722. # under the notification's own photo wait below.
  7723. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  7724. if in_flight is not None:
  7725. try:
  7726. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  7727. except TimeoutError:
  7728. logger.warning(
  7729. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  7730. printer_id,
  7731. )
  7732. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  7733. if cached_frame:
  7734. # Already rotated by the producer (#2708) — rotating again
  7735. # here would undo the fix on the banked-frame path, whose
  7736. # bytes reach the cache having been rotated once already.
  7737. photos_dir = archive_dir / "photos"
  7738. photos_dir.mkdir(parents=True, exist_ok=True)
  7739. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7740. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7741. photo_path = photos_dir / photo_filename
  7742. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  7743. logger.info(
  7744. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  7745. photo_filename,
  7746. len(cached_frame),
  7747. )
  7748. # #2547: the timelapse path reaches the live grab below whenever the
  7749. # video hasn't landed in time — the documented usual outcome on
  7750. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  7751. # returned early for those prints without raising the plate, so
  7752. # without this the photo that actually ships in the notification is
  7753. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  7754. # asked us to fix. The archive still gets the better video frame
  7755. # later; this is about the image the user is sent.
  7756. #
  7757. # Gated on `timelapse_was_active` precisely because that is the
  7758. # condition under which the producer skipped. On every other path it
  7759. # has already raised and lowered the plate, and repeating that here
  7760. # would be a second pointless round trip.
  7761. if (
  7762. not photo_filename
  7763. and data.get("timelapse_was_active")
  7764. and not print_dispatch_context.end_gcode_injected(printer_id)
  7765. ):
  7766. try:
  7767. async with async_session() as db:
  7768. from backend.app.api.routes.settings import get_setting
  7769. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7770. if restore_setting is None or restore_setting.lower() == "true":
  7771. max_z = await _max_z_for_current_print(
  7772. printer_id, data, logger, bound_archive_id, notify_plate_id
  7773. )
  7774. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  7775. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  7776. plate_restored_z = max_z
  7777. except Exception as e:
  7778. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  7779. # Fallback chain: external camera → buffered live frame →
  7780. # fresh RTSP capture. Only runs if the timelapse path above
  7781. # didn't already produce a photo.
  7782. # Chamber light for the live capture below (#1655).
  7783. async with camera_light(printer if not photo_filename else None):
  7784. if not photo_filename:
  7785. if printer.external_camera_enabled and printer.external_camera_url:
  7786. logger.info("[PHOTO-BG] Using external camera")
  7787. from backend.app.api.routes.camera import live_frame_for_capture
  7788. from backend.app.services.external_camera import capture_frame
  7789. # #2707: the second half of the finish-photo failure — the
  7790. # pre-capture and this fallback both collided with the live
  7791. # view. None here continues down the fallback chain.
  7792. defer, buffered = live_frame_for_capture(printer_id)
  7793. if defer:
  7794. frame_data = buffered
  7795. else:
  7796. frame_data = await capture_frame(
  7797. printer.external_camera_url,
  7798. printer.external_camera_type or "mjpeg",
  7799. snapshot_url=printer.external_camera_snapshot_url,
  7800. )
  7801. if frame_data:
  7802. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  7803. photos_dir = archive_dir / "photos"
  7804. photos_dir.mkdir(parents=True, exist_ok=True)
  7805. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7806. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7807. photo_path = photos_dir / photo_filename
  7808. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  7809. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  7810. else:
  7811. # Check if camera stream is active - use buffered frame to avoid freeze
  7812. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  7813. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  7814. active_chamber_for_printer = [
  7815. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  7816. ]
  7817. buffered_frame = get_buffered_frame(printer_id)
  7818. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  7819. # Use frame from active stream
  7820. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  7821. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  7822. photos_dir = archive_dir / "photos"
  7823. photos_dir.mkdir(parents=True, exist_ok=True)
  7824. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7825. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7826. photo_path = photos_dir / photo_filename
  7827. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  7828. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  7829. else:
  7830. # No active stream - capture new frame
  7831. from backend.app.services.camera import capture_finish_photo
  7832. photo_filename = await capture_finish_photo(
  7833. printer_id=printer_id,
  7834. ip_address=printer.ip_address,
  7835. access_code=printer.access_code,
  7836. model=printer.model,
  7837. archive_dir=archive_dir,
  7838. rotation=getattr(printer, "camera_rotation", 0),
  7839. )
  7840. # Write phase: attach the photo in a fresh short-lived session.
  7841. if photo_filename:
  7842. async with async_session() as db:
  7843. from backend.app.models.archive import PrintArchive
  7844. arch = await db.get(PrintArchive, archive_id)
  7845. if arch is not None:
  7846. photos = arch.photos or []
  7847. photos.append(photo_filename)
  7848. arch.photos = photos
  7849. await db.commit()
  7850. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  7851. # The short wait above is bounded so a slow printer can't hold up
  7852. # the print-complete notification, which is what the caller is
  7853. # blocking on. When it ran out with the video still on its way,
  7854. # keep waiting off to the side and add the better frame to the
  7855. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  7856. # users, whose videos routinely take minutes to transfer, never get
  7857. # the pre-bed-drop framing this path exists to provide.
  7858. #
  7859. # Spawned here rather than at the point the wait gave up: both this
  7860. # function and the upgrade do a read-modify-write on `photos`, and
  7861. # the live-camera fallback above can take tens of seconds. Starting
  7862. # the upgrade before that write means the two can interleave and one
  7863. # silently drops the other's entry, leaving a JPEG on disk that the
  7864. # gallery never lists.
  7865. if timelapse_still_pending:
  7866. spawn_background_task(
  7867. _upgrade_finish_photo_from_timelapse(
  7868. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  7869. ),
  7870. name=f"finish-photo-upgrade-{archive_id}",
  7871. )
  7872. return photo_filename
  7873. except Exception as e:
  7874. logger.warning("[PHOTO-BG] Failed: %s", e)
  7875. return None
  7876. finally:
  7877. # #2547: we raised the plate, so we owe the move back down — even if
  7878. # the capture in between threw. Otherwise the user finds the print
  7879. # pinned under the nozzle.
  7880. if plate_restored_z is not None:
  7881. try:
  7882. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  7883. except Exception as e:
  7884. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7885. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  7886. # Photo capture task - result will be used by notifications
  7887. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  7888. log_timing("Background tasks scheduled (energy, photo)")
  7889. # Also run smart plug, notifications, and maintenance as background tasks
  7890. print_status = data.get("status", "completed")
  7891. async def _background_smart_plug():
  7892. """Handle smart plug automation in background."""
  7893. try:
  7894. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  7895. async with async_session() as db:
  7896. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  7897. logger.info("[AUTO-OFF-BG] Completed")
  7898. except Exception as e:
  7899. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  7900. async def _background_notifications(finish_photo_filename: str | None = None):
  7901. """Send print complete notifications in background."""
  7902. try:
  7903. logger.info(
  7904. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  7905. )
  7906. async with async_session() as db:
  7907. from backend.app.models.archive import PrintArchive
  7908. from backend.app.models.printer import Printer
  7909. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7910. printer = result.scalar_one_or_none()
  7911. printer_name = printer.name if printer else f"Printer {printer_id}"
  7912. archive_data = None
  7913. if archive_id:
  7914. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7915. archive = archive_result.scalar_one_or_none()
  7916. if archive:
  7917. # Actual elapsed time from started_at/completed_at when both are
  7918. # populated (every terminal status sets completed_at after #1198).
  7919. # Falls back to None so the notification path can decide whether to
  7920. # render the slicer estimate as a last resort.
  7921. actual_time_seconds = None
  7922. if archive.started_at and archive.completed_at:
  7923. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  7924. if elapsed > 0:
  7925. actual_time_seconds = int(elapsed)
  7926. archive_data = {
  7927. "print_time_seconds": archive.print_time_seconds,
  7928. "actual_time_seconds": actual_time_seconds,
  7929. "actual_filament_grams": archive.filament_used_grams,
  7930. "failure_reason": archive.failure_reason,
  7931. "created_by_id": archive.created_by_id,
  7932. }
  7933. # Scale filament usage for partial prints
  7934. if print_status != "completed" and archive.filament_used_grams:
  7935. progress = data.get("progress") or 0
  7936. scale = _partial_progress_scale(progress)
  7937. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  7938. archive_data["progress"] = progress
  7939. # Pass per-slot data from archive.extra_data
  7940. if archive.extra_data and archive.extra_data.get("filament_slots"):
  7941. slots = archive.extra_data["filament_slots"]
  7942. if print_status != "completed":
  7943. scale = _partial_progress_scale(data.get("progress"))
  7944. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  7945. archive_data["filament_slots"] = slots
  7946. # Scope project-summed totals down to the plate that was
  7947. # actually printed — see _scope_notification_archive_data_to_plate
  7948. # for the why (#1785).
  7949. archive_data = _scope_notification_archive_data_to_plate(
  7950. archive_data,
  7951. archive.file_path,
  7952. notify_plate_id,
  7953. print_status,
  7954. data.get("progress"),
  7955. app_settings.base_dir,
  7956. )
  7957. # Enrich filament_grams from usage_results when archive has no 3MF data
  7958. if not archive_data.get("actual_filament_grams") and usage_results:
  7959. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7960. if total_from_usage > 0:
  7961. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7962. # Pass usage tracker results for AMS slot info in notifications
  7963. if usage_results:
  7964. archive_data["usage_results"] = usage_results
  7965. # Add finish photo URL and image bytes if available
  7966. if finish_photo_filename:
  7967. photo_url, photo_bytes = await _finish_photo_for_notification(
  7968. db, archive, archive_id, finish_photo_filename
  7969. )
  7970. if photo_url:
  7971. archive_data["finish_photo_url"] = photo_url
  7972. if photo_bytes:
  7973. archive_data["image_data"] = photo_bytes
  7974. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7975. await notification_service.on_print_complete(
  7976. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  7977. )
  7978. else:
  7979. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7980. # Post-print outcome confirmation (#1898). Runs in this
  7981. # background task so the finish photo fetched above rides
  7982. # along with the prompt.
  7983. if print_status == "completed" and archive_id:
  7984. await _dispatch_outcome_confirmation_safely(
  7985. db, printer_id, printer_name, data, archive_id, archive_data
  7986. )
  7987. # Send user-specific email notification
  7988. if archive_data:
  7989. created_by_id = archive_data.get("created_by_id")
  7990. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7991. await _dispatch_user_print_email(
  7992. print_status,
  7993. created_by_id,
  7994. printer_name,
  7995. raw_filename,
  7996. db,
  7997. image_data=archive_data.get("image_data"),
  7998. finish_photo_url=archive_data.get("finish_photo_url"),
  7999. )
  8000. logger.info("[NOTIFY-BG] Completed")
  8001. except Exception as e:
  8002. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  8003. async def _background_maintenance_check():
  8004. """Check for maintenance due in background."""
  8005. if print_status != "completed":
  8006. return
  8007. try:
  8008. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  8009. async with async_session() as db:
  8010. from backend.app.models.printer import Printer
  8011. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8012. printer = result.scalar_one_or_none()
  8013. printer_name = printer.name if printer else f"Printer {printer_id}"
  8014. await ensure_default_types(db)
  8015. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  8016. attention = [
  8017. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  8018. ]
  8019. items_needing_attention = [
  8020. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  8021. for item in attention
  8022. ]
  8023. if items_needing_attention:
  8024. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  8025. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  8026. # MQTT relay - publish maintenance alerts
  8027. for item in attention:
  8028. current_value, threshold, unit = maintenance_alert_values(item)
  8029. try:
  8030. await mqtt_relay.on_maintenance_alert(
  8031. printer_id=printer_id,
  8032. printer_name=printer_name,
  8033. maintenance_type=item.maintenance_type_name,
  8034. current_value=current_value,
  8035. threshold=threshold,
  8036. unit=unit,
  8037. )
  8038. except Exception:
  8039. pass # Don't fail if MQTT fails
  8040. else:
  8041. logger.info("[MAINT-BG] Completed (no items need attention)")
  8042. except Exception as e:
  8043. logger.warning("[MAINT-BG] Failed: %s", e)
  8044. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  8045. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  8046. # Notification task waits for photo capture to complete first (with timeout).
  8047. # When a timelapse was recording, photo sourcing polls the per-print
  8048. # timelapse for up to 60s (#1397) — extend the budget so the notification
  8049. # carries the correct bed-up photo instead of falling through to the
  8050. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  8051. #
  8052. # #2547: both budgets now have to cover a plate restore as well.
  8053. #
  8054. # Without timelapse, the wait is on the moment producer, which raises the
  8055. # plate before its grab — so this has to outlast that producer's own budget.
  8056. #
  8057. # With timelapse, the capture polls up to
  8058. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  8059. # falls back to a live grab, which is the case that raises the plate. At the
  8060. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  8061. # restore would have moved the plate for a photo nobody waited for.
  8062. photo_wait_timeout = (
  8063. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  8064. if data.get("timelapse_was_active")
  8065. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  8066. )
  8067. async def _photo_then_notify():
  8068. """Wait for photo capture, then send notification with photo URL."""
  8069. finish_photo = None
  8070. try:
  8071. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  8072. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  8073. except TimeoutError:
  8074. logger.warning(
  8075. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  8076. photo_wait_timeout,
  8077. )
  8078. except Exception as e:
  8079. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  8080. try:
  8081. await _background_notifications(finish_photo)
  8082. except Exception as e:
  8083. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  8084. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  8085. # Stitch external camera layer timelapse if session was active
  8086. print_status = data.get("status", "completed")
  8087. async def _background_layer_timelapse():
  8088. """Stitch layer timelapse and attach to archive."""
  8089. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  8090. try:
  8091. if print_status == "completed":
  8092. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  8093. timelapse_path = await tl_complete(printer_id)
  8094. if timelapse_path and archive_id:
  8095. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  8096. async with async_session() as db:
  8097. service = ArchiveService(db)
  8098. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  8099. await service.attach_timelapse(
  8100. archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=notify_plate_id
  8101. )
  8102. # Clean up the temp file
  8103. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  8104. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  8105. elif timelapse_path:
  8106. # Timelapse created but no archive - just clean up
  8107. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  8108. else:
  8109. # Print failed or cancelled - cancel timelapse session
  8110. cancel_session(printer_id)
  8111. logger.info(
  8112. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  8113. )
  8114. except Exception as e:
  8115. logger.warning("[LAYER-TL] Failed: %s", e)
  8116. # Try to cancel session on error
  8117. try:
  8118. cancel_session(printer_id)
  8119. except Exception:
  8120. pass # Best-effort timelapse session cancellation on error
  8121. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  8122. log_timing("All background tasks scheduled")
  8123. # Auto-scan for timelapse if recording was active during the print
  8124. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  8125. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  8126. # Schedule timelapse scan as background task with retries
  8127. # The printer needs time to encode the video after print completion
  8128. baseline = _timelapse_baselines.pop(printer_id, None)
  8129. spawn_background_task(
  8130. _scan_for_timelapse_with_retries(archive_id, baseline, plate_id=notify_plate_id),
  8131. name=f"scan-timelapse-{archive_id}",
  8132. )
  8133. log_timing("Timelapse scan scheduled")
  8134. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  8135. # AMS sensor history recording
  8136. _ams_history_task: asyncio.Task | None = None
  8137. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  8138. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  8139. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  8140. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  8141. _ams_alarm_cooldown: dict[str, datetime] = {}
  8142. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  8143. # (printer_id, ams_id) already reported as sending the drop index and no
  8144. # percentage. Logged once each so a supported printer that turns out to do this
  8145. # shows up in a support bundle rather than as a user wondering where the
  8146. # humidity reading went -- see the note at the read site below (#3140).
  8147. _ams_index_only_logged: set[tuple[int, int]] = set()
  8148. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  8149. """Temperature at which the AMS alarm fires, falling back to the display band.
  8150. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  8151. when a notification was sent as well, which is why a room above it made the
  8152. alarm fire once an hour for as long as the weather lasted -- and the only way
  8153. to stop that was to raise the display band and lose the colour that says the
  8154. unit is warm (#2905).
  8155. Unset resolves to the fair threshold, so an install that never sets one is
  8156. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  8157. so that arrives here as a string and is handled by the same branch as any
  8158. other unparseable value -- there is no separate sentinel to keep in sync.
  8159. A non-positive value is refused rather than honoured: zero would alarm
  8160. permanently, and it is far more likely to be a cleared field than a
  8161. deliberate choice.
  8162. """
  8163. if raw_alarm_value is None:
  8164. return fair_threshold
  8165. try:
  8166. value = float(raw_alarm_value)
  8167. except (TypeError, ValueError):
  8168. return fair_threshold
  8169. if not math.isfinite(value) or value <= 0:
  8170. return fair_threshold
  8171. return value
  8172. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  8173. # through a cycle and the cool-down after it (#1802). Stored in the settings
  8174. # table rather than alongside _ams_alarm_cooldown above, because a restart
  8175. # partway through a cool-down would otherwise resume alarming about heat the
  8176. # user asked for — the same internal-timestamp-row pattern as
  8177. # support.py's debug_logging_enabled_at.
  8178. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  8179. # Upper bound on that suppression. The latch normally clears as soon as the unit
  8180. # reads at or below the threshold; see utils.ams_drying for why this cap only
  8181. # matters when it never does.
  8182. AMS_DRYING_GRACE_MINUTES = 120
  8183. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  8184. """Read the persisted per-AMS drying latch, dropping entries out of window.
  8185. Anything older than the grace cap would expire on its next visit anyway, so
  8186. discarding it here costs nothing and stops rows for deleted printers from
  8187. accumulating.
  8188. Stamps ahead of now get two defences, because a box whose clock jumps
  8189. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  8190. ones are discarded outright, and the rest are clamped to now. Without the
  8191. clamp the cap would measure from a moment that has not happened yet and hold
  8192. the alarm quiet for the skew on top of the cap. One unnecessary notification
  8193. after a clock jump is a far better failure than an alarm silently disabled
  8194. for hours.
  8195. """
  8196. from backend.app.models.settings import Settings
  8197. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8198. setting = result.scalar_one_or_none()
  8199. if not setting or not setting.value:
  8200. return {}
  8201. try:
  8202. raw = json.loads(setting.value)
  8203. except (ValueError, TypeError):
  8204. return {} # Corrupted row → no latch, alarms behave as they did before
  8205. if not isinstance(raw, dict):
  8206. return {}
  8207. now = datetime.now(timezone.utc)
  8208. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  8209. latch: dict[str, datetime] = {}
  8210. for key, value in raw.items():
  8211. try:
  8212. stamp = datetime.fromisoformat(str(value))
  8213. except (ValueError, TypeError):
  8214. continue
  8215. if stamp.tzinfo is None:
  8216. stamp = stamp.replace(tzinfo=timezone.utc)
  8217. if not (now - window <= stamp <= now + window):
  8218. continue
  8219. # Nothing may sit in the future: suppression is measured as now minus
  8220. # the stamp, so a stamp ahead of now would extend it by the skew on top
  8221. # of the cap. Clamping the survivors keeps the cap an actual cap.
  8222. latch[str(key)] = min(stamp, now)
  8223. return latch
  8224. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  8225. """Persist the latch, writing only when it actually changed.
  8226. Adds the session change but does not commit — the caller's own commit
  8227. carries it, so the latch lands in the same transaction as the sensor rows
  8228. that produced it.
  8229. """
  8230. from backend.app.models.settings import Settings
  8231. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  8232. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8233. setting = result.scalar_one_or_none()
  8234. if setting is None:
  8235. # Don't create the row on installs that never dry anything.
  8236. if payload != "{}":
  8237. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  8238. elif setting.value != payload:
  8239. setting.value = payload
  8240. def _ams_has_filament(ams_data: dict) -> bool:
  8241. """True if this AMS unit has at least one tray slot holding filament.
  8242. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  8243. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  8244. still report sensor readings, but those readings are ambient and not
  8245. actionable: no filament to dry, no humidity to push down. #1619 — gate
  8246. humidity/temperature alarms on this check so empty units don't generate
  8247. hourly noise. Sensor history still records regardless so the UI charts
  8248. stay continuous.
  8249. Fallback path inspects the `tray` array's `tray_type` fields for setups
  8250. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  8251. """
  8252. bits = ams_data.get("tray_exist_bits")
  8253. if isinstance(bits, str) and bits.strip():
  8254. try:
  8255. return int(bits, 16) > 0
  8256. except ValueError:
  8257. pass
  8258. trays = ams_data.get("tray")
  8259. if isinstance(trays, list):
  8260. return any(
  8261. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  8262. )
  8263. return False
  8264. async def record_ams_history():
  8265. """Background task to record AMS humidity and temperature data."""
  8266. logger = logging.getLogger(__name__)
  8267. # Wait a short time for MQTT connections to establish on startup
  8268. await asyncio.sleep(10)
  8269. while True:
  8270. try:
  8271. from backend.app.models.ams_history import AMSSensorHistory
  8272. from backend.app.models.printer import Printer
  8273. from backend.app.models.settings import Settings
  8274. async with async_session() as db:
  8275. # Get all active printers
  8276. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8277. printers = result.scalars().all()
  8278. # Get alarm thresholds from settings
  8279. humidity_threshold = 60.0 # Default: fair threshold
  8280. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  8281. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  8282. setting = result.scalar_one_or_none()
  8283. if setting:
  8284. try:
  8285. humidity_threshold = float(setting.value)
  8286. except (ValueError, TypeError):
  8287. pass # Keep default threshold if stored value is invalid
  8288. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  8289. setting = result.scalar_one_or_none()
  8290. if setting:
  8291. try:
  8292. temp_fair_threshold = float(setting.value)
  8293. except (ValueError, TypeError):
  8294. pass # Keep default threshold if stored value is invalid
  8295. # The alarm gets its own threshold, seeded from the resolved fair
  8296. # value so an install that has never set one behaves exactly as
  8297. # it did before (#2905). ams_temp_fair decides when the card turns
  8298. # amber; 35 C is a reasonable place to change a colour and not a
  8299. # reasonable place to page someone. A room above it makes the
  8300. # alarm fire once an hour for as long as the weather lasts, and
  8301. # the only way to stop it was to raise the display band and lose
  8302. # the colour that says the unit is warm.
  8303. #
  8304. # An unset value is stored as the literal "None", which the except
  8305. # below swallows the same way it swallows garbage -- so the
  8306. # fallback costs nothing and needs no sentinel of its own.
  8307. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  8308. setting = result.scalar_one_or_none()
  8309. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  8310. temp_fair_threshold, setting.value if setting else None
  8311. )
  8312. # Per-filament humidity threshold overrides (#1605) — resolved
  8313. # per-AMS below from the loaded tray types. Reuses the same
  8314. # resolver as the auto-drying scheduler so behavior stays in
  8315. # lockstep across both consumers.
  8316. from backend.app.services.print_scheduler import PrintScheduler
  8317. per_type_humidity_thresholds: dict[str, int] = {}
  8318. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  8319. setting = result.scalar_one_or_none()
  8320. if setting and setting.value:
  8321. try:
  8322. raw = json.loads(setting.value)
  8323. if isinstance(raw, dict):
  8324. for k, v in raw.items():
  8325. try:
  8326. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  8327. v
  8328. )
  8329. except (TypeError, ValueError):
  8330. continue
  8331. except (ValueError, TypeError):
  8332. pass # Invalid JSON → no overrides, fall through to global threshold
  8333. # Per-AMS drying latch (#1802), loaded once per pass and written
  8334. # back below only if a unit changed it.
  8335. drying_latch = await _load_ams_drying_latch(db)
  8336. drying_latch_before = dict(drying_latch)
  8337. recorded_count = 0
  8338. for printer in printers:
  8339. # Get current state from printer manager
  8340. state = printer_manager.get_status(printer.id)
  8341. if not state or not state.connected or not state.raw_data:
  8342. continue # Skip disconnected printers - don't use stale data
  8343. raw_data = state.raw_data
  8344. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  8345. continue
  8346. # Record data for each AMS unit
  8347. for ams_data in raw_data["ams"]:
  8348. ams_id = int(ams_data.get("id", 0))
  8349. # Percentage only. The 1-5 index is inverted, so
  8350. # charting it as a percentage drew the wettest units as
  8351. # the driest (#3140); a unit that reports no percentage
  8352. # leaves a gap in the chart instead. See
  8353. # utils/ams_humidity.
  8354. humidity = ams_humidity_percent(ams_data)
  8355. # No supported printer is known to send the index
  8356. # alone -- the report came from unsupported firmware,
  8357. # and no install has been seen using the old fallback.
  8358. # "Known" is doing work there, so say so once per unit:
  8359. # the alternative is a silent blank card.
  8360. if humidity is None and ams_data.get("humidity") is not None:
  8361. unit_key = (printer.id, ams_id)
  8362. if unit_key not in _ams_index_only_logged:
  8363. _ams_index_only_logged.add(unit_key)
  8364. logger.info(
  8365. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  8366. "percentage. The index is inverted and is not shown as a percentage "
  8367. "(#3140), so this unit has no humidity reading, chart or alarm. "
  8368. "Please report this with the printer and AMS firmware versions.",
  8369. printer.name,
  8370. ams_id,
  8371. )
  8372. # Get temperature
  8373. temperature = None
  8374. temp_str = ams_data.get("temp")
  8375. if temp_str is not None:
  8376. try:
  8377. temperature = float(temp_str)
  8378. except (ValueError, TypeError):
  8379. pass # Skip unparseable temperature value
  8380. # Skip if no data
  8381. if humidity is None and temperature is None:
  8382. continue
  8383. # Record the data point
  8384. history = AMSSensorHistory(
  8385. printer_id=printer.id,
  8386. ams_id=ams_id,
  8387. humidity=humidity,
  8388. # Both columns hold the same reading now that the
  8389. # index can no longer reach ``humidity``. Writing it
  8390. # through the same value also stops a genuine 0%
  8391. # from being stored as NULL, which the old truthiness
  8392. # test did.
  8393. humidity_raw=humidity,
  8394. temperature=temperature,
  8395. )
  8396. db.add(history)
  8397. recorded_count += 1
  8398. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  8399. is_ams_ht = ams_id >= 128
  8400. if is_ams_ht:
  8401. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  8402. else:
  8403. ams_label = f"AMS-{chr(65 + ams_id)}"
  8404. # Skip alarm dispatch for empty AMS units — humidity /
  8405. # temperature readings are ambient with no filament to
  8406. # protect, and the hourly notification just becomes
  8407. # noise. Sensor history was already recorded above so
  8408. # the UI charts stay continuous (#1619). Per-AMS check
  8409. # so a multi-AMS setup with one loaded + one empty
  8410. # still alarms on the loaded unit.
  8411. if not _ams_has_filament(ams_data):
  8412. continue
  8413. # Resolve per-filament humidity threshold for this AMS
  8414. # unit (#1605). Falls back to the global ams_humidity_fair
  8415. # when no per-type overrides are configured.
  8416. trays = ams_data.get("tray", []) or []
  8417. effective_humidity_threshold = float(
  8418. PrintScheduler.resolve_humidity_threshold(
  8419. trays, per_type_humidity_thresholds, int(humidity_threshold)
  8420. )
  8421. )
  8422. # Check humidity alarm (only if above threshold)
  8423. if humidity is not None and humidity > effective_humidity_threshold:
  8424. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  8425. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8426. now = datetime.now(timezone.utc)
  8427. if (
  8428. last_alarm is None
  8429. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8430. ):
  8431. _ams_alarm_cooldown[cooldown_key] = now
  8432. logger.info(
  8433. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  8434. )
  8435. try:
  8436. # Call different notification method based on AMS type
  8437. if is_ams_ht:
  8438. await notification_service.on_ams_ht_humidity_high(
  8439. printer.id,
  8440. printer.name,
  8441. ams_label,
  8442. humidity,
  8443. effective_humidity_threshold,
  8444. db,
  8445. )
  8446. else:
  8447. await notification_service.on_ams_humidity_high(
  8448. printer.id,
  8449. printer.name,
  8450. ams_label,
  8451. humidity,
  8452. effective_humidity_threshold,
  8453. db,
  8454. )
  8455. except Exception as e:
  8456. logger.warning("Failed to send humidity alarm: %s", e)
  8457. # A drying cycle heats the unit far past ams_temp_fair on
  8458. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  8459. # AMS-HT, against a 35 C default — so the alarm fired
  8460. # once an hour for the whole cycle and kept firing while
  8461. # the unit cooled back down (#1802). Latch on the
  8462. # firmware's own drying state and hold until the reading
  8463. # returns to normal. Humidity is deliberately left alone:
  8464. # it falls during drying, which is the whole point.
  8465. latch_key = f"{printer.id}:{ams_id}"
  8466. # The latch releases at `threshold`, so it takes the alarm
  8467. # number too. Handing it the display band would strand the
  8468. # latch on any unit that settles back above it -- a room
  8469. # where the AMS rests at 37.7 C never returns under a 35 C
  8470. # band, so the latch could only expire on the grace cap
  8471. # rather than releasing when the unit had actually cooled.
  8472. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  8473. drying_active=is_drying_active(ams_data),
  8474. temperature=temperature,
  8475. threshold=temp_alarm_threshold,
  8476. latched_at=drying_latch.get(latch_key),
  8477. now=datetime.now(timezone.utc),
  8478. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  8479. )
  8480. if new_latch is None:
  8481. drying_latch.pop(latch_key, None)
  8482. else:
  8483. drying_latch[latch_key] = new_latch
  8484. # Check temperature alarm (only if above threshold)
  8485. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  8486. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  8487. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8488. now = datetime.now(timezone.utc)
  8489. if (
  8490. last_alarm is None
  8491. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8492. ):
  8493. _ams_alarm_cooldown[cooldown_key] = now
  8494. logger.info(
  8495. f"Sending temperature alarm for {printer.name} {ams_label}: "
  8496. f"{temperature}°C > {temp_alarm_threshold}°C"
  8497. )
  8498. try:
  8499. # Call different notification method based on AMS type
  8500. if is_ams_ht:
  8501. # The reported threshold has to be the one
  8502. # that fired, or the message says "> 35 °C"
  8503. # while firing at 45.
  8504. await notification_service.on_ams_ht_temperature_high(
  8505. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8506. )
  8507. else:
  8508. await notification_service.on_ams_temperature_high(
  8509. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8510. )
  8511. except Exception as e:
  8512. logger.warning("Failed to send temperature alarm: %s", e)
  8513. if drying_latch != drying_latch_before:
  8514. await _save_ams_drying_latch(db, drying_latch)
  8515. await db.commit()
  8516. if recorded_count > 0:
  8517. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  8518. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  8519. global _ams_cleanup_counter
  8520. _ams_cleanup_counter += 1
  8521. if _ams_cleanup_counter >= 288:
  8522. _ams_cleanup_counter = 0
  8523. # Get retention days from settings
  8524. from backend.app.models.settings import Settings
  8525. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  8526. setting = result.scalar_one_or_none()
  8527. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  8528. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8529. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  8530. await db.commit()
  8531. if result.rowcount > 0:
  8532. logger.info(
  8533. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  8534. )
  8535. # Wait until next recording interval
  8536. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  8537. except asyncio.CancelledError:
  8538. break
  8539. except Exception as e:
  8540. logger.warning("AMS history recording failed: %s", e)
  8541. await asyncio.sleep(60) # Wait a bit before retrying
  8542. def start_ams_history_recording():
  8543. """Start the AMS history recording background task."""
  8544. global _ams_history_task
  8545. if _ams_history_task is None:
  8546. _ams_history_task = asyncio.create_task(record_ams_history())
  8547. logging.getLogger(__name__).info("AMS history recording started")
  8548. def stop_ams_history_recording():
  8549. """Stop the AMS history recording background task."""
  8550. global _ams_history_task
  8551. if _ams_history_task:
  8552. _ams_history_task.cancel()
  8553. _ams_history_task = None
  8554. logging.getLogger(__name__).info("AMS history recording stopped")
  8555. # Printer sensor history recording (nozzle / bed / chamber)
  8556. _printer_sensor_history_task: asyncio.Task | None = None
  8557. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  8558. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  8559. _printer_sensor_cleanup_counter = 0
  8560. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  8561. # MQTT parser writes, so we don't need to handle per-model field aliases here
  8562. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  8563. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  8564. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  8565. _SENSOR_TARGET_KEYS = {
  8566. "nozzle": "nozzle_target",
  8567. "nozzle_2": "nozzle_2_target",
  8568. "bed": "bed_target",
  8569. "chamber": "chamber_target",
  8570. }
  8571. async def record_printer_sensor_history():
  8572. """Background task to record nozzle / bed / chamber readings.
  8573. Pulls from `state.temperatures` (already normalised across all printer
  8574. models by the MQTT parser) rather than re-parsing raw_data, so we get
  8575. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  8576. """
  8577. logger = logging.getLogger(__name__)
  8578. await asyncio.sleep(10)
  8579. while True:
  8580. try:
  8581. from backend.app.models.printer import Printer
  8582. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  8583. from backend.app.models.settings import Settings
  8584. async with async_session() as db:
  8585. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8586. printers = result.scalars().all()
  8587. recorded_count = 0
  8588. for printer in printers:
  8589. state = printer_manager.get_status(printer.id)
  8590. if not state or not state.connected:
  8591. continue
  8592. temps = getattr(state, "temperatures", None) or {}
  8593. if not isinstance(temps, dict):
  8594. continue
  8595. for kind in _SENSOR_KINDS:
  8596. if kind not in temps:
  8597. continue
  8598. try:
  8599. value = float(temps[kind])
  8600. except (ValueError, TypeError):
  8601. continue
  8602. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  8603. target_val: float | None = None
  8604. if target_raw is not None:
  8605. try:
  8606. target_val = float(target_raw)
  8607. except (ValueError, TypeError):
  8608. target_val = None
  8609. db.add(
  8610. PrinterSensorHistory(
  8611. printer_id=printer.id,
  8612. sensor_kind=kind,
  8613. value=value,
  8614. target=target_val,
  8615. )
  8616. )
  8617. recorded_count += 1
  8618. await db.commit()
  8619. if recorded_count > 0:
  8620. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  8621. # Periodic cleanup — once every ~24h at this interval.
  8622. global _printer_sensor_cleanup_counter
  8623. _printer_sensor_cleanup_counter += 1
  8624. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  8625. if _printer_sensor_cleanup_counter >= cleanup_every:
  8626. _printer_sensor_cleanup_counter = 0
  8627. result = await db.execute(
  8628. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  8629. )
  8630. setting = result.scalar_one_or_none()
  8631. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  8632. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8633. cleanup = await db.execute(
  8634. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  8635. )
  8636. await db.commit()
  8637. if cleanup.rowcount > 0:
  8638. logger.info(
  8639. "Cleaned up %s old printer sensor history entries (older than %s days)",
  8640. cleanup.rowcount,
  8641. retention_days,
  8642. )
  8643. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  8644. except asyncio.CancelledError:
  8645. break
  8646. except Exception as e:
  8647. logger.warning("Printer sensor history recording failed: %s", e)
  8648. await asyncio.sleep(60)
  8649. def start_printer_sensor_history_recording():
  8650. global _printer_sensor_history_task
  8651. if _printer_sensor_history_task is None:
  8652. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  8653. logging.getLogger(__name__).info("Printer sensor history recording started")
  8654. def stop_printer_sensor_history_recording():
  8655. global _printer_sensor_history_task
  8656. if _printer_sensor_history_task:
  8657. _printer_sensor_history_task.cancel()
  8658. _printer_sensor_history_task = None
  8659. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  8660. # Printer runtime tracking
  8661. _runtime_tracking_task: asyncio.Task | None = None
  8662. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  8663. async def track_printer_runtime():
  8664. """Background task to track printer active runtime (RUNNING state only).
  8665. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  8666. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  8667. which track mechanical wear. Pause time has no motion and no wear, so
  8668. counting it inflates maintenance warnings (#1521).
  8669. """
  8670. logger = logging.getLogger(__name__)
  8671. # Wait for MQTT connections to establish on startup
  8672. await asyncio.sleep(15)
  8673. while True:
  8674. try:
  8675. from backend.app.models.printer import Printer
  8676. # Fetch printer IDs in a short-lived read-only session
  8677. async with async_session() as db:
  8678. result = await db.execute(
  8679. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  8680. Printer.is_active.is_(True)
  8681. )
  8682. )
  8683. printer_rows = result.all()
  8684. now = datetime.now(timezone.utc)
  8685. updated_count = 0
  8686. # Update each printer in its own short session to minimise write-lock
  8687. # hold time and avoid blocking critical commits like queue status
  8688. # updates (#897).
  8689. for pid, pname, runtime_secs, last_update in printer_rows:
  8690. state = printer_manager.get_status(pid)
  8691. if not state:
  8692. logger.debug("[%s] Runtime tracking: no state available", pname)
  8693. continue
  8694. if not state.connected:
  8695. logger.debug("[%s] Runtime tracking: not connected", pname)
  8696. continue
  8697. needs_commit = False
  8698. new_runtime = runtime_secs
  8699. new_last_update = last_update
  8700. if state.state == "RUNNING":
  8701. if last_update:
  8702. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  8703. elapsed = (now - lu).total_seconds()
  8704. if elapsed > 0:
  8705. new_runtime = runtime_secs + int(elapsed)
  8706. updated_count += 1
  8707. needs_commit = True
  8708. logger.debug(
  8709. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  8710. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  8711. )
  8712. else:
  8713. needs_commit = True
  8714. logger.debug("[%s] Runtime tracking: first active detection", pname)
  8715. new_last_update = now
  8716. else:
  8717. if last_update is not None:
  8718. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  8719. new_last_update = None
  8720. needs_commit = True
  8721. if needs_commit:
  8722. try:
  8723. async with async_session() as db:
  8724. result = await db.execute(select(Printer).where(Printer.id == pid))
  8725. printer = result.scalar_one_or_none()
  8726. if printer:
  8727. printer.runtime_seconds = new_runtime
  8728. printer.last_runtime_update = new_last_update
  8729. await db.commit()
  8730. except Exception as e:
  8731. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  8732. if updated_count > 0:
  8733. logger.debug("Updated runtime for %s printer(s)", updated_count)
  8734. except asyncio.CancelledError:
  8735. logger.info("Runtime tracking cancelled")
  8736. break
  8737. except Exception as e:
  8738. logger.warning("Runtime tracking failed: %s", e)
  8739. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  8740. def start_runtime_tracking():
  8741. """Start the printer runtime tracking background task."""
  8742. global _runtime_tracking_task
  8743. if _runtime_tracking_task is None:
  8744. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  8745. logging.getLogger(__name__).info("Printer runtime tracking started")
  8746. def stop_runtime_tracking():
  8747. """Stop the printer runtime tracking background task."""
  8748. global _runtime_tracking_task
  8749. if _runtime_tracking_task:
  8750. _runtime_tracking_task.cancel()
  8751. _runtime_tracking_task = None
  8752. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  8753. # SpoolBuddy device watchdog
  8754. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  8755. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  8756. async def _spoolbuddy_watchdog_loop():
  8757. """Periodic check for SpoolBuddy devices that have gone offline."""
  8758. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  8759. while True:
  8760. try:
  8761. await spoolbuddy_watchdog()
  8762. except asyncio.CancelledError:
  8763. break
  8764. except Exception as e:
  8765. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  8766. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  8767. def start_spoolbuddy_watchdog():
  8768. global _spoolbuddy_watchdog_task
  8769. if _spoolbuddy_watchdog_task is None:
  8770. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  8771. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  8772. def stop_spoolbuddy_watchdog():
  8773. global _spoolbuddy_watchdog_task
  8774. if _spoolbuddy_watchdog_task:
  8775. _spoolbuddy_watchdog_task.cancel()
  8776. _spoolbuddy_watchdog_task = None
  8777. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  8778. # Dead-MQTT-session recovery
  8779. #
  8780. # check_staleness() covers the "connected but silent" half-broken session. It
  8781. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  8782. # is the only thing left watching at that point. When paho stops making
  8783. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  8784. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  8785. # offline with the UI open the whole time, recovered only when something
  8786. # happened to nudge it.
  8787. #
  8788. # This loop is that backstop. It only touches printers that had a working
  8789. # session and lost it, and only when the MQTT port still answers — a printer
  8790. # that is simply switched off is left to paho, since rebuilding a client
  8791. # against an unreachable host achieves nothing and would fill the log every
  8792. # night.
  8793. _connection_watchdog_task: asyncio.Task | None = None
  8794. CONNECTION_WATCHDOG_INTERVAL = 60
  8795. # How long a printer must have been silent before we stop trusting paho.
  8796. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  8797. # so a session that is recovering on its own is never interrupted.
  8798. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  8799. # Per-printer floor between rebuild attempts.
  8800. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  8801. _connection_watchdog_last_attempt: dict[int, float] = {}
  8802. async def _recover_dead_printer_sessions() -> int:
  8803. """Rebuild MQTT clients that have been offline too long to still be trying.
  8804. Returns the number of printers a rebuild was attempted for (for tests and
  8805. for the caller's logging). Never raises: one unreachable printer must not
  8806. stop the sweep for the rest of the farm.
  8807. """
  8808. logger = logging.getLogger(__name__)
  8809. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  8810. now = time.monotonic()
  8811. recovered = 0
  8812. for printer_id, client in list(printer_manager._clients.items()):
  8813. try:
  8814. if client.state.connected:
  8815. _connection_watchdog_last_attempt.pop(printer_id, None)
  8816. continue
  8817. # Time since the last inbound message is the age of the last known
  8818. # good session — no extra bookkeeping needed, and it is the same
  8819. # clock is_stale() reads. 0 means this client has never had one:
  8820. # that is the initial-connect path, where paho retrying is the
  8821. # correct and only behaviour, so leave it be.
  8822. last_msg = client._last_message_time
  8823. if not last_msg:
  8824. continue
  8825. offline_for = time.time() - last_msg
  8826. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  8827. continue
  8828. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  8829. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  8830. continue
  8831. if not await check_port(client.ip_address, PORT_MQTT):
  8832. # Switched off, unplugged, or off the network. Paho's retry is
  8833. # the right handler; say so at debug level and move on.
  8834. logger.debug(
  8835. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  8836. "— leaving the reconnect to paho",
  8837. printer_id,
  8838. offline_for,
  8839. )
  8840. _connection_watchdog_last_attempt[printer_id] = now
  8841. continue
  8842. _connection_watchdog_last_attempt[printer_id] = now
  8843. recovered += 1
  8844. logger.warning(
  8845. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  8846. "rebuilding the client with a fresh session (last connect error: %s)",
  8847. printer_id,
  8848. offline_for,
  8849. PORT_MQTT,
  8850. client.last_connect_error or "none recorded",
  8851. )
  8852. # Async context, so this takes the hard-reset path: fresh client_id,
  8853. # paho's QoS 1 queue dropped. That matters — a project_file left
  8854. # unacked on the dead session would otherwise replay into the new
  8855. # one and trip 0500_4003 on the printer (#1136).
  8856. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  8857. except Exception as e:
  8858. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  8859. return recovered
  8860. async def _connection_watchdog_loop():
  8861. logger = logging.getLogger(__name__)
  8862. # Let the initial connects settle before judging anyone offline.
  8863. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  8864. while True:
  8865. try:
  8866. await _recover_dead_printer_sessions()
  8867. except asyncio.CancelledError:
  8868. break
  8869. except Exception as e:
  8870. logger.warning("Connection watchdog sweep failed: %s", e)
  8871. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  8872. def start_connection_watchdog():
  8873. global _connection_watchdog_task
  8874. if _connection_watchdog_task is None:
  8875. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  8876. logging.getLogger(__name__).info("Printer connection watchdog started")
  8877. def stop_connection_watchdog():
  8878. global _connection_watchdog_task
  8879. if _connection_watchdog_task:
  8880. _connection_watchdog_task.cancel()
  8881. _connection_watchdog_task = None
  8882. _connection_watchdog_last_attempt.clear()
  8883. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  8884. # Camera stream orphan cleanup
  8885. _camera_cleanup_task: asyncio.Task | None = None
  8886. CAMERA_CLEANUP_INTERVAL = 60
  8887. async def _camera_cleanup_loop():
  8888. """Periodically clean up orphaned ffmpeg processes."""
  8889. from backend.app.api.routes.camera import cleanup_orphaned_streams
  8890. while True:
  8891. try:
  8892. await cleanup_orphaned_streams()
  8893. except asyncio.CancelledError:
  8894. break
  8895. except Exception as e:
  8896. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  8897. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  8898. def start_camera_cleanup():
  8899. global _camera_cleanup_task
  8900. if _camera_cleanup_task is None:
  8901. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  8902. logging.getLogger(__name__).info("Camera stream cleanup started")
  8903. def stop_camera_cleanup():
  8904. global _camera_cleanup_task
  8905. if _camera_cleanup_task:
  8906. _camera_cleanup_task.cancel()
  8907. _camera_cleanup_task = None
  8908. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  8909. # ---------------------------------------------------------------------------
  8910. # Expected-print TTL eviction
  8911. # ---------------------------------------------------------------------------
  8912. def _evict_stale_expected_prints() -> None:
  8913. """Remove entries from _expected_prints / _expected_print_creators that are
  8914. older than _EXPECTED_PRINT_TTL_SECONDS.
  8915. This prevents unbounded growth when a print is registered (via
  8916. register_expected_print) but on_print_start never fires — e.g. because the
  8917. printer disconnects, the app restarts, or the print is started directly from
  8918. the printer panel without going through the queue.
  8919. """
  8920. # Use monotonic time so the TTL is unaffected by system clock adjustments
  8921. # (e.g. NTP sync, DST changes).
  8922. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  8923. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  8924. if not stale_keys:
  8925. return
  8926. evicted_archive_ids: set[int] = set()
  8927. for key in stale_keys:
  8928. archive_id = _expected_prints.pop(key, None)
  8929. if archive_id is not None:
  8930. evicted_archive_ids.add(archive_id)
  8931. _expected_print_creators.pop(key, None)
  8932. _expected_print_registered_at.pop(key, None)
  8933. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  8934. # that have no remaining live keys in _expected_prints (all variants
  8935. # were just evicted) and are not printing right now. Print start pops
  8936. # only the names the printer reported, so the "<base>.gcode" variant
  8937. # outlives it; without the printing check its eviction two hours after
  8938. # dispatch threw away a running print's plate, AMS mapping and cost
  8939. # centre, which completion still reads (#3275).
  8940. live_archive_ids = set(_expected_prints.values()) | set(_active_prints.values())
  8941. for archive_id in evicted_archive_ids:
  8942. if archive_id not in live_archive_ids:
  8943. _print_ams_mappings.pop(archive_id, None)
  8944. _print_cost_center_ids.pop(archive_id, None)
  8945. _print_plate_ids.pop(archive_id, None)
  8946. logging.getLogger(__name__).info(
  8947. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  8948. )
  8949. async def _expected_prints_cleanup_loop() -> None:
  8950. """Background task: periodically evict stale expected-print entries."""
  8951. while True:
  8952. try:
  8953. _evict_stale_expected_prints()
  8954. except asyncio.CancelledError:
  8955. raise
  8956. except Exception as e:
  8957. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  8958. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  8959. def start_expected_prints_cleanup() -> None:
  8960. global _expected_prints_cleanup_task
  8961. if _expected_prints_cleanup_task is None:
  8962. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  8963. logging.getLogger(__name__).info("Expected prints cleanup started")
  8964. def stop_expected_prints_cleanup() -> None:
  8965. global _expected_prints_cleanup_task
  8966. if _expected_prints_cleanup_task:
  8967. _expected_prints_cleanup_task.cancel()
  8968. _expected_prints_cleanup_task = None
  8969. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  8970. # ---------------------------------------------------------------------------
  8971. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  8972. # ---------------------------------------------------------------------------
  8973. _auth_cleanup_task: asyncio.Task | None = None
  8974. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  8975. async def _run_auth_cleanup() -> None:
  8976. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  8977. from backend.app.core.database import async_session
  8978. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  8979. from backend.app.models.user_totp import UserTOTP
  8980. now = datetime.now(timezone.utc)
  8981. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  8982. try:
  8983. async with async_session() as db:
  8984. stale_cutoff = now - timedelta(hours=1)
  8985. result = await db.execute(
  8986. select(UserTOTP).where(
  8987. UserTOTP.is_enabled.is_(False),
  8988. UserTOTP.created_at < stale_cutoff,
  8989. )
  8990. )
  8991. stale_records = result.scalars().all()
  8992. if stale_records:
  8993. for rec in stale_records:
  8994. await db.delete(rec)
  8995. await db.commit()
  8996. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  8997. except Exception as e:
  8998. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  8999. # Remove expired revoked-JTI entries (they are no longer needed once the
  9000. # original token's exp has passed — the token would be rejected by JWT
  9001. # signature verification regardless).
  9002. try:
  9003. async with async_session() as db:
  9004. await db.execute(
  9005. delete(AuthEphemeralToken).where(
  9006. AuthEphemeralToken.token_type == "revoked_jti",
  9007. AuthEphemeralToken.expires_at < now,
  9008. )
  9009. )
  9010. await db.commit()
  9011. except Exception as e:
  9012. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  9013. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  9014. # Events outside this window can never affect rate-limit decisions — they only
  9015. # consume DB space. Use the same window constant as the rate limiter so the
  9016. # two are always in sync.
  9017. try:
  9018. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  9019. async with async_session() as db:
  9020. await db.execute(
  9021. delete(AuthRateLimitEvent).where(
  9022. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  9023. )
  9024. )
  9025. await db.commit()
  9026. except Exception as e:
  9027. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  9028. async def _auth_cleanup_loop() -> None:
  9029. """Periodic background task: run auth cleanup every hour."""
  9030. while True:
  9031. try:
  9032. await _run_auth_cleanup()
  9033. except asyncio.CancelledError:
  9034. break
  9035. except Exception as e:
  9036. logging.warning("Auth cleanup loop error: %s", e)
  9037. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  9038. def start_auth_cleanup() -> None:
  9039. global _auth_cleanup_task
  9040. if _auth_cleanup_task is None:
  9041. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  9042. logging.getLogger(__name__).info("Auth periodic cleanup started")
  9043. def stop_auth_cleanup() -> None:
  9044. global _auth_cleanup_task
  9045. if _auth_cleanup_task:
  9046. _auth_cleanup_task.cancel()
  9047. _auth_cleanup_task = None
  9048. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  9049. @asynccontextmanager
  9050. async def lifespan(app: FastAPI):
  9051. # Startup
  9052. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  9053. # anything else can spawn tasks that might trip it.
  9054. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  9055. install_proactor_reset_filter()
  9056. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  9057. # what turned descriptor exhaustion into a corrupted database (#2883).
  9058. from backend.app.core.fd_limit import raise_open_file_limit
  9059. raise_open_file_limit()
  9060. # Before init_db, so the warning is near the top of the log rather than
  9061. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  9062. warn_if_running_on_uvloop()
  9063. await init_db()
  9064. # Browser download tokens expire after five minutes. Remove abandoned
  9065. # prepared ZIPs at startup as well as before each new preparation so a
  9066. # quiet appliance cannot retain an unusable bundle indefinitely.
  9067. try:
  9068. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  9069. await prune_stale_printer_file_bundles()
  9070. except Exception as exc:
  9071. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  9072. # After migrations, so the is_env_managed column exists. Never raises --
  9073. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  9074. # startup (see apply_env_oidc_provider).
  9075. from backend.app.core.oidc_env import apply_env_oidc_provider
  9076. async with async_session() as oidc_db:
  9077. await apply_env_oidc_provider(oidc_db)
  9078. # Close out batches that finished before `completed` was a reachable status
  9079. # (#342). Without this the Batches tab opens on every batch created since
  9080. # the feature shipped, all still marked active. Never blocks startup.
  9081. try:
  9082. from backend.app.services.print_batch import backfill_batch_statuses
  9083. async with async_session() as batch_db:
  9084. await backfill_batch_statuses(batch_db)
  9085. except Exception as exc:
  9086. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  9087. # Register an app-scoped httpx client for Bambu Cloud services so
  9088. # per-request BambuCloudService instances reuse the same connection pool
  9089. # (important for routes like /cloud/filament-info that chain many
  9090. # get_setting_detail calls). The shared client stores no region/token
  9091. # state, so the per-request ownership pattern that fixed the region-bleed
  9092. # bug is preserved.
  9093. import httpx as _httpx
  9094. from backend.app.services.bambu_cloud import set_shared_http_client
  9095. from backend.app.services.model_providers.makerworld.service import (
  9096. set_shared_http_client as set_shared_makerworld_http_client,
  9097. )
  9098. from backend.app.services.orca_cloud import (
  9099. set_shared_http_client as set_shared_orca_http_client,
  9100. )
  9101. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  9102. set_shared_http_client(_shared_cloud_http_client)
  9103. # Reuse the same connection pool for MakerWorld — different host, same
  9104. # keep-alive pool saves a TLS handshake per request.
  9105. set_shared_makerworld_http_client(_shared_cloud_http_client)
  9106. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  9107. # each spun up (and never closed) its own client, leaking sockets.
  9108. set_shared_orca_http_client(_shared_cloud_http_client)
  9109. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  9110. # This can happen when a print was cancelled mid-print on versions before this fix.
  9111. try:
  9112. async with async_session() as db:
  9113. from backend.app.models.print_queue import PrintQueueItem
  9114. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  9115. aborted_items = result.scalars().all()
  9116. if aborted_items:
  9117. for item in aborted_items:
  9118. item.status = "cancelled"
  9119. await db.commit()
  9120. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  9121. except Exception as e:
  9122. logging.warning("Failed to fix aborted queue items: %s", e)
  9123. # Restore debug logging state from previous session
  9124. await init_debug_logging()
  9125. # Set up printer manager callbacks
  9126. loop = asyncio.get_event_loop()
  9127. printer_manager.set_event_loop(loop)
  9128. printer_manager.set_status_change_callback(on_printer_status_change)
  9129. printer_manager.set_print_start_callback(on_print_start)
  9130. printer_manager.set_print_complete_callback(on_print_complete)
  9131. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  9132. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  9133. printer_manager.set_ams_change_callback(on_ams_change)
  9134. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  9135. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  9136. await printer_manager.load_awaiting_plate_clear_from_db()
  9137. # Layer change callback for external camera timelapse
  9138. async def on_layer_change(printer_id: int, layer_num: int):
  9139. """Capture timelapse frame on layer change + first layer notification."""
  9140. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  9141. await tl_layer_change(printer_id, layer_num)
  9142. # #1867: bank a recent in-print frame so the finish-photo path has a
  9143. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  9144. # #2547 added `on_print_progress` as a second driver — this one alone
  9145. # stops firing once the final layer begins.
  9146. await _maybe_bank_inprint_frame(printer_id, layer_num)
  9147. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  9148. # Gate on actual printing state — Bambu firmware ticks layer_num during
  9149. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  9150. # nozzle clean), so a bare layer_num check can fire minutes before the
  9151. # first real extrusion. We require gcode_state == RUNNING and
  9152. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  9153. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  9154. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  9155. # edge fires later; _first_layer_notified stays clear until we actually send
  9156. # so a deferred re-evaluation can win. See issue #1837.
  9157. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  9158. client = printer_manager.get_client(printer_id)
  9159. state = client.state if client else None
  9160. if not state or state.state != "RUNNING":
  9161. return
  9162. if state.mc_print_sub_stage not in (None, 0):
  9163. return
  9164. _first_layer_notified[printer_id] = True
  9165. try:
  9166. async with async_session() as db:
  9167. from backend.app.models.printer import Printer
  9168. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9169. printer = result.scalar_one_or_none()
  9170. if not printer:
  9171. return
  9172. printer_name = printer.name
  9173. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  9174. total_layers = state.total_layers if state else 0
  9175. image_data = await _capture_snapshot_for_notification(
  9176. printer_id, printer, logging.getLogger(__name__)
  9177. )
  9178. await notification_service.on_first_layer_complete(
  9179. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  9180. )
  9181. except Exception as e:
  9182. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  9183. printer_manager.set_layer_change_callback(on_layer_change)
  9184. async def on_print_progress(printer_id: int, percent: int):
  9185. """#2547: keep the in-print frame bank fresh through the final layer.
  9186. `on_layer_change` stops the moment the last layer starts, which on the
  9187. H2C capture that closed #2547 left the bank stale for the three minutes
  9188. that layer took. Progress is the only field that keeps advancing there,
  9189. and it freezes before the End G-code runs — so banking on it stays
  9190. inside the print and never sees a swapped plate.
  9191. """
  9192. client = printer_manager.get_client(printer_id)
  9193. state = client.state if client else None
  9194. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  9195. printer_manager.set_print_progress_callback(on_print_progress)
  9196. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  9197. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  9198. waiter = _bed_cool_waiters.get(printer_id)
  9199. if not waiter:
  9200. return
  9201. threshold = waiter["threshold"]
  9202. if bed_temp > threshold:
  9203. return
  9204. # Bed is at or below threshold — fire notification and remove waiter
  9205. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  9206. if not waiter_info:
  9207. return # Another callback already handled it
  9208. bed_cool_logger = logging.getLogger(__name__)
  9209. bed_cool_logger.info(
  9210. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  9211. bed_temp,
  9212. printer_id,
  9213. threshold,
  9214. )
  9215. try:
  9216. printer_info = printer_manager.get_printer(printer_id)
  9217. p_name = printer_info.name if printer_info else "Unknown"
  9218. async with async_session() as db:
  9219. await notification_service.on_bed_cooled(
  9220. printer_id=printer_id,
  9221. printer_name=p_name,
  9222. bed_temp=bed_temp,
  9223. threshold=threshold,
  9224. filename=waiter_info["filename"],
  9225. db=db,
  9226. )
  9227. except Exception as e:
  9228. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  9229. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  9230. async def on_drying_complete(printer_id: int, ams_id: int):
  9231. """Smart-plug auto-off-after-drying trigger (#1349).
  9232. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  9233. manager walks all plugs linked to this printer and turns off only
  9234. the ones with ``auto_off_after_drying`` enabled, after their
  9235. per-plug delay. Multiple AMS units finishing close together (e.g. a
  9236. dual-AMS dry that ends within the same MQTT push) call this once
  9237. per unit — the manager's ``_cancel_pending_off`` collapses
  9238. repeated scheduling on the same plug to one timer, so duplicate
  9239. fires are safe.
  9240. """
  9241. try:
  9242. async with async_session() as db:
  9243. await smart_plug_manager.on_drying_complete(printer_id, db)
  9244. except Exception as e:
  9245. logging.getLogger(__name__).warning(
  9246. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  9247. printer_id,
  9248. ams_id,
  9249. e,
  9250. )
  9251. printer_manager.set_drying_complete_callback(on_drying_complete)
  9252. async def on_drying_cycle_end(printer_id: int, cycle):
  9253. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  9254. from backend.app.services.spool_drying import record_drying_cycle
  9255. try:
  9256. async with async_session() as db:
  9257. await record_drying_cycle(db, printer_id, cycle)
  9258. except Exception as e:
  9259. logging.getLogger(__name__).warning(
  9260. "Failed to record drying for printer %d (AMS %d): %s",
  9261. printer_id,
  9262. cycle.ams_id,
  9263. e,
  9264. )
  9265. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  9266. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  9267. """Surface the read-back result of a spool assignment to the UI (#2582).
  9268. The MQTT client confirms (or fails to confirm) that the tray telemetry
  9269. echoed back the filament id we pushed. We relay that as a websocket
  9270. event so the frontend can toast "loaded" / "assignment didn't take"
  9271. instead of the historic silent fire-and-forget, which made the
  9272. AMS→Studio hand-off feel random to users.
  9273. """
  9274. try:
  9275. from backend.app.services.spool_assignment_notifications import (
  9276. _slot_label_from_global_tray,
  9277. )
  9278. if ams_id == 255:
  9279. global_id = 254 + tray_id
  9280. elif ams_id >= 128:
  9281. global_id = ams_id
  9282. else:
  9283. global_id = ams_id * 4 + tray_id
  9284. slot_label = _slot_label_from_global_tray(global_id)
  9285. printer_info = printer_manager.get_printer(printer_id)
  9286. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  9287. await ws_manager.broadcast(
  9288. {
  9289. "type": "spool_assignment_verified",
  9290. "printer_id": printer_id,
  9291. "printer_name": printer_name,
  9292. "ams_id": ams_id,
  9293. "tray_id": tray_id,
  9294. "slot": slot_label,
  9295. "verified": verified,
  9296. # Present on success: False means the filament setting landed
  9297. # but the K-profile (cali_idx) did not — the reporter's exact
  9298. # "loaded but no flow profile" symptom.
  9299. "kprofile_applied": detail.get("kprofile_applied", True),
  9300. # Present on failure: whether any tray telemetry was seen in
  9301. # the window (distinguishes "printer silent" from "printer
  9302. # stored something else").
  9303. "saw_tray": detail.get("saw_tray", False),
  9304. }
  9305. )
  9306. except Exception as e:
  9307. logging.getLogger(__name__).warning(
  9308. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  9309. printer_id,
  9310. ams_id,
  9311. tray_id,
  9312. e,
  9313. )
  9314. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  9315. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  9316. """Persist a mid-print tray change for completion-time attribution.
  9317. AMS filament backup switches trays without telling the slicer, so the
  9318. tray-change log is the only record of which spool fed which layers.
  9319. Keeping it only in memory meant a restart mid-print charged everything
  9320. to the tray that finished the job.
  9321. """
  9322. try:
  9323. from backend.app.services.usage_tracker import record_tray_change
  9324. async with async_session() as db:
  9325. await record_tray_change(db, printer_id, tray_global, layer_num)
  9326. except Exception as e:
  9327. logging.getLogger(__name__).warning(
  9328. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  9329. printer_id,
  9330. tray_global,
  9331. layer_num,
  9332. e,
  9333. )
  9334. printer_manager.set_tray_change_callback(on_tray_change)
  9335. # Initialize MQTT relay from settings
  9336. async with async_session() as db:
  9337. from backend.app.api.routes.settings import get_setting
  9338. mqtt_settings = {
  9339. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  9340. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  9341. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  9342. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  9343. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  9344. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  9345. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  9346. }
  9347. await mqtt_relay.configure(mqtt_settings)
  9348. # Restore MQTT smart plug subscriptions
  9349. if mqtt_settings.get("mqtt_enabled"):
  9350. from backend.app.models.smart_plug import SmartPlug
  9351. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  9352. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  9353. mqtt_plugs = result.scalars().all()
  9354. restored = 0
  9355. for plug in mqtt_plugs:
  9356. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  9357. restored += 1
  9358. if restored:
  9359. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  9360. # Connect to all active printers
  9361. async with async_session() as db:
  9362. await init_printer_connections(db)
  9363. # Auto-connect to Spoolman if enabled
  9364. async with async_session() as db:
  9365. from backend.app.api.routes.settings import get_setting
  9366. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  9367. spoolman_url = await get_setting(db, "spoolman_url")
  9368. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  9369. try:
  9370. client = await init_spoolman_client(spoolman_url)
  9371. if await client.health_check():
  9372. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  9373. # Ensure the 'tag' extra field exists for RFID/UUID storage
  9374. field_ok = await client.ensure_tag_extra_field()
  9375. if not field_ok:
  9376. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  9377. # Register the BambuStudio slicer-preset fields used by the
  9378. # spool-edit / assign flow. Spoolman rejects PATCHes with
  9379. # unknown extra keys, so these must exist before any update
  9380. # that touches them.
  9381. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  9382. if not await client.ensure_extra_field(field_name):
  9383. logging.warning(
  9384. "Spoolman extra field %r registration failed — "
  9385. "spool slicer-preset edits will return 502",
  9386. field_name,
  9387. )
  9388. else:
  9389. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  9390. except Exception as e:
  9391. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  9392. # Start the print scheduler
  9393. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  9394. # Start the smart plug scheduler for time-based on/off
  9395. smart_plug_manager.start_scheduler()
  9396. # Start the Home Assistant sensor poller (#1148)
  9397. ha_sensor_manager.start()
  9398. location_ha_sensor_manager.start()
  9399. # Resume any pending auto-offs that were interrupted by restart
  9400. await smart_plug_manager.resume_pending_auto_offs()
  9401. # Start the notification digest scheduler
  9402. notification_service.start_digest_scheduler()
  9403. notify_live_activities.start()
  9404. notify_widgets.start()
  9405. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  9406. # provider in reactions/both mode; the notification routes resync them.
  9407. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  9408. # until the next provider save, not the whole startup.
  9409. try:
  9410. await telegram_reaction_poller.start()
  9411. except Exception as e:
  9412. logging.warning("Telegram reaction poller did not start: %s", e)
  9413. # Start the GitHub backup scheduler
  9414. await github_backup_service.start_scheduler()
  9415. # Start the local backup scheduler
  9416. await local_backup_service.start_scheduler()
  9417. await obico_detection_service.start()
  9418. # Start the library trash sweeper (#1008)
  9419. await library_trash_service.start_scheduler()
  9420. # Start the archive auto-purge sweeper (#1008 follow-up)
  9421. await archive_purge_service.start_scheduler()
  9422. # Start AMS history recording
  9423. start_ams_history_recording()
  9424. # Start printer sensor (nozzle / bed / chamber) history recording
  9425. start_printer_sensor_history_recording()
  9426. # Start printer runtime tracking
  9427. start_runtime_tracking()
  9428. # Start SpoolBuddy device watchdog
  9429. start_spoolbuddy_watchdog()
  9430. # Start camera stream orphan cleanup
  9431. start_camera_cleanup()
  9432. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  9433. start_connection_watchdog()
  9434. # One-shot sweep for timelapse session directories orphaned by a crash
  9435. # or restart that happened mid-print (in-memory session tracking can't
  9436. # survive that, and nothing else reaps the leftover frames/output file)
  9437. try:
  9438. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9439. removed = cleanup_orphaned_timelapse_sessions()
  9440. if removed:
  9441. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  9442. except Exception as e:
  9443. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  9444. # Start expected-print TTL eviction (prevents memory leak when prints are
  9445. # registered but on_print_start never fires)
  9446. start_expected_prints_cleanup()
  9447. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  9448. start_auth_cleanup()
  9449. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  9450. from backend.app.services import announcements as announcements_service
  9451. announcements_service.start()
  9452. from backend.app.services.printer_media import start_printer_download_cleanup
  9453. start_printer_download_cleanup()
  9454. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  9455. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  9456. from backend.app.services.loop_watchdog import start_loop_watchdog
  9457. start_loop_watchdog()
  9458. # Initialize virtual printer manager and sync from DB
  9459. from backend.app.services.virtual_printer import virtual_printer_manager
  9460. virtual_printer_manager.set_session_factory(async_session)
  9461. virtual_printer_manager.set_printer_manager(printer_manager)
  9462. try:
  9463. await virtual_printer_manager.sync_from_db()
  9464. logging.info("Virtual printer manager synced from database")
  9465. except Exception as e:
  9466. logging.warning("Failed to sync virtual printers: %s", e)
  9467. yield
  9468. # Shutdown
  9469. print_scheduler.stop()
  9470. smart_plug_manager.stop_scheduler()
  9471. ha_sensor_manager.stop()
  9472. location_ha_sensor_manager.stop()
  9473. notification_service.stop_digest_scheduler()
  9474. await notify_live_activities.close()
  9475. await notify_widgets.close()
  9476. await telegram_reaction_poller.aclose()
  9477. github_backup_service.stop_scheduler()
  9478. local_backup_service.stop_scheduler()
  9479. library_trash_service.stop_scheduler()
  9480. archive_purge_service.stop_scheduler()
  9481. obico_detection_service.stop()
  9482. stop_ams_history_recording()
  9483. stop_printer_sensor_history_recording()
  9484. stop_runtime_tracking()
  9485. stop_spoolbuddy_watchdog()
  9486. stop_camera_cleanup()
  9487. stop_connection_watchdog()
  9488. from backend.app.services.loop_watchdog import stop_loop_watchdog
  9489. stop_loop_watchdog()
  9490. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  9491. # cleanly rather than waiting on a queue that nothing will ever fill.
  9492. try:
  9493. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  9494. await shutdown_all_broadcasters()
  9495. except Exception as e:
  9496. logging.warning("Failed to shut down camera broadcasters: %s", e)
  9497. stop_expected_prints_cleanup()
  9498. stop_auth_cleanup()
  9499. from backend.app.services import announcements as announcements_service
  9500. announcements_service.stop()
  9501. from backend.app.services.printer_media import stop_printer_download_cleanup
  9502. await stop_printer_download_cleanup()
  9503. printer_manager.disconnect_all()
  9504. slot_unlink_grace.reset()
  9505. await close_spoolman_client()
  9506. # Stop all virtual printer services
  9507. await virtual_printer_manager.stop_all()
  9508. await mqtt_smart_plug_service.disconnect(timeout=2)
  9509. await mqtt_relay.disconnect(timeout=2)
  9510. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  9511. set_shared_http_client(None)
  9512. set_shared_makerworld_http_client(None)
  9513. set_shared_orca_http_client(None)
  9514. await _shared_cloud_http_client.aclose()
  9515. # Checkpoint WAL (SQLite only) and close all database connections
  9516. from backend.app.core.db_dialect import is_sqlite
  9517. if is_sqlite():
  9518. try:
  9519. async with engine.begin() as conn:
  9520. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  9521. logging.info("WAL checkpoint completed")
  9522. except Exception as e:
  9523. logging.warning("WAL checkpoint failed: %s", e)
  9524. await engine.dispose()
  9525. app = FastAPI(
  9526. title=app_settings.app_name,
  9527. description="Archive and manage Bambu Lab 3MF files",
  9528. version=APP_VERSION,
  9529. lifespan=lifespan,
  9530. )
  9531. # =============================================================================
  9532. # Authentication Middleware - Secures ALL API routes by default
  9533. # =============================================================================
  9534. # Public routes that don't require authentication even when auth is enabled
  9535. PUBLIC_API_ROUTES = {
  9536. # Auth routes needed before/during login
  9537. "/api/v1/auth/status",
  9538. "/api/v1/auth/login",
  9539. "/api/v1/auth/setup", # Needed for initial setup and recovery
  9540. # Advanced auth status needed for login page
  9541. "/api/v1/auth/advanced-auth/status",
  9542. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  9543. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  9544. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  9545. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  9546. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  9547. # OIDC routes that must be reachable without a JWT
  9548. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  9549. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  9550. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  9551. # Connected apps: the app's server swaps a code for the user's identity,
  9552. # authenticated by its client secret rather than a login token.
  9553. "/api/v1/connect/token",
  9554. # Version check for updates (no sensitive data)
  9555. "/api/v1/updates/version",
  9556. # Metrics endpoint handles its own prometheus_token authentication
  9557. "/api/v1/metrics",
  9558. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  9559. # this BEFORE a JWT is available to pick up the firstboot wizard's
  9560. # hostname / timezone / locale and the chrony NTP-gate state. The
  9561. # response contains user-set defaults and a public sync flag — no
  9562. # secrets. Without this entry the global auth middleware returns 401
  9563. # before the route handler runs, regardless of the route's own
  9564. # "no auth required" intent.
  9565. "/api/v1/system/appliance",
  9566. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  9567. # authenticates with a long-lived ``camwall``-scoped token in the query
  9568. # string — exactly like the camera streams two lists below, and for the same
  9569. # reason (no header to put a JWT in). "Public" here only means the middleware
  9570. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  9571. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  9572. # plain ``camera_stream`` token does NOT open this door.
  9573. "/api/v1/camwall/printers",
  9574. # Overlay branding: the route enforces overlay-scoped token authentication.
  9575. "/api/v1/overlay-branding/logo",
  9576. }
  9577. # Route prefixes that are public (for routes with dynamic segments)
  9578. PUBLIC_API_PREFIXES = [
  9579. # WebSocket connections handle their own auth
  9580. "/api/v1/ws",
  9581. # OIDC authorize redirects — include provider_id in path
  9582. "/api/v1/auth/oidc/authorize/",
  9583. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  9584. # a phone with no session, so no header can carry a JWT — the single-use
  9585. # capability token in the path IS the credential (same reasoning as the
  9586. # /dl/ slicer downloads below). The route grants nothing beyond writing
  9587. # good/reject on the one archive the token was minted for.
  9588. "/api/v1/archives/confirm/",
  9589. ]
  9590. # Route patterns that are public (read-only display data)
  9591. # These are checked with "in path" - needed because browsers load images/videos
  9592. # via <img src> and <video src> which don't include Authorization headers
  9593. PUBLIC_API_PATTERNS = [
  9594. # Thumbnails
  9595. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  9596. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  9597. # Images and media
  9598. "/photos/", # /archives/{id}/photos/{filename}
  9599. "/project-image/", # /archives/{id}/project-image/{path}
  9600. "/qrcode", # /archives/{id}/qrcode
  9601. "/timelapse", # /archives/{id}/timelapse (video)
  9602. "/cover", # /printers/{id}/cover
  9603. "/icon", # /external-links/{id}/icon
  9604. # Camera (streams loaded via <img> tag)
  9605. "/camera/stream", # /printers/{id}/camera/stream
  9606. "/camera/snapshot", # /printers/{id}/camera/snapshot
  9607. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  9608. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  9609. # string (same reasoning as the camera streams above — no header to carry a
  9610. # JWT). "Public" only means the middleware steps aside; the route still runs
  9611. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  9612. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  9613. "/overlay-status", # /printers/{id}/overlay-status
  9614. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  9615. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  9616. # download token in the URL path instead.
  9617. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  9618. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  9619. # and these patterns match by substring. Without its own entry the middleware
  9620. # 401s the slicer's header-less request before the route's token check runs,
  9621. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  9622. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  9623. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  9624. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  9625. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  9626. ]
  9627. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  9628. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  9629. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  9630. Format: comma-separated list of ``scheme://host[:port]`` origins.
  9631. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  9632. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  9633. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  9634. Invalid entries are dropped with a warning rather than failing startup, so
  9635. a typo in one origin doesn't take the whole deployment down.
  9636. """
  9637. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  9638. if not raw:
  9639. return ()
  9640. valid: list[str] = []
  9641. for item in raw.split(","):
  9642. candidate = item.strip()
  9643. if not candidate:
  9644. continue
  9645. try:
  9646. parsed = urlparse(candidate)
  9647. except ValueError as e:
  9648. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  9649. continue
  9650. if parsed.scheme not in ("http", "https"):
  9651. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  9652. continue
  9653. if not parsed.netloc:
  9654. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  9655. continue
  9656. if parsed.path and parsed.path != "/":
  9657. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  9658. continue
  9659. if parsed.query or parsed.fragment:
  9660. _security_headers_logger.warning(
  9661. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  9662. )
  9663. continue
  9664. if "*" in parsed.netloc:
  9665. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  9666. continue
  9667. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  9668. if valid:
  9669. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  9670. return tuple(valid)
  9671. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  9672. def _frame_ancestors(default_value: str) -> str:
  9673. """Compose the ``frame-ancestors`` CSP directive (#1191).
  9674. ``default_value`` is the strict directive used when the operator has not
  9675. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  9676. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  9677. Settings URL builder's preview). When trusted origins
  9678. are configured, ``'self'`` is always included so same-origin embedding never
  9679. breaks even if an operator forgets to add their own origin to the list.
  9680. """
  9681. if _TRUSTED_FRAME_ORIGINS:
  9682. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  9683. return f"frame-ancestors {default_value};"
  9684. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  9685. # patterns are anchored on the exact emitted name so the relaxed policies
  9686. # below can never apply to any other asset.
  9687. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  9688. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  9689. # -> /assets/pdf.worker.min-<hash>.js
  9690. # Vite also emits a one-line chunk under the second name that only exports the
  9691. # worker's URL. The page imports it as a module, and a module script is run
  9692. # under the importing document's policy, never its own response's, so it
  9693. # matching as well changes nothing.
  9694. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  9695. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  9696. @app.middleware("http")
  9697. async def security_headers_middleware(request, call_next):
  9698. """Add standard HTTP security headers to every response."""
  9699. # Per-request nonce stamped into `script-src` (#1460). On its own this
  9700. # changes nothing for Bambuddy's own pages — index.html has no inline
  9701. # scripts since the SW registration moved to /sw-register.js. The reason
  9702. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  9703. # script injected into the HTML on the edge, with a fresh hash on every
  9704. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  9705. # it clones the same nonce onto its injected <script>, and the inline
  9706. # script passes the policy without us needing 'unsafe-inline'. See
  9707. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  9708. csp_nonce = secrets.token_urlsafe(16)
  9709. # Routes that render their own HTML need it too, or their inline script is
  9710. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  9711. # one that does: it submits its own form so a verdict still costs one tap.
  9712. request.state.csp_nonce = csp_nonce
  9713. response = await call_next(request)
  9714. response.headers["X-Content-Type-Options"] = "nosniff"
  9715. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  9716. # browsers honour CSP frame-ancestors instead, and the legacy
  9717. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  9718. # When operators have explicitly allowlisted trusted frame origins (#1191
  9719. # — typically Home Assistant on a different port), drop X-Frame-Options
  9720. # and let the CSP-side frame-ancestors directive govern embedding.
  9721. if not _TRUSTED_FRAME_ORIGINS:
  9722. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  9723. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  9724. # Content-Security-Policy for the React SPA.
  9725. # Notes:
  9726. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  9727. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  9728. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  9729. # - media-src blob:: timelapse video player uses Blob URLs.
  9730. # - font-src data:: some icon fonts are embedded as data URIs.
  9731. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  9732. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  9733. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  9734. # default CSP would render a blank page.
  9735. response.headers["Content-Security-Policy"] = (
  9736. "default-src 'self'; "
  9737. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  9738. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  9739. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  9740. "connect-src 'self'; "
  9741. "font-src 'self' data: https://fonts.gstatic.com; "
  9742. "worker-src 'self' blob:; "
  9743. "object-src 'none'; "
  9744. "base-uri 'self'; " + _frame_ancestors("'none'")
  9745. )
  9746. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  9747. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  9748. # its emscripten/embind glue generates invoker functions with `new
  9749. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  9750. # worker is governed by the policy delivered with the WORKER SCRIPT's
  9751. # own response — not the document's — so relaxing it here confines
  9752. # eval to that DOM-less worker context. The document policy below
  9753. # stays nonce-strict, and this response header has no effect when the
  9754. # file is merely fetched (a fetch's CSP is enforced against the
  9755. # requesting document, not the resource's own headers).
  9756. response.headers["Content-Security-Policy"] = (
  9757. "default-src 'self'; "
  9758. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  9759. "connect-src 'self'; "
  9760. "object-src 'none'; "
  9761. "base-uri 'self'; " + _frame_ancestors("'none'")
  9762. )
  9763. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  9764. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  9765. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  9766. # rule as the STEP worker above: the policy that governs a dedicated
  9767. # worker is the one delivered with its own script, so the wasm compile
  9768. # has to be permitted here rather than on the document. Unlike the STEP
  9769. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  9770. response.headers["Content-Security-Policy"] = (
  9771. "default-src 'self'; "
  9772. "script-src 'self' 'wasm-unsafe-eval'; "
  9773. "connect-src 'self'; "
  9774. "object-src 'none'; "
  9775. "base-uri 'self'; " + _frame_ancestors("'none'")
  9776. )
  9777. else:
  9778. # The streaming overlay is embedded same-origin by the URL builder's
  9779. # preview in Settings (#1422), so this branch allows 'self'.
  9780. # Embedding from anywhere else is still refused: 'self'
  9781. # only permits a framer on this origin, which is Bambuddy's own UI, so
  9782. # a clickjacking page on another host is blocked exactly as before.
  9783. # (The overlay draws status over a camera feed and its only interactive
  9784. # element is the logo link, so there is nothing to bait a click into
  9785. # even from a same-origin framer.) Cross-origin embedding of the
  9786. # overlay — Home Assistant on another port — remains what
  9787. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  9788. # allowlist in.
  9789. #
  9790. # The connected-app consent page (/connect/authorize) gets the same
  9791. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  9792. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  9793. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  9794. # requires every ancestor to be this origin, so a foreign page -- a
  9795. # sidebar link's site included -- still cannot frame the consent
  9796. # screen to bait a click.
  9797. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  9798. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  9799. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  9800. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  9801. # the policy served with their own script, so each gets it in its own
  9802. # branch above and the document policy stays as strict as it was.
  9803. response.headers["Content-Security-Policy"] = (
  9804. "default-src 'self'; "
  9805. f"script-src 'self' 'nonce-{csp_nonce}'; "
  9806. "style-src 'self' 'unsafe-inline'; "
  9807. "img-src 'self' data: blob:; "
  9808. "media-src 'self' blob:; "
  9809. "connect-src 'self' ws: wss:; "
  9810. "font-src 'self' data:; "
  9811. "object-src 'none'; "
  9812. "base-uri 'self'; "
  9813. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  9814. )
  9815. if request.url.scheme == "https":
  9816. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  9817. return response
  9818. @app.middleware("http")
  9819. async def auth_middleware(request, call_next):
  9820. """Enforce authentication on all API routes when auth is enabled.
  9821. This middleware provides defense-in-depth by checking auth at the API gateway level,
  9822. regardless of whether individual routes have auth dependencies.
  9823. """
  9824. from starlette.responses import JSONResponse
  9825. path = request.url.path
  9826. # Only apply to API routes
  9827. if not path.startswith("/api/"):
  9828. return await call_next(request)
  9829. # Allow public routes
  9830. if path in PUBLIC_API_ROUTES:
  9831. return await call_next(request)
  9832. # Allow public prefixes
  9833. for prefix in PUBLIC_API_PREFIXES:
  9834. if path.startswith(prefix):
  9835. return await call_next(request)
  9836. # Allow public patterns (read-only display data like thumbnails)
  9837. for pattern in PUBLIC_API_PATTERNS:
  9838. if pattern in path:
  9839. return await call_next(request)
  9840. # Check if auth is enabled. Fail CLOSED on any exception during the
  9841. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  9842. # an attacker who could force a DB exception (e.g. file-descriptor
  9843. # exhaustion via login flood) bypass auth on every protected endpoint.
  9844. # Only the probe is guarded: the request itself runs outside the try, so an
  9845. # error in a route surfaces as the 500 it is rather than as an auth outage.
  9846. try:
  9847. async with async_session() as db:
  9848. from backend.app.core.auth import is_auth_enabled
  9849. auth_enabled = await is_auth_enabled(db)
  9850. except Exception:
  9851. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  9852. return JSONResponse(
  9853. status_code=503,
  9854. content={"detail": "Authentication service temporarily unavailable"},
  9855. )
  9856. if not auth_enabled:
  9857. # Auth disabled, allow all requests
  9858. return await call_next(request)
  9859. # Auth is enabled - require valid token
  9860. auth_header = request.headers.get("Authorization")
  9861. x_api_key = request.headers.get("X-API-Key")
  9862. # Check for API key auth first
  9863. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  9864. # API key authentication - let the request through to be validated by route handler
  9865. # API keys are validated per-route since they have different permission levels
  9866. return await call_next(request)
  9867. # Check for JWT auth
  9868. if not auth_header or not auth_header.startswith("Bearer "):
  9869. return JSONResponse(
  9870. status_code=401,
  9871. content={"detail": "Authentication required"},
  9872. headers={"WWW-Authenticate": "Bearer"},
  9873. )
  9874. # Validate JWT token
  9875. import jwt
  9876. try:
  9877. from backend.app.core.auth import (
  9878. ALGORITHM,
  9879. SECRET_KEY,
  9880. _is_token_fresh,
  9881. get_user_by_username,
  9882. is_jti_revoked,
  9883. )
  9884. token = auth_header.replace("Bearer ", "")
  9885. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  9886. username = payload.get("sub")
  9887. if not username:
  9888. raise ValueError("No username in token")
  9889. jti = payload.get("jti")
  9890. if not jti:
  9891. raise ValueError("No jti in token")
  9892. iat = payload.get("iat")
  9893. # Verify user exists, is active, and token is still fresh (L-R8-A).
  9894. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  9895. # this session so the gateway adds a single pooled checkout, not two (#2572).
  9896. async with async_session() as db:
  9897. if await is_jti_revoked(jti, db):
  9898. return JSONResponse(
  9899. status_code=401,
  9900. content={"detail": "Token has been revoked"},
  9901. headers={"WWW-Authenticate": "Bearer"},
  9902. )
  9903. user = await get_user_by_username(db, username)
  9904. if not user or not user.is_active:
  9905. return JSONResponse(
  9906. status_code=401,
  9907. content={"detail": "User not found or inactive"},
  9908. headers={"WWW-Authenticate": "Bearer"},
  9909. )
  9910. if not _is_token_fresh(iat, user):
  9911. return JSONResponse(
  9912. status_code=401,
  9913. content={"detail": "Token no longer valid"},
  9914. headers={"WWW-Authenticate": "Bearer"},
  9915. )
  9916. except jwt.ExpiredSignatureError:
  9917. return JSONResponse(
  9918. status_code=401,
  9919. content={"detail": "Token has expired"},
  9920. headers={"WWW-Authenticate": "Bearer"},
  9921. )
  9922. except (jwt.InvalidTokenError, ValueError):
  9923. return JSONResponse(
  9924. status_code=401,
  9925. content={"detail": "Invalid token"},
  9926. headers={"WWW-Authenticate": "Bearer"},
  9927. )
  9928. except Exception:
  9929. # Not a bad token but a failure checking it (database, pool): refuse,
  9930. # as for the probe above, rather than answer 401 -- the frontend reads
  9931. # a 401 from /auth/me as final and signs the user out.
  9932. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  9933. return JSONResponse(
  9934. status_code=503,
  9935. content={"detail": "Authentication service temporarily unavailable"},
  9936. )
  9937. return await call_next(request)
  9938. @app.middleware("http")
  9939. async def trace_id_middleware(request, call_next):
  9940. """Stamp every HTTP request with a trace ID and echo it back.
  9941. Decorated AFTER auth_middleware on purpose: Starlette stacks
  9942. @app.middleware decorators LIFO, so the last-decorated runs first
  9943. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  9944. which means auth-middleware log lines (and every line emitted on the
  9945. way down to and back from the route handler) all carry the same
  9946. trace ID. If we put it before auth, auth's logs would be stamped
  9947. with the *previous* request's ID — useless for correlation.
  9948. Honours an inbound ``X-Trace-Id`` header so callers running their
  9949. own tracing can correlate their span IDs with our log lines, but
  9950. only if the value passes the whitelist gate in
  9951. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  9952. rejected (too long, contains control chars, etc.) silently triggers
  9953. a freshly minted server-side ID rather than failing the request.
  9954. The minted (or echoed) ID is set on a ContextVar so that every log
  9955. record emitted during the request — application logs *and* uvicorn's
  9956. access log — carries it via TraceIDFilter, and is also written to
  9957. the ``X-Trace-Id`` response header so clients can pin a server-side
  9958. log search to the exact request they made.
  9959. """
  9960. from backend.app.core.trace import (
  9961. generate_trace_id,
  9962. normalise_inbound_trace_id,
  9963. trace_id_var,
  9964. )
  9965. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  9966. trace_id = inbound if inbound is not None else generate_trace_id()
  9967. token = trace_id_var.set(trace_id)
  9968. try:
  9969. response = await call_next(request)
  9970. finally:
  9971. # Reset the ContextVar so a record emitted in a totally
  9972. # unrelated background task that just happens to inherit this
  9973. # context doesn't keep referencing this request's ID forever.
  9974. # In practice ContextVar.reset is best-effort under asyncio
  9975. # task-spawn semantics, but the cost is one attribute write so
  9976. # we may as well do it.
  9977. trace_id_var.reset(token)
  9978. response.headers["X-Trace-Id"] = trace_id
  9979. return response
  9980. # API routes
  9981. app.include_router(auth.router, prefix=app_settings.api_prefix)
  9982. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  9983. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  9984. app.include_router(users.router, prefix=app_settings.api_prefix)
  9985. app.include_router(groups.router, prefix=app_settings.api_prefix)
  9986. app.include_router(printers.router, prefix=app_settings.api_prefix)
  9987. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  9988. app.include_router(archives.router, prefix=app_settings.api_prefix)
  9989. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  9990. app.include_router(finance.router, prefix=app_settings.api_prefix)
  9991. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  9992. app.include_router(labels.router, prefix=app_settings.api_prefix)
  9993. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  9994. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  9995. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  9996. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  9997. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  9998. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  9999. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  10000. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  10001. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  10002. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  10003. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  10004. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  10005. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  10006. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  10007. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  10008. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  10009. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  10010. app.include_router(updates.router, prefix=app_settings.api_prefix)
  10011. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  10012. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  10013. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  10014. app.include_router(camera.router, prefix=app_settings.api_prefix)
  10015. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  10016. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  10017. app.include_router(projects.router, prefix=app_settings.api_prefix)
  10018. app.include_router(library.router, prefix=app_settings.api_prefix)
  10019. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  10020. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  10021. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  10022. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  10023. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  10024. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  10025. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  10026. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  10027. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  10028. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  10029. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  10030. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  10031. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  10032. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  10033. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  10034. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  10035. app.include_router(system.router, prefix=app_settings.api_prefix)
  10036. app.include_router(support.router, prefix=app_settings.api_prefix)
  10037. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  10038. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  10039. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  10040. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  10041. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  10042. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  10043. app.include_router(obico.router, prefix=app_settings.api_prefix)
  10044. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  10045. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  10046. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  10047. # Serve static files (React build)
  10048. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  10049. # Compressed, and cached for good where Vite hashed the name (#3175).
  10050. app.mount(
  10051. "/assets",
  10052. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  10053. name="assets",
  10054. )
  10055. if (app_settings.static_dir / "img").exists():
  10056. app.mount(
  10057. "/img",
  10058. StaticFiles(directory=app_settings.static_dir / "img"),
  10059. name="img",
  10060. )
  10061. if (app_settings.static_dir / "icons").exists():
  10062. app.mount(
  10063. "/icons",
  10064. StaticFiles(directory=app_settings.static_dir / "icons"),
  10065. name="icons",
  10066. )
  10067. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  10068. # falls through to the SPA catch-all and returns index.html, which the
  10069. # browser's font sanitizer rejects ("downloadable font: rejected by
  10070. # sanitizer").
  10071. if (app_settings.static_dir / "fonts").exists():
  10072. app.mount(
  10073. "/fonts",
  10074. StaticFiles(directory=app_settings.static_dir / "fonts"),
  10075. name="fonts",
  10076. )
  10077. @app.get("/")
  10078. async def serve_frontend():
  10079. """Serve the React frontend."""
  10080. index_file = app_settings.static_dir / "index.html"
  10081. if index_file.exists():
  10082. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10083. return {
  10084. "message": "Bambuddy API",
  10085. "docs": "/docs",
  10086. "frontend": "Build and place React app in /static directory",
  10087. }
  10088. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  10089. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  10090. # forever, but the HTML wrapping it is the only file that knows which hash
  10091. # is current. Without explicit cache-control headers Chromium decides
  10092. # heuristically (typically 10% of the time since Last-Modified) and on
  10093. # long-running kiosks happily serves stale HTML across browser restarts.
  10094. # That stale HTML references an old bundle hash, the old bundle is also
  10095. # in the disk cache, and the user ends up running pre-update JS forever
  10096. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  10097. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  10098. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  10099. @app.get("/health")
  10100. async def health_check():
  10101. """Health check endpoint."""
  10102. return {"status": "healthy"}
  10103. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  10104. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  10105. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  10106. # in deployment debugging.
  10107. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  10108. async def serve_manifest():
  10109. """Serve PWA manifest."""
  10110. manifest_file = app_settings.static_dir / "manifest.json"
  10111. if manifest_file.exists():
  10112. return FileResponse(manifest_file, media_type="application/manifest+json")
  10113. return {"error": "Manifest not found"}
  10114. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  10115. async def serve_service_worker():
  10116. """Serve service worker."""
  10117. sw_file = app_settings.static_dir / "sw.js"
  10118. if sw_file.exists():
  10119. return FileResponse(
  10120. sw_file,
  10121. media_type="application/javascript",
  10122. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  10123. )
  10124. return {"error": "Service worker not found"}
  10125. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  10126. async def serve_sw_register():
  10127. """Serve the service-worker registration bootstrap script.
  10128. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  10129. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  10130. """
  10131. reg_file = app_settings.static_dir / "sw-register.js"
  10132. if reg_file.exists():
  10133. return FileResponse(reg_file, media_type="application/javascript")
  10134. return {"error": "sw-register.js not found"}
  10135. # ── GCode viewer static files ────────────────────────────────────────────────
  10136. # Catch-all route for React Router (must be last)
  10137. @app.get("/{full_path:path}")
  10138. async def serve_spa(full_path: str):
  10139. """Serve React app for client-side routing."""
  10140. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  10141. if full_path.startswith("api/"):
  10142. from fastapi import HTTPException
  10143. raise HTTPException(status_code=404, detail="Not found")
  10144. index_file = app_settings.static_dir / "index.html"
  10145. if index_file.exists():
  10146. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10147. return {"error": "Frontend not built"}