main.py 623 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860
  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 shutil
  10. import time
  11. from contextlib import asynccontextmanager
  12. from datetime import datetime, timedelta, timezone
  13. from logging.handlers import RotatingFileHandler
  14. from pathlib import Path, PurePosixPath
  15. from typing import cast
  16. from urllib.parse import urlparse
  17. from fastapi import FastAPI
  18. from fastapi.encoders import jsonable_encoder
  19. from fastapi.exceptions import RequestValidationError
  20. from fastapi.responses import FileResponse, JSONResponse
  21. from fastapi.staticfiles import StaticFiles
  22. from sqlalchemy import delete, func, inspect as sa_inspect, or_, select, text, update
  23. from sqlalchemy.engine import CursorResult
  24. from sqlalchemy.exc import IntegrityError
  25. from sqlalchemy.orm.exc import StaleDataError
  26. from backend.app.api.routes import (
  27. ams_history,
  28. announcements,
  29. api_keys,
  30. archive_purge,
  31. archives,
  32. auth,
  33. bug_report,
  34. bulk,
  35. camera,
  36. camwall,
  37. cloud,
  38. connected_apps,
  39. discovery,
  40. external_links,
  41. filaments,
  42. finance,
  43. firmware,
  44. github_backup,
  45. groups,
  46. ha_sensors,
  47. inventory,
  48. kprofiles,
  49. labels,
  50. library,
  51. library_tags,
  52. library_trash,
  53. library_variants,
  54. local_backup,
  55. local_presets,
  56. location_ha_sensors,
  57. maintenance,
  58. makerworld,
  59. manyfold,
  60. metrics,
  61. mfa,
  62. notification_templates,
  63. notifications,
  64. obico,
  65. orca_cloud,
  66. overlay_branding,
  67. pending_uploads,
  68. pipeline_runs,
  69. print_log,
  70. print_queue,
  71. printer_locations,
  72. printer_sensor_history,
  73. printers,
  74. projects,
  75. scheduled_dryings,
  76. settings as settings_routes,
  77. slice_jobs,
  78. slicer_pipelines,
  79. slicer_presets,
  80. smart_plugs,
  81. sponsor_prompt,
  82. spoolbuddy,
  83. spoolman,
  84. spoolman_inventory,
  85. support,
  86. system,
  87. updates,
  88. user_notifications,
  89. users,
  90. virtual_printers,
  91. webhook,
  92. websocket,
  93. )
  94. from backend.app.api.routes.maintenance import (
  95. _get_printer_maintenance_internal,
  96. ensure_default_types,
  97. maintenance_alert_values,
  98. )
  99. from backend.app.api.routes.support import init_debug_logging
  100. from backend.app.core.config import APP_VERSION, settings as app_settings
  101. from backend.app.core.database import async_session, engine, init_db
  102. from backend.app.core.static_assets import AssetStaticFiles
  103. from backend.app.core.tasks import spawn_background_task
  104. from backend.app.core.websocket import ws_manager
  105. from backend.app.services import kprofile_drift, pause_eta, print_dispatch_context, slot_unlink_grace
  106. from backend.app.services.ams_assignment_lock import get_ams_assignment_lock
  107. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  108. from backend.app.services.archive_cost_estimate import (
  109. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  110. settle_archive_cost_estimate as _settle_archive_cost_estimate,
  111. )
  112. from backend.app.services.archive_purge import archive_purge_service
  113. from backend.app.services.bambu_ftp import (
  114. RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  115. FileNotOnPrinterError,
  116. cache_3mf_download,
  117. clear_3mf_cache,
  118. download_file_async,
  119. download_file_try_paths_async,
  120. ftps_handshake_blocked,
  121. get_cached_3mf,
  122. get_ftp_retry_settings,
  123. normalize_3mf_name,
  124. with_ftp_retry,
  125. )
  126. from backend.app.services.bambu_mqtt import PrinterState
  127. from backend.app.services.camera_light import camera_light
  128. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  129. from backend.app.services.github_backup import github_backup_service
  130. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  131. from backend.app.services.library_trash import library_trash_service
  132. from backend.app.services.local_backup import local_backup_service
  133. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  134. from backend.app.services.mqtt_relay import mqtt_relay
  135. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  136. from backend.app.services.notification_service import notification_service
  137. from backend.app.services.notify_live_activities import notify_live_activities
  138. from backend.app.services.notify_widgets import notify_widgets
  139. from backend.app.services.obico_detection import obico_detection_service
  140. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  141. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  142. from backend.app.services.print_scheduler import scheduler as print_scheduler
  143. from backend.app.services.print_storage import (
  144. REASON_FTP_TRANSFER_FAILED,
  145. REASON_FTPS_COOLOFF,
  146. external_storage_present,
  147. ftp_probe_paths,
  148. print_file_reachable_over_ftp,
  149. )
  150. from backend.app.services.printer_manager import (
  151. init_printer_connections,
  152. parse_plate_id,
  153. printer_manager,
  154. printer_state_to_dict,
  155. resolve_plate_id,
  156. )
  157. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  158. from backend.app.services.slot_nozzle import (
  159. nozzle_diameter_for_extruder,
  160. nozzle_flow_for_extruder,
  161. )
  162. from backend.app.services.smart_plug_manager import smart_plug_manager
  163. from backend.app.services.spool_assignment_notifications import (
  164. notify_missing_spool_assignments_on_print_start,
  165. )
  166. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  167. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  168. from backend.app.services.spoolman_tracking import (
  169. cleanup_tracking as _cleanup_spoolman_tracking,
  170. release_archived_slot_rows as _release_archived_spoolman_slots,
  171. report_usage as _report_spoolman_usage,
  172. store_print_data as _store_spoolman_print_data,
  173. )
  174. from backend.app.services.telegram_reactions import telegram_reaction_poller
  175. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  176. from backend.app.utils.ams_humidity import ams_humidity_percent
  177. from backend.app.utils.filament_types import printer_filament_type
  178. from backend.app.utils.fts_routing import extruder_for_inlet
  179. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  180. from backend.app.utils.print_jobs import is_internal_printer_job
  181. # =============================================================================
  182. # Dependency Check - runs before other imports to give helpful error messages
  183. # =============================================================================
  184. def _start_error_server(missing_packages: list):
  185. """Start a minimal HTTP server to display dependency errors in browser."""
  186. import os
  187. import signal
  188. from http.server import BaseHTTPRequestHandler, HTTPServer
  189. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  190. html = f"""<!DOCTYPE html>
  191. <html>
  192. <head>
  193. <title>Bambuddy - Setup Required</title>
  194. <style>
  195. body {{
  196. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  197. background: #0f172a; color: #e2e8f0;
  198. display: flex; justify-content: center; align-items: center;
  199. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  200. }}
  201. .container {{
  202. background: #1e293b; border-radius: 12px; padding: 40px;
  203. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  204. }}
  205. h1 {{ color: #f87171; margin-bottom: 10px; }}
  206. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  207. .packages {{
  208. background: #0f172a; border-radius: 8px; padding: 20px;
  209. margin: 20px 0; text-align: left;
  210. }}
  211. .packages ul {{ margin: 0; padding-left: 20px; }}
  212. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  213. .command {{
  214. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  215. margin: 15px 0; font-family: monospace; color: #4ade80;
  216. text-align: left; overflow-x: auto;
  217. }}
  218. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  219. </style>
  220. </head>
  221. <body>
  222. <div class="container">
  223. <h1>Setup Required</h1>
  224. <h2>Missing Python packages</h2>
  225. <div class="packages"><ul>{packages_html}</ul></div>
  226. <p>To fix, run this command on your server:</p>
  227. <div class="command">pip install -r requirements.lock</div>
  228. <p>Or if using a virtual environment:</p>
  229. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  230. <p class="note">After installing, restart Bambuddy:<br>
  231. <code>sudo systemctl restart bambuddy</code></p>
  232. </div>
  233. </body>
  234. </html>"""
  235. class ErrorHandler(BaseHTTPRequestHandler):
  236. def do_GET(self):
  237. self.send_response(503)
  238. self.send_header("Content-type", "text/html")
  239. self.end_headers()
  240. self.wfile.write(html.encode())
  241. def log_message(self, format, *args):
  242. print(f"[Error Server] {args[0]}")
  243. port = int(os.environ.get("PORT", 8000))
  244. print(f"\nStarting error server on http://0.0.0.0:{port}")
  245. print("Visit this URL in your browser to see the error details.\n")
  246. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  247. def shutdown(signum, frame):
  248. print("\nShutting down error server...")
  249. raise SystemExit(0)
  250. signal.signal(signal.SIGTERM, shutdown)
  251. signal.signal(signal.SIGINT, shutdown)
  252. server.serve_forever()
  253. def check_dependencies():
  254. """Check that all required packages are installed."""
  255. missing = []
  256. # Map of import name -> package name (for pip install)
  257. required = {
  258. "jwt": "PyJWT",
  259. "fastapi": "fastapi",
  260. "uvicorn": "uvicorn",
  261. "sqlalchemy": "sqlalchemy",
  262. "aiosqlite": "aiosqlite",
  263. "pydantic": "pydantic",
  264. "paho.mqtt": "paho-mqtt",
  265. }
  266. for module, package in required.items():
  267. try:
  268. __import__(module)
  269. except ImportError:
  270. missing.append(package)
  271. if missing:
  272. print("\n" + "=" * 60)
  273. print("ERROR: Missing required Python packages!")
  274. print("=" * 60)
  275. print(f"\nMissing packages: {', '.join(missing)}")
  276. print("\nTo fix, run:")
  277. print(" pip install -r requirements.lock")
  278. print("\nOr if using a virtual environment:")
  279. print(" ./venv/bin/pip install -r requirements.lock")
  280. print("=" * 60 + "\n")
  281. _start_error_server(missing)
  282. check_dependencies()
  283. # =============================================================================
  284. # Import settings first for logging configuration
  285. # Configure logging based on settings
  286. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  287. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  288. log_level = getattr(logging, log_level_str, logging.INFO)
  289. # Trace ID column ([-] when no request scope is active — startup, MQTT
  290. # callbacks, scheduled tasks not chained from a request — so the column
  291. # stays visually aligned and missing values are obvious in grep). See
  292. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  293. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  294. # Create root logger
  295. root_logger = logging.getLogger()
  296. root_logger.setLevel(log_level)
  297. # Trace-ID injection: this filter populates record.trace_id from the
  298. # per-request ContextVar so the format string above can reference it.
  299. # Attached to each HANDLER (not the root logger) because Python's
  300. # logging semantics only invoke a logger's filters on records that
  301. # *originated* at that logger — records propagated up from child
  302. # loggers (every named logger in the app) never trigger root's filter.
  303. # Putting it on the handlers means every record any handler emits gets
  304. # trace_id injected just before the formatter runs, regardless of which
  305. # logger created the record. Without this, the formatter raises
  306. # KeyError on every child-logger record and the record is silently
  307. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  308. # partially" bug we hit. See backend/app/core/trace.py for the
  309. # ContextVar the filter reads.
  310. from backend.app.core.logging_filters import RefusedHeaderRedactFilter
  311. from backend.app.core.response_redaction import RefusedHeaderResponseMask
  312. from backend.app.core.trace import TraceIDFilter
  313. _trace_id_filter = TraceIDFilter()
  314. # Console handler - always enabled
  315. console_handler = logging.StreamHandler()
  316. console_handler.setLevel(log_level)
  317. console_handler.setFormatter(logging.Formatter(log_format))
  318. console_handler.addFilter(_trace_id_filter)
  319. # A refused header's value (often a token) masked before the line is written.
  320. _refused_header_filter = RefusedHeaderRedactFilter()
  321. console_handler.addFilter(_refused_header_filter)
  322. root_logger.addHandler(console_handler)
  323. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  324. """Send uvicorn's own loggers to bambuddy.log as well.
  325. Neither reaches the root handler: uvicorn.access has propagate=False, and
  326. uvicorn.error propagates only to "uvicorn", which has propagate=False.
  327. uvicorn.access is the record of which endpoint changed server state;
  328. uvicorn.error is where an unhandled route error is logged with its
  329. traceback ("Exception in ASGI application").
  330. """
  331. for name in ("uvicorn.access", "uvicorn.error"):
  332. logging.getLogger(name).addHandler(handler)
  333. # File handler - only in production or if explicitly enabled
  334. if app_settings.log_to_file:
  335. log_file = app_settings.log_dir / "bambuddy.log"
  336. file_handler = RotatingFileHandler(
  337. log_file,
  338. maxBytes=app_settings.log_max_bytes,
  339. backupCount=app_settings.log_backup_count,
  340. encoding="utf-8",
  341. )
  342. file_handler.setLevel(log_level)
  343. file_handler.setFormatter(logging.Formatter(log_format))
  344. file_handler.addFilter(_trace_id_filter)
  345. file_handler.addFilter(_refused_header_filter)
  346. root_logger.addHandler(file_handler)
  347. logging.info("Logging to file: %s", log_file)
  348. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  349. # access logger with propagate=False by default, so without this attach
  350. # there is no on-disk record of which endpoint triggered a server-state
  351. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  352. # for exactly this reason. Filtered to write methods only
  353. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  354. # frontend don't churn the rotation window faster than it's useful.
  355. from backend.app.core.logging_filters import (
  356. CancelledPoolNoiseFilter,
  357. WriteRequestsOnlyFilter,
  358. )
  359. _attach_file_handler_to_uvicorn(file_handler)
  360. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  361. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  362. # Uvicorn's access logger has propagate=False (its own default), so the
  363. # root-attached TraceIDFilter never sees these records. Attach a
  364. # second instance directly so HTTP access lines carry the same trace
  365. # ID column as the application logs they correlate with.
  366. uvicorn_access_logger.addFilter(TraceIDFilter())
  367. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  368. # BaseHTTPMiddleware cancelling the inner task scope on client
  369. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  370. # underlying transaction leak; this filter only suppresses the residual
  371. # log records that pre-existing pools still emit during their cleanup.
  372. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  373. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  374. # handler (console included), whether or not file logging is on.
  375. from backend.app.core.logging_filters import ( # noqa: E402
  376. QueryTokenRedactFilter,
  377. ShutdownCancelledRequestFilter,
  378. )
  379. # First, so the traceback of a stream cancelled at shutdown is dropped before
  380. # the filters below render it.
  381. logging.getLogger("uvicorn.error").addFilter(ShutdownCancelledRequestFilter())
  382. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  383. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  384. logging.getLogger(_uvicorn_logger).addFilter(_refused_header_filter)
  385. # These stay at WARNING even in debug mode: at INFO/DEBUG httpx/httpcore log
  386. # full request URLs, and some carry credentials (bot tokens, webhook URLs, API
  387. # keys in the query). Same as the runtime log-level toggle in support.py.
  388. logging.getLogger("httpcore").setLevel(logging.WARNING)
  389. logging.getLogger("httpx").setLevel(logging.WARNING)
  390. # aiosqlite logs every statement with its parameters at DEBUG.
  391. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  392. # Reduce noise from third-party libraries in production
  393. if not app_settings.debug:
  394. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  395. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  396. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  397. # Track active prints: {(printer_id, filename): archive_id}
  398. _active_prints: dict[tuple[int, str], int] = {}
  399. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  400. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  401. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  402. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  403. # instead of running its own grab-now chain when present, so the finish photo
  404. # captures the better-framed pre-bed-drop moment without us having to force
  405. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  406. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  407. #
  408. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  409. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  410. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  411. # bank and the others are not — so the consumer can't tell them apart and
  412. # must not rotate again.
  413. _stage22_finish_frames: dict[int, bytes] = {}
  414. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  415. # `finally` block (whether it captured a frame or not). The consumer in
  416. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  417. # so the FINISH-state fallback path — where moment and completion are dispatched
  418. # back-to-back — doesn't race past the producer with an empty pop, and the
  419. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  420. # grab (Bambu printers allow only one RTSP client at a time).
  421. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  422. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  423. # layer-change and on print-progress advances (#2547) while the model is still
  424. # printing, then consumed by the FINISH-state finish-photo path when the
  425. # dispatcher recorded that it injected End G-code into this print. Bambu
  426. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  427. # plate-swap) has run, so a live grab there would capture the swapped/empty
  428. # plate.
  429. #
  430. # The load-bearing property: both drivers are print telemetry that stops before
  431. # the End G-code executes — no further layer_num increases, and mc_percent
  432. # freezes — so the last banked frame is always the finished print before the
  433. # swap. Anything added as a third driver must hold that same property.
  434. _inprint_frame_bank: dict[int, bytes] = {}
  435. # Monotonic timestamp of the last banked frame per printer — throttles banking
  436. # so tall prints don't add a camera grab on every layer.
  437. _inprint_frame_bank_ts: dict[int, float] = {}
  438. # Minimum seconds between banked frames, except the final object layer which
  439. # always refreshes for the best framing.
  440. _INPRINT_BANK_MIN_INTERVAL = 25.0
  441. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  442. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  443. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  444. # the first connected status update for that connection; transitions back
  445. # to False whenever we observe `state.connected = False` so the next
  446. # reconnect re-arms reconciliation. Keyed by printer_id.
  447. _printer_reconciled_since_connect: dict[int, bool] = {}
  448. # Same edge, same keying, for priming the printer's calibration table exactly
  449. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  450. # is otherwise filled only when someone opens the Profiles page or Configure
  451. # Slot, when a GitHub backup runs, or when the printer happens to answer
  452. # somebody else's query on the report topic. Until then the AMS slot card has
  453. # no K value to show on the printers whose trays carry none of their own
  454. # (#2854 — H2-series report cali_idx and nothing more).
  455. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  456. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  457. # {(printer_id, filename): archive_id}
  458. _expected_prints: dict[tuple[int, str], int] = {}
  459. # Archives of the running prints Bambuddy dispatched itself: adopted from an
  460. # expected print, or found with Bambuddy's dispatch marker. _active_prints holds
  461. # every print on_print_start archived, those started from Bambu Studio, Handy or
  462. # the printer's screen included, so it is no proof of ownership on its own.
  463. _owned_print_archive_ids: set[int] = set()
  464. # What a dispatch registered for its print, keyed (printer_id, archive_id):
  465. # plates of one archive print on two printers at once, each with its own.
  466. # Track AMS mapping for prints: {(printer_id, archive_id): [global_tray_id_per_slot]}
  467. # Used by usage tracker to map 3MF slots to physical AMS trays
  468. _print_ams_mappings: dict[tuple[int, int], list[int]] = {}
  469. # Track cost center selection for the current print run: {(printer_id, archive_id): cost_center_id}
  470. _print_cost_center_ids: dict[tuple[int, int], int] = {}
  471. # Track plate_id for prints from multi-plate 3MFs: {(printer_id, archive_id): plate_id}
  472. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  473. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  474. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  475. # for the queue path. Cleared on print completion or TTL eviction.
  476. _print_plate_ids: dict[tuple[int, int], int] = {}
  477. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  478. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  479. _last_progress_milestone: dict[int, int] = {}
  480. # Track whether first layer complete notification has been sent for current print
  481. _first_layer_notified: dict[int, bool] = {}
  482. # Track whether we already sent a kill-switch stop for the current unauthorized print
  483. _unauthorized_print_kill_sent: set[int] = set()
  484. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  485. # lookup briefly so an unknown active print does not query the database on
  486. # every status frame. A short TTL keeps settings changes responsive.
  487. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  488. _kill_switch_setting_cache: tuple[bool, float] | None = None
  489. # Provider notification started when the kill switch stops a print. The later
  490. # MQTT print-complete callback awaits this task and only sends its regular
  491. # provider notification when the immediate attempt failed.
  492. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  493. # HMS faults already notified, with when each was last seen:
  494. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  495. # fault that flickers beside a held notice was forgotten on every gap and
  496. # notified on every return (#3226). The window is long because the measured
  497. # gaps reach 64 s.
  498. _notified_hms_errors: dict[int, dict[str, float]] = {}
  499. _HMS_CLEAR_GRACE_SECONDS = 600.0
  500. # The print state each printer was last seen in, and the faults recorded before
  501. # it last changed, which are forgotten as soon as they are gone (see
  502. # _take_new_hms_faults).
  503. _hms_print_state: dict[int, str] = {}
  504. _hms_forget_when_gone: dict[int, set[str]] = {}
  505. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  506. # Used for snapshot-diff detection at print completion
  507. _timelapse_baselines: dict[int, set[str]] = {}
  508. # Printers whose baseline above was taken off a card that could not be read,
  509. # so it is empty without the card being empty (#3412).
  510. _timelapse_baselines_unread: set[int] = set()
  511. # Archives whose last run still has work after it completed: the timelapse
  512. # scan and the layer timelapse stitch. Both tell their run from a later one by
  513. # the archive's start time, so a queue dispatch of the same file must not start
  514. # a new run on the archive until they end (_claim_reusable_archive in the
  515. # scheduler). archive_id -> number of such tasks.
  516. _archive_runs_finishing: dict[int, int] = {}
  517. async def _while_run_finishes(archive_id: int, work):
  518. """Run ``work`` with the archive marked as still finishing its last run.
  519. Marked by the caller's spawn already: see ``_mark_run_finishing``."""
  520. try:
  521. return await work
  522. finally:
  523. left = _archive_runs_finishing.get(archive_id, 0) - 1
  524. if left > 0:
  525. _archive_runs_finishing[archive_id] = left
  526. else:
  527. _archive_runs_finishing.pop(archive_id, None)
  528. def _mark_run_finishing(archive_id: int, work):
  529. """``work`` wrapped to keep the archive marked until it ends. Marked now,
  530. before the task starts, so no dispatch between the spawn and its first
  531. step can take the archive."""
  532. _archive_runs_finishing[archive_id] = _archive_runs_finishing.get(archive_id, 0) + 1
  533. return _while_run_finishes(archive_id, work)
  534. # Track printers waiting for bed to cool after print completion.
  535. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  536. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  537. _bed_cool_waiters: dict[int, dict] = {}
  538. # Track printers where the user explicitly stopped the print from the queue UI.
  539. # When on_print_complete fires with status "failed" for these printers we treat it
  540. # as "cancelled" (stopped by user) so the correct notification email is sent.
  541. _user_stopped_printers: set[int] = set()
  542. # Printers whose running print the kill switch stopped. Their completion is a
  543. # cancel with the reason "killSwitch", not the "failed" the printer reports.
  544. _kill_switch_stopped: set[int] = set()
  545. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  546. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  547. # holds the previous observation so we only fire on the True → False edge (a
  548. # False → False repeat doesn't notify; an initial False at startup doesn't
  549. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  550. # holds the per-printer pending asyncio task that fires the notification
  551. # after a debounce window — cancelled if the printer reconnects before the
  552. # window elapses, so transient MQTT blips don't flood the user.
  553. _printer_last_connected: dict[int, bool] = {}
  554. # Printers whose relay offline event went out, so the reconnect publishes the
  555. # matching online event and a blip shorter than the debounce publishes neither.
  556. _printer_offline_published: set[int] = set()
  557. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  558. # Debounce: a printer must stay offline this long before we notify. Sized
  559. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  560. # so a single stale-trigger cooldown isn't enough to fire — only a real
  561. # offline that survives one reconnect attempt notifies.
  562. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  563. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  564. # when status="failed" to label the print's failure_reason in archives.
  565. #
  566. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  567. # which is wrong on two counts:
  568. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  569. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  570. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  571. # the public wiki) as part of its user-cancel sequence. Matching on the module
  572. # alone caused user-cancellations to be archived as "Layer shift" failures.
  573. # We now match by full short code only — anything not in this map leaves
  574. # failure_reason=None rather than guessing.
  575. # Values are the canonical camelCase failure-reason keys, NOT display labels
  576. # (issue #2974). The vocabulary is enforced on writes by
  577. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  578. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  579. # Statistics breakdown. Storing a label here instead put a second spelling of
  580. # the same cause into one column: the Failure Analysis widget groups on the raw
  581. # value, so a print the backend classified and an identical one a user
  582. # classified counted as two different reasons, and the label form could never
  583. # be translated because there was no key for ``t()`` to resolve.
  584. _HMS_FAILURE_REASONS: dict[str, str] = {
  585. # Layer shift / step loss
  586. "0300_4057": "layerShift",
  587. "0300_4068": "layerShift",
  588. "0300_800C": "layerShift",
  589. # Filament runout (printer-side & per-AMS-slot)
  590. "0300_8004": "filamentRunout",
  591. "0700_8011": "filamentRunout",
  592. "0701_8011": "filamentRunout",
  593. "0702_8011": "filamentRunout",
  594. "0703_8011": "filamentRunout",
  595. "0704_8011": "filamentRunout",
  596. "0705_8011": "filamentRunout",
  597. "0706_8011": "filamentRunout",
  598. "0707_8011": "filamentRunout",
  599. "07FF_8011": "filamentRunout",
  600. # Clogged nozzle / extruder
  601. "0300_4006": "cloggedNozzle",
  602. "0300_8016": "cloggedNozzle",
  603. "0300_801C": "cloggedNozzle",
  604. "0700_8003": "cloggedNozzle",
  605. "0700_8007": "cloggedNozzle",
  606. "0700_8013": "cloggedNozzle",
  607. "0701_8003": "cloggedNozzle",
  608. "0701_8007": "cloggedNozzle",
  609. "0701_8013": "cloggedNozzle",
  610. "0702_8003": "cloggedNozzle",
  611. # AI print monitoring — spaghetti / the model coming off the plate.
  612. # `spaghettiDetached` is a key the archive editor already offers for this
  613. # failure mode, not a new one, so a derived reason opens the dropdown on
  614. # that option rather than blank — and survives the next save, which clears
  615. # any value the editor does not recognise.
  616. #
  617. # A module-0x0C row is safe here despite the warning above: that warning is
  618. # about matching on the module alone, and 0C00_8042 is a full short code
  619. # with a documented meaning ("The AI print monitor has detected a spaghetti
  620. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  621. # cannot collide.
  622. #
  623. # 0300_8003's own text ends "before continuing your print", but on an X2D
  624. # it arrives with the print already paused, offering only
  625. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  626. #
  627. # Two neighbours are left out on purpose, so this does not get re-derived:
  628. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  629. # reads as a warning about a print that is still running, not a halt.
  630. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  631. # the waste chute. That is not the print failing.
  632. #
  633. # That line is drawn from the text, not from `severity`, because severity
  634. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  635. # module/error word with no level in it, and bambu_mqtt.py gives every
  636. # print_error entry a flat severity=3. Matching on the short code alone is
  637. # the right shape for derive_failure_reason, not an omission.
  638. "0300_8003": "spaghettiDetached",
  639. "0C00_8042": "spaghettiDetached",
  640. }
  641. def _hms_short_code(attr: int, code: int | str) -> str:
  642. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  643. if isinstance(code, str):
  644. code_int = int(code.replace("0x", ""), 16) if code else 0
  645. else:
  646. code_int = int(code or 0)
  647. attr_int = int(attr or 0)
  648. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  649. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  650. """Derive the failure_reason key for an archived print.
  651. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  652. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  653. no HMS code matches (don't guess — null is honest). The keys are the
  654. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  655. translated at render time.
  656. """
  657. if status in ("aborted", "cancelled"):
  658. return "userCancelled"
  659. if status != "failed":
  660. return None
  661. for err in hms_errors or []:
  662. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  663. if short_code in _HMS_FAILURE_REASONS:
  664. return _HMS_FAILURE_REASONS[short_code]
  665. return None
  666. # Track created_by_id for expected prints so the user email can be sent even when
  667. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  668. # {(printer_id, filename): created_by_id}
  669. _expected_print_creators: dict[tuple[int, str], int] = {}
  670. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  671. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  672. # tag tuple changes for the slot. Cleared when the slot is reported empty
  673. # so remove + reinsert reliably re-prompts the UI.
  674. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  675. async def _broadcast_unknown_tag(
  676. *,
  677. printer_id: int,
  678. ams_id: int,
  679. tray_id: int,
  680. tag_uid: str,
  681. tray_uuid: str,
  682. tray_type: str | None = None,
  683. tray_color: str | None = None,
  684. tray_sub_brands: str | None = None,
  685. tray_count: int | None = None,
  686. ) -> None:
  687. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  688. _logger = logging.getLogger(__name__)
  689. slot_key = (ams_id, tray_id)
  690. tag_key = (tag_uid or "", tray_uuid or "")
  691. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  692. if per_printer.get(slot_key) == tag_key:
  693. _logger.debug(
  694. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  695. printer_id,
  696. ams_id,
  697. tray_id,
  698. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  699. )
  700. return
  701. _logger.info(
  702. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  703. printer_id,
  704. ams_id,
  705. tray_id,
  706. tray_type,
  707. tray_color,
  708. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  709. )
  710. # Broadcast first; only commit the dedup if the WS write succeeds.
  711. # If broadcast raises, the next MQTT push retries instead of being
  712. # permanently silenced by a poisoned dedup entry.
  713. await ws_manager.broadcast(
  714. {
  715. "type": "unknown_tag",
  716. "printer_id": printer_id,
  717. "ams_id": ams_id,
  718. "tray_id": tray_id,
  719. "tag_uid": tag_uid,
  720. "tray_uuid": tray_uuid,
  721. "tray_type": tray_type,
  722. "tray_color": tray_color,
  723. "tray_sub_brands": tray_sub_brands,
  724. "tray_count": tray_count,
  725. }
  726. )
  727. per_printer[slot_key] = tag_key
  728. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  729. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  730. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  731. if per_printer is None:
  732. return
  733. per_printer.pop((ams_id, tray_id), None)
  734. # TTL for expected-print entries: evict registrations older than this to prevent
  735. # unbounded growth when a print is registered but never starts (e.g. printer
  736. # disconnect, app restart, print started from the printer panel).
  737. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  738. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  739. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  740. # Cleanup loop interval
  741. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  742. _expected_prints_cleanup_task: asyncio.Task | None = None
  743. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  744. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  745. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  746. possible_keys: list[tuple[int, str]] = []
  747. filename = (state.gcode_file or state.current_print or "").strip()
  748. subtask_name = (state.subtask_name or "").strip()
  749. if subtask_name:
  750. possible_keys.append((printer_id, subtask_name))
  751. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  752. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  753. if filename:
  754. base_name = filename.rsplit("/", 1)[-1]
  755. if base_name.endswith(".gcode.3mf"):
  756. root_name = base_name[: -len(".gcode.3mf")]
  757. possible_keys.append((printer_id, root_name))
  758. possible_keys.append((printer_id, base_name))
  759. possible_keys.append((printer_id, f"{root_name}.gcode"))
  760. possible_keys.append((printer_id, f"{root_name}.3mf"))
  761. elif base_name.endswith(".3mf"):
  762. root_name = base_name[: -len(".3mf")]
  763. possible_keys.append((printer_id, root_name))
  764. possible_keys.append((printer_id, base_name))
  765. elif base_name.endswith(".gcode"):
  766. root_name = base_name[: -len(".gcode")]
  767. possible_keys.append((printer_id, root_name))
  768. possible_keys.append((printer_id, f"{root_name}.3mf"))
  769. possible_keys.append((printer_id, base_name))
  770. else:
  771. possible_keys.append((printer_id, base_name))
  772. possible_keys.append((printer_id, f"{base_name}.3mf"))
  773. return possible_keys
  774. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  775. """The id of who started the print, unless that user has been deleted since.
  776. Deleting a user forgets them in printer_manager, but a print that ended a
  777. moment before still holds them.
  778. """
  779. if not print_user or print_user.get("user_id") is None:
  780. return None
  781. from backend.app.models.user import User
  782. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  783. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  784. """Check the cheap, process-local print ownership signals."""
  785. if printer_manager.get_current_print_user(printer_id):
  786. return True
  787. return any(
  788. key in _expected_prints or _active_prints.get(key) in _owned_print_archive_ids
  789. for key in _build_status_print_keys(printer_id, state)
  790. )
  791. def _reported_print_names(printer_id: int, state: PrinterState) -> set[str]:
  792. """The names the printer reports for its print, as it echoes them (spaces become underscores)."""
  793. return {_normalise_subtask_name(name) for _pid, name in _build_status_print_keys(printer_id, state)} - {""}
  794. async def _printing_archive_without_job_id(
  795. db, printer_id: int, reported: set[str], *, dispatched_only: bool, live_only: bool = False
  796. ):
  797. """The newest printing archive on ``printer_id`` of a print that reported no job id, under a reported name.
  798. An archive with a real id of its own is a print that reported one: a "0"
  799. print is not it, even under the same name (one whose completion was missed
  800. would otherwise cover it). ``dispatched_only`` keeps to archives carrying
  801. Bambuddy's dispatch marker; ``live_only`` leaves out deleted ones.
  802. """
  803. from backend.app.models.archive import PrintArchive
  804. query = select(PrintArchive).where(
  805. PrintArchive.printer_id == printer_id,
  806. PrintArchive.status == "printing",
  807. or_(PrintArchive.subtask_id.is_(None), PrintArchive.subtask_id.in_(("", "0"))),
  808. )
  809. if dispatched_only:
  810. query = query.where(or_(PrintArchive.billing_run_id.is_not(None), PrintArchive.created_by_id.is_not(None)))
  811. if live_only:
  812. query = query.where(PrintArchive.deleted_at.is_(None))
  813. archives = await db.execute(query.order_by(PrintArchive.created_at.desc()))
  814. return next((a for a in archives.scalars() if _archive_name_forms(a) & reported), None)
  815. async def running_print_archive(db, printer_id: int, state: PrinterState, *, printing_only: bool, by_name: bool):
  816. """The archive of the print running on ``printer_id``, or None (#3327).
  817. By the print's subtask_id first, which the firmware mints per print; with
  818. ``printing_only`` only an archive that is still printing (a leftover row of
  819. a completion never seen must not stand in for another job). A print
  820. started outside the cloud (Bambu Studio over LAN, Handy, the printer's
  821. screen) reports subtask_id "0", which links it to nothing: the archive
  822. Bambuddy bound to the running print comes next, the one completion charges
  823. and photographs. A restart forgets that binding and rebinds only Bambuddy's
  824. own prints, so with ``by_name`` a "0" print last falls back to its printing
  825. archive under the name the printer reports. That can be an earlier run of
  826. the same name whose completion was missed while Bambuddy was down: good
  827. enough for a plate label or a cover, not for which objects skip-objects
  828. offers, so those callers leave it off. None until the archive exists, and
  829. never a deleted one.
  830. """
  831. from backend.app.models.archive import PrintArchive
  832. from backend.app.services.print_log import open_run_on_printer
  833. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  834. if subtask_id not in ("", "0"):
  835. # The run open on the printer for this job: the archive row is shared
  836. # by every plate of it, its printer and job id the latest start's.
  837. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  838. if run is not None and run.archive_id is not None:
  839. archive = await db.scalar(
  840. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  841. )
  842. if archive is not None:
  843. return archive
  844. query = select(PrintArchive).where(
  845. PrintArchive.printer_id == printer_id,
  846. PrintArchive.subtask_id == subtask_id,
  847. PrintArchive.deleted_at.is_(None),
  848. )
  849. if printing_only:
  850. query = query.where(PrintArchive.status == "printing")
  851. archive = await db.scalar(query.order_by(PrintArchive.created_at.desc()).limit(1))
  852. if archive is not None:
  853. return archive
  854. bound = next(
  855. (_active_prints[key] for key in _build_status_print_keys(printer_id, state) if key in _active_prints),
  856. None,
  857. )
  858. if bound is not None:
  859. return await db.scalar(select(PrintArchive).where(PrintArchive.id == bound, PrintArchive.deleted_at.is_(None)))
  860. if not by_name or subtask_id != "0":
  861. return None
  862. reported = _reported_print_names(printer_id, state)
  863. if not reported:
  864. return None
  865. return await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=False, live_only=True)
  866. def _bind_active_print(
  867. printer_id: int,
  868. archive_id: int,
  869. archive_filename: str | None,
  870. filename: str | None = None,
  871. subtask_name: str | None = None,
  872. ) -> None:
  873. """Track a running print under every name its completion may report.
  874. One set for every path that binds a print (new archive, expected print,
  875. restart resume, fallback): the archive's file name, the name the printer
  876. reported, and the subtask with and without ``.3mf``. Paths that registered
  877. fewer names lost the bound archive at completion, and with it the plate
  878. restore's height (#3240), whenever MQTT reported a name they had left out.
  879. """
  880. for name in {archive_filename, filename, f"{subtask_name}.3mf" if subtask_name else None, subtask_name}:
  881. if name:
  882. _active_prints[(printer_id, name)] = archive_id
  883. async def _archive_of_open_run(printer_id: int, subtask_id: str | None = None) -> int | None:
  884. """The archive of the run open on the printer, if it is still there.
  885. With ``subtask_id``, only a run of that job."""
  886. try:
  887. from backend.app.models.archive import PrintArchive
  888. from backend.app.services.print_log import open_run_on_printer
  889. async with async_session() as db:
  890. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  891. if run is None or run.archive_id is None:
  892. return None
  893. return await db.scalar(
  894. select(PrintArchive.id).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  895. )
  896. except Exception as e:
  897. logging.getLogger(__name__).warning("[RUN] Could not read the open run of printer %s: %s", printer_id, e)
  898. return None
  899. async def _open_run_for(archive_id: int, printer_id: int, subtask_id: str | None = None) -> None:
  900. """Write the run of the print that just started on the archive (archive
  901. redesign). In a session of its own and never in the way of the print
  902. start: until its readers move over, the archive still carries the print.
  903. The archive's start must be committed before. ``subtask_id`` is the
  904. printer's job, which finds the run again at a resume."""
  905. try:
  906. from backend.app.models.archive import PrintArchive
  907. from backend.app.models.printer import Printer
  908. from backend.app.services.print_log import open_run
  909. async with async_session() as db:
  910. archive = await db.get(PrintArchive, archive_id)
  911. if archive is None:
  912. return
  913. printer_name = await db.scalar(select(Printer.name).where(Printer.id == printer_id))
  914. await open_run(
  915. db,
  916. archive,
  917. printer_id=printer_id,
  918. printer_name=printer_name,
  919. plate_id=_print_plate_ids.get((printer_id, archive_id)),
  920. subtask_id=subtask_id,
  921. )
  922. await db.commit()
  923. except Exception as e:
  924. logging.getLogger(__name__).warning("[RUN] Could not open the run of archive %s: %s", archive_id, e)
  925. def _mark_owned_if_dispatched(archive) -> None:
  926. """Remember a running print's archive as Bambuddy's when it carries a
  927. dispatch marker Bambuddy writes itself: ``billing_run_id`` (minted per
  928. dispatch in the scheduler) or ``created_by_id`` (from the queue item)."""
  929. if archive.billing_run_id is not None or archive.created_by_id is not None:
  930. _owned_print_archive_ids.add(archive.id)
  931. async def _is_printer_kill_switch_enabled_cached() -> bool:
  932. """Return the kill-switch setting without querying on every MQTT frame."""
  933. global _kill_switch_setting_cache
  934. now = time.monotonic()
  935. if _kill_switch_setting_cache is not None:
  936. enabled, expires_at = _kill_switch_setting_cache
  937. if now < expires_at:
  938. return enabled
  939. async with async_session() as db:
  940. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  941. enabled = await is_printer_kill_switch_enabled(db)
  942. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  943. return enabled
  944. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  945. """Resolve whether the current print was started by Bambuddy.
  946. ``None`` means identity is not yet safe to decide. The kill switch must
  947. defer in that case: stopping a print is irreversible, and the first status
  948. frames after a restart may arrive before all subtask fields are populated.
  949. """
  950. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  951. return True
  952. # The printer's built-in calibration runs (Bambuddy's Calibrate, the
  953. # printer's screen) play gcode from its read-only system partition, where no
  954. # user file can be. Only that path counts: a calibration *name* proves
  955. # nothing, since Bambu Studio's pressure-advance print reports a user-style
  956. # path, and any print can be given that name.
  957. if str(getattr(state, "gcode_file", "") or "").startswith("/usr/"):
  958. return True
  959. # A1, A1 Mini, P1 and A2L report the same calibration as a bare file name,
  960. # which nothing distinguishes from a user's file given that name, so it is
  961. # not exempt: with the kill switch on, calibrate on those printers with the
  962. # switch off.
  963. possible_keys = _build_status_print_keys(printer_id, state)
  964. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  965. # is on disk. subtask_id is minted per print and pins the answer to the job
  966. # actually running, rather than to an unrelated one that reuses a filename.
  967. raw_subtask_id = getattr(state, "subtask_id", None)
  968. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  969. if subtask_id == "":
  970. # Not reported yet: the first frames after a restart can lack it.
  971. return None
  972. from backend.app.models.archive import PrintArchive
  973. if subtask_id == "0":
  974. # A print started outside the cloud from Bambu Studio, Handy or the
  975. # printer's screen reports "0", so there is no id to match: one of
  976. # Bambuddy's printing archives on this printer under the name the
  977. # printer reports, compared as the printer echoes names (spaces become
  978. # underscores). Nothing reported to compare yet: wait.
  979. reported = _reported_print_names(printer_id, state)
  980. if not reported:
  981. return None
  982. archive = await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=True)
  983. else:
  984. from backend.app.services.print_log import open_run_on_printer
  985. # This job's run open on the printer: the archive is shared by every
  986. # plate of it, and its status, printer and job id are the latest
  987. # start's, which may be another printer's.
  988. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  989. archive = await db.get(PrintArchive, run.archive_id) if run is not None and run.archive_id else None
  990. if archive is None:
  991. result = await db.execute(
  992. select(PrintArchive)
  993. .where(
  994. PrintArchive.printer_id == printer_id,
  995. PrintArchive.status == "printing",
  996. PrintArchive.subtask_id == subtask_id,
  997. )
  998. .order_by(PrintArchive.created_at.desc())
  999. .limit(1)
  1000. )
  1001. archive = result.scalar_one_or_none()
  1002. # An archive row on its own proves nothing: `on_print_start` archives every
  1003. # print it observes, including ones started from Bambu Studio or Handy, and
  1004. # stamps them with the same status and subtask_id. Authorizing on its mere
  1005. # existence would disable the kill switch the moment the 3MF finishes
  1006. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  1007. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  1008. # (carried over from the queue item that started it).
  1009. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  1010. # Rehydrate the fast in-memory path for subsequent status frames. Include
  1011. # both the archive filename and every normalized key reported by MQTT.
  1012. _owned_print_archive_ids.add(archive.id)
  1013. _active_prints[(printer_id, archive.filename)] = archive.id
  1014. for key in possible_keys:
  1015. _active_prints[key] = archive.id
  1016. return True
  1017. # No dispatch marker. Before calling this someone else's print, check whether
  1018. # Bambuddy has a job of its own running on this printer: a library-file
  1019. # dispatch has no archive at send time, and an archive created seconds later
  1020. # by `on_print_start` carries neither marker. The queue row, which the
  1021. # scheduler commits to status="printing" before the MQTT send, is the one
  1022. # durable record every Bambuddy print has. It cannot be tied to this
  1023. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  1024. # print is irreversible, and refusing to act costs nothing but a log line.
  1025. from backend.app.models.print_queue import PrintQueueItem
  1026. dispatched_here = await db.scalar(
  1027. select(PrintQueueItem.id)
  1028. .where(
  1029. PrintQueueItem.printer_id == printer_id,
  1030. PrintQueueItem.status == "printing",
  1031. )
  1032. .limit(1)
  1033. )
  1034. if dispatched_here is not None:
  1035. return None
  1036. return False
  1037. async def _send_kill_switch_provider_notification(
  1038. printer_id: int,
  1039. printer_name: str,
  1040. data: dict,
  1041. ) -> bool:
  1042. """Send the immediate print-stopped provider notification.
  1043. Returning a success flag lets the normal MQTT completion path retry when
  1044. this early notification could not be delivered.
  1045. """
  1046. logger = logging.getLogger(__name__)
  1047. try:
  1048. async with async_session() as db:
  1049. await notification_service.on_print_complete(
  1050. printer_id,
  1051. printer_name,
  1052. "stopped",
  1053. data,
  1054. db,
  1055. )
  1056. return True
  1057. except Exception as e:
  1058. logger.warning(
  1059. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  1060. printer_id,
  1061. e,
  1062. )
  1063. return False
  1064. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  1065. """Wait for an immediate kill-switch notification, if one was scheduled."""
  1066. if task is None:
  1067. return False
  1068. try:
  1069. return await task
  1070. except Exception as e:
  1071. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  1072. return False
  1073. async def _run_needs_energy_start(archive, printer_id: int, db) -> bool:
  1074. """At a resume: whether the print's run still lacks its energy start
  1075. reading. The archive's may be an earlier print's. Commits a reading
  1076. found on the archive for this run onto it."""
  1077. try:
  1078. from backend.app.services.print_log import run_needs_energy_start
  1079. needs = await run_needs_energy_start(db, archive, printer_id=printer_id)
  1080. await db.commit()
  1081. return needs
  1082. except Exception as e:
  1083. logging.getLogger(__name__).warning("[RUN] Energy start of archive %s's run not checked: %s", archive.id, e)
  1084. return archive.energy_start_kwh is None
  1085. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  1086. """Capture the smart plug lifetime counter on the archive at print start.
  1087. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  1088. tracking survives a backend restart mid-print. The print-end handler reads
  1089. this value back from the DB and computes the delta against the current
  1090. plug counter.
  1091. """
  1092. _logger = logging.getLogger(__name__)
  1093. try:
  1094. candidates = await energy_plug_candidates(db, printer_id)
  1095. if not candidates:
  1096. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  1097. return False
  1098. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  1099. if selected is None:
  1100. # Naming the plugs matters here: with several linked to one printer
  1101. # this is the difference between "the meter is offline" and "you
  1102. # linked only accessories" (#2859).
  1103. _logger.warning(
  1104. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  1105. printer_id,
  1106. archive.id,
  1107. ", ".join(plug.name for plug in candidates),
  1108. )
  1109. return False
  1110. plug, energy = selected
  1111. archive.energy_start_kwh = float(energy["total"])
  1112. # With the plug's snapshots, what lets the cost follow the price over
  1113. # the print rather than take the price at its end (#1251). A price that
  1114. # can't be had must not cost the print its energy reading.
  1115. archive.energy_start_at = utcnow_naive()
  1116. archive.energy_start_plug_id = plug.id
  1117. try:
  1118. from backend.app.services.energy_price import current_price
  1119. archive.energy_start_price = await current_price(db)
  1120. except Exception as e:
  1121. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  1122. archive.energy_start_price = None
  1123. try:
  1124. from backend.app.services.print_log import mirror_energy_start
  1125. await mirror_energy_start(db, archive, printer_id=printer_id)
  1126. except Exception as e:
  1127. _logger.warning("[RUN] Energy start not copied onto the run of archive %s: %s", archive.id, e)
  1128. await db.commit()
  1129. _logger.info(
  1130. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  1131. f" ({context})" if context else "",
  1132. archive.id,
  1133. plug.name,
  1134. energy["total"],
  1135. )
  1136. return True
  1137. except Exception as e:
  1138. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  1139. return False
  1140. def forget_print_creator(user_id: int) -> None:
  1141. """The print-start emails of a deleted user's jobs go to nobody, not to
  1142. whoever is given the id next (SQLite reuses it)."""
  1143. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  1144. del _expected_print_creators[key]
  1145. async def forget_printer(printer_id: int) -> None:
  1146. """Drop what is kept for a deleted printer's id, here and in the services.
  1147. SQLite used to give the id to the next printer created, which inherited it
  1148. all: the running print's owner (its prints passed the kill switch and were
  1149. billed to that user), the plate-clear gate, pending and suppressed
  1150. notifications, the camera feed, the plate references. Ids are no longer
  1151. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  1152. stay. Called after the delete is committed, and again by work that was in
  1153. flight and wrote state back.
  1154. Every printer-keyed map of this module is listed here or, with the reason,
  1155. in tests/unit/test_forget_printer.py.
  1156. """
  1157. from backend.app.api.routes import camera
  1158. from backend.app.services import (
  1159. bambu_ftp,
  1160. kprofile_drift,
  1161. layer_timelapse,
  1162. plate_detection,
  1163. print_dispatch_context,
  1164. usage_tracker,
  1165. )
  1166. from backend.app.services.notify_live_activities import notify_live_activities
  1167. from backend.app.services.obico_detection import obico_detection_service
  1168. from backend.app.services.printer_file_cache import printer_file_cache
  1169. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  1170. archive_ids = set()
  1171. for tracked in (_active_prints, _expected_prints):
  1172. for key in [key for key in tracked if key[0] == printer_id]:
  1173. archive_ids.add(tracked.pop(key))
  1174. for archive_id in archive_ids:
  1175. _owned_print_archive_ids.discard(archive_id)
  1176. for registered in (_print_ams_mappings, _print_cost_center_ids, _print_plate_ids):
  1177. for key in [key for key in registered if key[0] == printer_id]:
  1178. del registered[key]
  1179. for tracked in (_expected_print_creators, _expected_print_registered_at):
  1180. for key in [key for key in tracked if key[0] == printer_id]:
  1181. del tracked[key]
  1182. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  1183. _ams_index_only_logged.discard(key)
  1184. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  1185. del _ams_alarm_cooldown[key]
  1186. # Pending work that would act on the id: an offline notice, a 3MF retry.
  1187. # A kill-switch notice is about a stop that happened and is left to finish.
  1188. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  1189. task = tasks.pop(printer_id, None)
  1190. if task is not None:
  1191. task.cancel()
  1192. for keyed in (
  1193. _stage22_finish_frames,
  1194. _stage22_finish_in_flight,
  1195. _inprint_frame_bank,
  1196. _inprint_frame_bank_ts,
  1197. _printer_reconciled_since_connect,
  1198. _printer_kprofiles_primed_since_connect,
  1199. _last_progress_milestone,
  1200. _first_layer_notified,
  1201. _kill_switch_notification_tasks,
  1202. _notified_hms_errors,
  1203. _hms_print_state,
  1204. _hms_forget_when_gone,
  1205. _timelapse_baselines,
  1206. _bed_cool_waiters,
  1207. _printer_last_connected,
  1208. _unknown_tag_last_broadcast,
  1209. _last_status_broadcast,
  1210. _connection_watchdog_last_attempt,
  1211. ):
  1212. keyed.pop(printer_id, None)
  1213. for marked in (
  1214. _unauthorized_print_kill_sent,
  1215. _user_stopped_printers,
  1216. _kill_switch_stopped,
  1217. _printer_offline_published,
  1218. _nozzle_count_updated,
  1219. _runtime_seen_connected,
  1220. _timelapse_baselines_unread,
  1221. ):
  1222. marked.discard(printer_id)
  1223. printer_manager.forget_printer(printer_id)
  1224. printer_file_cache.forget_printer(printer_id)
  1225. print_dispatch_context.clear(printer_id)
  1226. kprofile_drift.forget_printer(printer_id, deleted=True)
  1227. layer_timelapse.cancel_session(printer_id)
  1228. usage_tracker.forget_printer(printer_id)
  1229. obico_detection_service.forget_printer(printer_id)
  1230. bambu_ftp.clear_3mf_cache(printer_id)
  1231. await camera.forget_printer(printer_id)
  1232. printers.clear_cover_cache(printer_id)
  1233. print_scheduler.forget_printer(printer_id)
  1234. notify_live_activities.forget_printer(printer_id)
  1235. plate_detection.remove_printer_references(printer_id)
  1236. def register_expected_print(
  1237. printer_id: int,
  1238. filename: str,
  1239. archive_id: int,
  1240. ams_mapping: list[int] | None = None,
  1241. created_by_id: int | None = None,
  1242. cost_center_id: int | None = None,
  1243. plate_id: int | None = None,
  1244. ):
  1245. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1246. # Store with multiple filename variations to catch different naming patterns
  1247. _expected_prints[(printer_id, filename)] = archive_id
  1248. # Also store without .3mf extension if present
  1249. if filename.endswith(".3mf"):
  1250. base = filename[:-4]
  1251. _expected_prints[(printer_id, base)] = archive_id
  1252. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1253. # Store AMS mapping for usage tracking at print completion, and plate_id for
  1254. # a single-plate dispatch from a multi-plate 3MF — without it, the direct-Print
  1255. # path attributes the whole file's filament total to the spool instead of just
  1256. # the printed plate (#1697). They describe this dispatch: one that has none
  1257. # drops what an earlier dispatch of the archive left (sent, never started),
  1258. # unless a plate of the archive is printing now and still needs them.
  1259. dispatch = (printer_id, archive_id)
  1260. archive_printing = _printing_here(printer_id, archive_id)
  1261. if ams_mapping is not None:
  1262. _print_ams_mappings[dispatch] = ams_mapping
  1263. elif not archive_printing:
  1264. _print_ams_mappings.pop(dispatch, None)
  1265. if cost_center_id is not None:
  1266. _print_cost_center_ids[dispatch] = cost_center_id
  1267. elif not archive_printing:
  1268. _print_cost_center_ids.pop(dispatch, None)
  1269. if plate_id is not None:
  1270. _print_plate_ids[dispatch] = plate_id
  1271. elif not archive_printing:
  1272. _print_plate_ids.pop(dispatch, None)
  1273. # Store created_by_id so the user start email can be sent even when the archive
  1274. # itself has no created_by_id (e.g. library-file-based queue prints)
  1275. if created_by_id is not None:
  1276. _expected_print_creators[(printer_id, filename)] = created_by_id
  1277. if filename.endswith(".3mf"):
  1278. base = filename[:-4]
  1279. _expected_print_creators[(printer_id, base)] = created_by_id
  1280. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1281. # Record registration time for TTL-based eviction
  1282. _registered_at = time.monotonic()
  1283. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1284. if filename.endswith(".3mf"):
  1285. base = filename[:-4]
  1286. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1287. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1288. logging.getLogger(__name__).info(
  1289. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1290. )
  1291. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1292. """Undo :func:`register_expected_print` when the print never went out.
  1293. Registration has to happen *before* the MQTT print command, because the
  1294. printer can report the print before the line after the send executes. So
  1295. every path that registers and then fails to send — a cancel winning the
  1296. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1297. between — leaves an expectation for a print that will never arrive.
  1298. The TTL sweep evicts those after two hours, which is far longer than it
  1299. takes a user to react to a failed dispatch by pressing print again: that
  1300. reprint would be folded into the *old* archive and take the stale
  1301. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1302. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1303. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1304. are keyed by printer and archive, not by file, so they may only be dropped
  1305. once no live key of the printer still points at that archive.
  1306. """
  1307. keys = [(printer_id, filename)]
  1308. if filename.endswith(".3mf"):
  1309. base = filename[:-4]
  1310. keys.append((printer_id, base))
  1311. keys.append((printer_id, f"{base}.gcode"))
  1312. removed = False
  1313. for key in keys:
  1314. if _expected_prints.pop(key, None) is not None:
  1315. removed = True
  1316. _expected_print_creators.pop(key, None)
  1317. _expected_print_registered_at.pop(key, None)
  1318. # Still needed by another expected print of the archive on the printer,
  1319. # or a plate of it printing there, as in the sweep.
  1320. if not _expected_or_printing_here(printer_id, archive_id):
  1321. _drop_dispatch(printer_id, archive_id)
  1322. if removed:
  1323. logging.getLogger(__name__).info(
  1324. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1325. printer_id,
  1326. filename,
  1327. archive_id,
  1328. )
  1329. def _compute_run_filament_grams(
  1330. status: str,
  1331. archive_filament_used_grams: float | None,
  1332. progress: float | int | None,
  1333. usage_results: list[dict] | None,
  1334. ) -> float | None:
  1335. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1336. Priority for every status:
  1337. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1338. weight delta — same source that drives "Total Consumed" on the
  1339. Inventory page, so Stats and Inventory totals stay aligned).
  1340. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1341. back to the canonical "this print used X" value).
  1342. 3. For partial statuses: ``estimate * progress%``.
  1343. 4. ``None`` if nothing is known.
  1344. """
  1345. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1346. if tracked_grams > 0:
  1347. return round(tracked_grams, 1)
  1348. if status == "completed":
  1349. return archive_filament_used_grams
  1350. if archive_filament_used_grams:
  1351. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1352. if scale > 0:
  1353. return round(archive_filament_used_grams * scale, 1)
  1354. return None
  1355. def _printing_here(printer_id: int, archive_id: int) -> bool:
  1356. """Whether a plate of the archive is printing on the printer."""
  1357. return any(key[0] == printer_id and bound == archive_id for key, bound in _active_prints.items())
  1358. def _expected_or_printing_here(printer_id: int, archive_id: int) -> bool:
  1359. """Whether a print of the archive is expected or printing on the printer."""
  1360. return _printing_here(printer_id, archive_id) or any(
  1361. key[0] == printer_id and expected == archive_id for key, expected in _expected_prints.items()
  1362. )
  1363. def _drop_dispatch(printer_id: int, archive_id: int) -> None:
  1364. """Forget what the dispatch of the archive to the printer registered."""
  1365. dispatch = (printer_id, archive_id)
  1366. _print_ams_mappings.pop(dispatch, None)
  1367. _print_cost_center_ids.pop(dispatch, None)
  1368. _print_plate_ids.pop(dispatch, None)
  1369. def _get_start_ams_mapping(data: dict, printer_id: int, archive_id: int | None) -> list[int] | None:
  1370. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1371. stored_ams_mapping = data.get("ams_mapping")
  1372. if not stored_ams_mapping and archive_id:
  1373. stored_ams_mapping = _print_ams_mappings.get((printer_id, archive_id))
  1374. return stored_ams_mapping
  1375. def _get_start_plate_id(printer_id: int, archive_id: int | None) -> int | None:
  1376. """Resolve plate_id for print start without consuming stored direct-Print state.
  1377. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1378. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1379. read it back at print-start without popping (the entry is popped on print
  1380. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1381. """
  1382. if archive_id is None:
  1383. return None
  1384. return _print_plate_ids.get((printer_id, archive_id))
  1385. def _partial_progress_scale(progress: int | float | None) -> float:
  1386. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1387. Used by every site that multiplies a "would-have-used" slicer estimate
  1388. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1389. so the three sites in ``_background_notifications`` (and the per-plate
  1390. override helper) can't drift apart on the coercion shape.
  1391. """
  1392. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1393. def _scope_notification_archive_data_to_plate(
  1394. archive_data: dict,
  1395. archive_file_path: str | None,
  1396. plate_id: int | None,
  1397. print_status: str,
  1398. progress: int | float | None,
  1399. base_dir: Path,
  1400. ) -> dict:
  1401. """Override summed-across-plates totals in ``archive_data`` with the values
  1402. for ``plate_id`` so the completion notification reports what was actually
  1403. printed, not the whole project (#1785).
  1404. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1405. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1406. the archive card's "whole project" headline, wrong for the completion
  1407. notification of a single-plate print. The queue UI already re-reads the
  1408. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1409. notification payload (filament grams, time estimate, per-slot breakdown).
  1410. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1411. no per-plate values — in every fail case the original ``archive_data`` is
  1412. returned unchanged so the notification still sends.
  1413. """
  1414. if plate_id is None or not archive_file_path:
  1415. return archive_data
  1416. from backend.app.utils.threemf_tools import (
  1417. extract_filament_usage_from_3mf,
  1418. extract_print_time_from_3mf,
  1419. )
  1420. archive_path = base_dir / archive_file_path
  1421. if not archive_path.exists():
  1422. return archive_data
  1423. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1424. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1425. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1426. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1427. if plate_time:
  1428. archive_data["print_time_seconds"] = plate_time
  1429. # Gate both the grams headline AND the per-slot breakdown on the same
  1430. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1431. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1432. # to the project-level grams the archive columns already provide rather
  1433. # than ship a project-level headline next to an all-zero per-plate
  1434. # breakdown.
  1435. if plate_grams > 0:
  1436. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1437. archive_data["filament_slots"] = [
  1438. {
  1439. "slot_id": s.get("slot_id"),
  1440. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1441. "type": s.get("type", ""),
  1442. "color": s.get("color", ""),
  1443. }
  1444. for s in plate_slots
  1445. ]
  1446. return archive_data
  1447. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1448. """Best-effort filament metadata from the MQTT print-start snapshot.
  1449. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1450. file during print, see #1533) so the fallback PrintArchive still has
  1451. enough filament info to support the inventory views and AMS-expansion
  1452. planning the operator opens it for. Returns a dict with optional
  1453. ``filament_type`` and ``filament_color`` keys in the same
  1454. comma-separated format the 3MF extractor produces, so the rest of the
  1455. codebase treats the fallback archive identically to a normal one.
  1456. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1457. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1458. entries). When supplied, only the slots actually consumed by this
  1459. print contribute. Without it the function falls back to every loaded
  1460. AMS slot — less accurate but still useful.
  1461. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1462. that the unit tests pass directly, AND the on_print_start callback
  1463. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1464. bambu_mqtt service hands to main.py at runtime. The original
  1465. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1466. handled the inner shape and silently returned ``{}`` for every real
  1467. print start, leaving fallback archives' filament fields NULL — the
  1468. exact regression the fix was meant to close. Reported with a log
  1469. proving the AMS state was right there at
  1470. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1471. """
  1472. result: dict[str, str] = {}
  1473. # Look at the on_print_start wrapper first, then the inner shape.
  1474. raw_data = (data or {}).get("raw_data")
  1475. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1476. if not isinstance(ams_root, dict):
  1477. ams_root = (data or {}).get("ams") or {}
  1478. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1479. if not isinstance(ams_units, list) or not ams_units:
  1480. return result
  1481. from backend.app.services.print_scheduler import _global_tray_id
  1482. # Map global tray id → (type, color), addressed as the print's ams_mapping
  1483. # is: unit * 4 + tray, or the bare unit id for an AMS-HT (from 128).
  1484. loaded: dict[int, tuple[str, str]] = {}
  1485. for unit in ams_units:
  1486. if not isinstance(unit, dict):
  1487. continue
  1488. try:
  1489. unit_id = int(unit.get("id", 0))
  1490. except (TypeError, ValueError):
  1491. continue
  1492. for tray in unit.get("tray") or []:
  1493. if not isinstance(tray, dict):
  1494. continue
  1495. try:
  1496. tray_id = int(tray.get("id", 0))
  1497. except (TypeError, ValueError):
  1498. continue
  1499. ttype = (tray.get("tray_type") or "").strip()
  1500. # RRGGBBAA from the printer, stored as the 3MF path stores it:
  1501. # "#RRGGBB" (the Archives page's swatches and colour filter).
  1502. hex_color = (tray.get("tray_color") or "").strip().upper()[:6]
  1503. tcolor = f"#{hex_color}" if re.fullmatch(r"[0-9A-F]{6}", hex_color) else ""
  1504. if not ttype:
  1505. continue # Empty / unloaded slot.
  1506. loaded[_global_tray_id(unit_id, tray_id)] = (ttype, tcolor)
  1507. if not loaded:
  1508. return result
  1509. if ams_mapping:
  1510. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1511. filaments = [loaded[g] for g in used_ids if g in loaded]
  1512. if not filaments:
  1513. return result # Mapping points entirely at slots we have no data for.
  1514. else:
  1515. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1516. types_joined = ",".join(f[0] for f in filaments)
  1517. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1518. # Column limits per backend/app/models/archive.py: filament_type=50,
  1519. # filament_color=200.
  1520. if types_joined:
  1521. result["filament_type"] = types_joined[:50]
  1522. if colors_joined:
  1523. result["filament_color"] = colors_joined[:200]
  1524. return result
  1525. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1526. """Start a layer-timelapse session for *archive_id* when the printer has
  1527. an external camera configured. Returns True if a session was started.
  1528. Three call sites in on_print_start (expected-archive promotion, fallback
  1529. archive creation, fresh-archive creation) used to inline this same
  1530. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1531. on the first pass). Centralising the conditional + call here makes the
  1532. contract testable in isolation and keeps the three sites locked in step.
  1533. """
  1534. if not (printer.external_camera_enabled and printer.external_camera_url):
  1535. return False
  1536. from backend.app.services.layer_timelapse import start_session
  1537. start_session(
  1538. printer_id,
  1539. archive_id,
  1540. printer.external_camera_url,
  1541. printer.external_camera_type or "mjpeg",
  1542. snapshot_url=printer.external_camera_snapshot_url,
  1543. rotation=getattr(printer, "camera_rotation", 0),
  1544. )
  1545. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1546. return True
  1547. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1548. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1549. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1550. — since #2926 — the description the parser already resolved, which is preferred
  1551. when present so the queue's failure reason reads the same as the status
  1552. response. The short code still produces the bracketed label, and still
  1553. resolves the sentence for a caller whose entries predate the field. An entry
  1554. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1555. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1556. label when no description is on file. Returns None for an empty list so
  1557. callers can leave error_message unset.
  1558. """
  1559. if not hms_errors:
  1560. return None
  1561. from backend.app.services.hms_errors import get_error_description
  1562. parts: list[str] = []
  1563. for err in hms_errors:
  1564. try:
  1565. # `_hms_short_code` rather than a local derivation: this one used to
  1566. # format the error without masking it to 16 bits, so an `hms[]` entry
  1567. # whose code carries an alert-level group produced a five-digit label
  1568. # like "0500_3000A" — not a code the user can look up, and never a
  1569. # catalogue key, so the sentence was lost with it.
  1570. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1571. except (TypeError, ValueError):
  1572. continue
  1573. description = err.get("description") or get_error_description(short_code)
  1574. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1575. # groups and is not a code anyone can look up; its full code in the
  1576. # printer screen's four groups is (#2728).
  1577. full_code = str(err.get("full_code") or "")
  1578. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1579. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1580. return "; ".join(parts) if parts else None
  1581. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1582. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1583. print completes successfully. Gated to status=='completed': failed, cancelled
  1584. and aborted prints do not count as usage. Caller is responsible for committing
  1585. the session. No-op when the queue item has no linked library file (e.g. reprints
  1586. from an archive). See #1008."""
  1587. if queue_status != "completed" or item.library_file_id is None:
  1588. return
  1589. from backend.app.models.library import LibraryFile
  1590. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1591. if lib_file is None:
  1592. return
  1593. lib_file.print_count = (lib_file.print_count or 0) + 1
  1594. lib_file.last_printed_at = datetime.now(timezone.utc)
  1595. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1596. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1597. When on_print_complete fires with status 'failed' for a printer in this set we
  1598. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1599. rather than a 'print failed' notification.
  1600. """
  1601. _user_stopped_printers.add(printer_id)
  1602. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1603. _last_status_broadcast: dict[int, str] = {}
  1604. # Track printers where we've updated nozzle_count
  1605. _nozzle_count_updated: set[int] = set()
  1606. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1607. """Wait the debounce window then fire `on_printer_offline` if the printer
  1608. is still offline.
  1609. Scheduled by `on_printer_status_change` on the connected → disconnected
  1610. edge (#1752). Cancelled by the same handler if the printer reconnects
  1611. before the window elapses, so a single MQTT blip + recovery doesn't
  1612. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1613. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1614. route through the same status-change callback, so this covers both.
  1615. """
  1616. logger = logging.getLogger(__name__)
  1617. try:
  1618. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1619. still_offline = not printer_manager.is_connected(printer_id)
  1620. logger.info(
  1621. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1622. printer_id,
  1623. still_offline,
  1624. )
  1625. if not still_offline:
  1626. return
  1627. async with async_session() as db:
  1628. from backend.app.models.printer import Printer
  1629. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1630. printer = result.scalar_one_or_none()
  1631. if not printer:
  1632. logger.warning(
  1633. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1634. printer_id,
  1635. )
  1636. return
  1637. # Recorded only when the relay can publish it, so the reconnect's
  1638. # online event always has an offline before it.
  1639. if mqtt_relay.enabled and mqtt_relay.connected:
  1640. _printer_offline_published.add(printer_id)
  1641. try:
  1642. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1643. except Exception as e:
  1644. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1645. logger.info(
  1646. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1647. printer_id,
  1648. printer.name,
  1649. )
  1650. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1651. except asyncio.CancelledError:
  1652. raise
  1653. except Exception as e:
  1654. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1655. finally:
  1656. _printer_offline_notify_tasks.pop(printer_id, None)
  1657. def _hms_notify_key(error) -> str:
  1658. """What identifies a fault for notification de-duplication.
  1659. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1660. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1661. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1662. and -0006 together) shared a key and only the first was ever notified. An
  1663. entry without a full code falls back to attr and code together.
  1664. """
  1665. full_code = getattr(error, "full_code", "") or ""
  1666. if full_code:
  1667. return full_code.upper()
  1668. return f"{error.attr:08X}:{error.code}"
  1669. def _hms_fault_counts(error) -> bool:
  1670. """Whether a fault counts as a problem: the same rule the frontend's
  1671. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1672. It counts when Bambu publishes text for it or it offers action buttons, and
  1673. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1674. no actions does not count: those are things like "the top cover is open" or
  1675. "the chamber is hot, fan speed increased", which a printer can hold through
  1676. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1677. it always has; those are prompts such as "unable to start drying" (#2728).
  1678. """
  1679. if error.severity < 1:
  1680. return False
  1681. has_actions = bool(getattr(error, "actions", None))
  1682. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1683. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1684. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1685. """The new faults that count (see ``_hms_fault_counts``).
  1686. These go to the MQTT relay; the caller also needs a description before it
  1687. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1688. used to read ``severity >= 2`` when severity held the part byte; on the real
  1689. level that would drop the task-stopping errors (#2728).
  1690. """
  1691. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1692. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1693. """The faults on this printer not notified yet, and record them as notified.
  1694. Tracking is updated before anything is sent, so concurrent status callbacks
  1695. cannot notify the same fault twice. A notified fault is forgotten once it
  1696. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1697. and on is notified once (#3226), while one that clears and comes back much
  1698. later is notified again.
  1699. When ``print_state`` changes (a print resumed, started or finished), every
  1700. fault recorded so far is forgotten the first time it is gone, without the
  1701. wait: a runout fixed before resuming must be notified if it happens again a
  1702. few minutes later, while the printer sits paused. Not only the faults gone
  1703. at the change itself, because the update that flips the state can still
  1704. carry the old fault (a ``print_error`` entry stays until a payload brings
  1705. ``hms``).
  1706. """
  1707. now = time.time()
  1708. current = {_hms_notify_key(e) for e in errors}
  1709. seen = _notified_hms_errors.setdefault(printer_id, {})
  1710. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1711. if print_state is not None:
  1712. print_state = print_state.upper()
  1713. if _hms_print_state.get(printer_id, print_state) != print_state:
  1714. forget_when_gone.update(seen)
  1715. _hms_print_state[printer_id] = print_state
  1716. for key, last_seen in list(seen.items()):
  1717. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1718. del seen[key]
  1719. forget_when_gone.discard(key)
  1720. new = current - seen.keys()
  1721. for key in current:
  1722. seen[key] = now
  1723. if not seen:
  1724. _notified_hms_errors.pop(printer_id, None)
  1725. if not forget_when_gone:
  1726. _hms_forget_when_gone.pop(printer_id, None)
  1727. return _hms_errors_to_notify(errors, new)
  1728. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1729. # "Printing", -1 and 255 are "no stage" (#3211).
  1730. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1731. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1732. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1733. Records it as notified. Called only for a printing state with progress above 0.
  1734. Progress before the first layer is not progress through the print (#3211).
  1735. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1736. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1737. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1738. 75% notification together with Print Started, and since 75 was then on
  1739. record, 25 and 50 could never fire. So nothing counts while the printer
  1740. reports a layer count but has not started layer 1.
  1741. Without a layer count -- a print whose first frame carried no
  1742. ``total_layer_num``, until the pushall that asks for it is answered
  1743. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1744. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1745. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1746. reports neither keeps the old behaviour rather than never notifying.
  1747. """
  1748. if (state.layer_num or 0) < 1:
  1749. if (state.total_layers or 0) > 0:
  1750. return None
  1751. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1752. return None
  1753. progress = state.progress or 0
  1754. current_milestone = 0
  1755. if progress >= 75:
  1756. current_milestone = 75
  1757. elif progress >= 50:
  1758. current_milestone = 50
  1759. elif progress >= 25:
  1760. current_milestone = 25
  1761. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1762. _last_progress_milestone[printer_id] = current_milestone
  1763. return current_milestone
  1764. return None
  1765. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1766. """Handle printer status changes - broadcast via WebSocket."""
  1767. try:
  1768. notify_live_activities.observe(printer_id, state)
  1769. except Exception:
  1770. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1771. try:
  1772. pause_eta.observe(printer_id, state)
  1773. except Exception:
  1774. logging.getLogger(__name__).exception("Pause heads-up check failed for printer %s", printer_id)
  1775. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1776. # transitions disconnected → connected — which covers both Bambuddy
  1777. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1778. # `reconcile_stale_active_prints` exactly once for this connection so
  1779. # any archive still in `status="printing"` that can't actually be
  1780. # running anymore (printer IDLE / different subtask / empty subtask)
  1781. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1782. # finished during a disconnect window + a smart-plug power cycle
  1783. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1784. # next boot. Reconciliation runs concurrently — it must not block the
  1785. # WebSocket dedup / broadcast logic below, and the connected edge is
  1786. # marked True BEFORE the await so concurrent status updates inside
  1787. # the same connection don't re-trigger reconciliation.
  1788. #
  1789. # Wait for a real push_status before reconciling (#1679): MQTT
  1790. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1791. # the connection, BEFORE `_request_push_all` round-trips. At that
  1792. # instant the `PrinterState` is still on construction defaults — most
  1793. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1794. # If reconcile spawns here, every in-flight archive falls through to
  1795. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1796. # creates a duplicate archive on the real PRINT COMPLETE and
  1797. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1798. # keeps the #1542 mechanism intact: once the first real push_status
  1799. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1800. # fires again with the flag still False — reconcile then runs against
  1801. # actual evidence.
  1802. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1803. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1804. _printer_reconciled_since_connect[printer_id] = True
  1805. spawn_background_task(
  1806. reconcile_stale_active_prints(printer_id),
  1807. name=f"reconcile-stale-prints-{printer_id}",
  1808. )
  1809. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1810. # Re-arm so the next reconnect triggers reconciliation again.
  1811. _printer_reconciled_since_connect[printer_id] = False
  1812. # Same edge, for the calibration table the AMS card reads its K values from.
  1813. #
  1814. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1815. # tables to ask for. A `state_known` gate alone is not enough: the first
  1816. # real push_status is what makes the state known, and the nozzle fields do
  1817. # not always arrive in it. Latching there would spend this connection's one
  1818. # attempt on a printer that could not yet say what was fitted.
  1819. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1820. if (
  1821. state.connected
  1822. and state_known
  1823. and nozzle_known
  1824. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1825. ):
  1826. _printer_kprofiles_primed_since_connect[printer_id] = True
  1827. spawn_background_task(
  1828. prime_kprofile_table(printer_id),
  1829. name=f"prime-kprofiles-{printer_id}",
  1830. )
  1831. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1832. _printer_kprofiles_primed_since_connect[printer_id] = False
  1833. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1834. # else in the AMS report changing -- a power cycle does it to every slot --
  1835. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1836. # while the printer is idle; needs_check is cheap and throttled per slot.
  1837. # Guarded: nothing here may stop the status broadcast below.
  1838. try:
  1839. if not state.connected:
  1840. kprofile_drift.forget_printer(printer_id)
  1841. elif kprofile_drift.needs_check(printer_id, state):
  1842. spawn_background_task(
  1843. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1844. name=f"reapply-kprofiles-{printer_id}",
  1845. )
  1846. except Exception:
  1847. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1848. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1849. # connected → disconnected. The "back online" channel is already covered
  1850. # by the print-failure notification (firmware reports gcode_state=FAILED
  1851. # on reconnect of an interrupted print), so there is no online
  1852. # notification. The MQTT relay gets both: offline after the debounce, and
  1853. # online on the reconnect that follows a published offline.
  1854. prev_connected = _printer_last_connected.get(printer_id)
  1855. _printer_last_connected[printer_id] = state.connected
  1856. if prev_connected is True and not state.connected:
  1857. existing = _printer_offline_notify_tasks.get(printer_id)
  1858. if existing is None or existing.done():
  1859. logging.getLogger(__name__).info(
  1860. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1861. printer_id,
  1862. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1863. )
  1864. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1865. _maybe_notify_printer_offline(printer_id),
  1866. name=f"printer-offline-notify-{printer_id}",
  1867. )
  1868. elif state.connected:
  1869. # Kept until the relay can actually send online: with its broker down
  1870. # now, the next status update after the reconnect sends it.
  1871. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1872. _printer_offline_published.discard(printer_id)
  1873. printer_info = printer_manager.get_printer(printer_id)
  1874. if printer_info:
  1875. try:
  1876. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1877. except Exception as e:
  1878. logging.getLogger(__name__).warning(
  1879. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1880. )
  1881. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1882. if pending is not None and not pending.done():
  1883. logging.getLogger(__name__).info(
  1884. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1885. printer_id,
  1886. )
  1887. pending.cancel()
  1888. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1889. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1890. temps = state.temperatures or {}
  1891. nozzle_temp = round(temps.get("nozzle", 0))
  1892. bed_temp = round(temps.get("bed", 0))
  1893. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1894. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1895. # Auto-detect dual-nozzle printers from MQTT temperature data
  1896. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1897. _nozzle_count_updated.add(printer_id)
  1898. # Update nozzle_count in database
  1899. async with async_session() as db:
  1900. from backend.app.models.printer import Printer
  1901. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1902. printer = result.scalar_one_or_none()
  1903. if printer and printer.nozzle_count != 2:
  1904. printer.nozzle_count = 2
  1905. await db.commit()
  1906. logging.getLogger(__name__).info(
  1907. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1908. )
  1909. # Include target temps for heating phase detection
  1910. bed_target = round(temps.get("bed_target", 0))
  1911. nozzle_target = round(temps.get("nozzle_target", 0))
  1912. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1913. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1914. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1915. #
  1916. # dry_countdown_stalled rides along because it is the one drying signal the
  1917. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1918. # dry_time stopped moving, so on the frame that flips it every other member
  1919. # of this key is identical and the push would be deduplicated away. Mid-print
  1920. # a temperature would eventually break the tie, but a parked command on an
  1921. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1922. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1923. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1924. ams_dry_key = (
  1925. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1926. if state.raw_data
  1927. else ()
  1928. )
  1929. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1930. #
  1931. # The filament identity fields are here because Configure Slot writes
  1932. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1933. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1934. # matched, this function returned before broadcasting, and the card kept
  1935. # showing the old filament until the 30s fallback poll or a page reload —
  1936. # even though the configure route asks the printer for a fresh pushall and
  1937. # that push does carry the new values. Reset always worked, because it
  1938. # clears tray_type.
  1939. #
  1940. # These fields only change when someone configures a slot or swaps a spool,
  1941. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1942. ams_tray_key = (
  1943. tuple(
  1944. (
  1945. t.get("id"),
  1946. t.get("tray_type", ""),
  1947. t.get("state"),
  1948. t.get("tray_color", ""),
  1949. t.get("tray_info_idx", ""),
  1950. t.get("tray_sub_brands", ""),
  1951. t.get("cali_idx"),
  1952. )
  1953. for a in (state.raw_data.get("ams") or [])
  1954. for t in a.get("tray", [])
  1955. )
  1956. if state.raw_data
  1957. else ()
  1958. )
  1959. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1960. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1961. # in the AMS change-hash (tray fields only, and widening that would fire
  1962. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1963. # screen changed no key at all and the card's inlet badges sat stale until a
  1964. # reload. Like the filament-backup flag, these only move when someone
  1965. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1966. fts_key = (
  1967. state.fila_switch.installed if state.fila_switch else False,
  1968. tuple(sorted(state.ams_switch_inlet.items())),
  1969. # Which hotend holds which slot. Unlike the two above this does move
  1970. # mid-print, on every filament change — but only between discrete slots,
  1971. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1972. # it live: it decides which hotend the Load dialog may offer and whether
  1973. # Unload has anything to act on.
  1974. tuple(
  1975. sorted(
  1976. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1977. # Sort on the extruder id alone: the other members are nullable
  1978. # and comparing None with an int raises.
  1979. key=lambda entry: entry[0],
  1980. )
  1981. ),
  1982. )
  1983. status_key = (
  1984. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1985. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1986. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1987. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1988. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1989. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1990. )
  1991. # Fields that change only when the machine does (a nozzle swap, a firmware
  1992. # update, developer mode) or once per print (its AMS mapping): no traffic,
  1993. # but on an idle printer nothing else moves the key when they change.
  1994. machine_key = (
  1995. tuple((n.nozzle_type, n.nozzle_diameter) for n in (state.nozzles or [])),
  1996. state.firmware_version,
  1997. state.developer_mode,
  1998. tuple(state.print_ams_mapping) if isinstance(state.print_ams_mapping, list) else None,
  1999. # Cooling/heating, switched on the printer's screen too: on an idle
  2000. # printer nothing else moves the key (PSF-4).
  2001. state.airduct_mode,
  2002. )
  2003. status_key = f"{status_key}:{machine_key}"
  2004. is_active_print = state.state in _ACTIVE_PRINT_STATES
  2005. if not is_active_print:
  2006. _unauthorized_print_kill_sent.discard(printer_id)
  2007. elif printer_id in _unauthorized_print_kill_sent:
  2008. # stop_print() was already sent for this print; avoid all further
  2009. # ownership and settings work until the printer leaves an active state.
  2010. pass
  2011. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  2012. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  2013. _unauthorized_print_kill_sent.discard(printer_id)
  2014. else:
  2015. kill_switch_enabled = False
  2016. authorization: bool | None = None
  2017. status_logger = logging.getLogger(__name__)
  2018. try:
  2019. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  2020. if kill_switch_enabled:
  2021. async with async_session() as db:
  2022. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  2023. except Exception as e:
  2024. # Fail safe: a database/reconciliation error must never turn into an
  2025. # irreversible stop of a print whose ownership is still unknown.
  2026. authorization = None
  2027. status_logger.warning(
  2028. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  2029. )
  2030. if not kill_switch_enabled or authorization is True:
  2031. _unauthorized_print_kill_sent.discard(printer_id)
  2032. elif authorization is None:
  2033. _unauthorized_print_kill_sent.discard(printer_id)
  2034. status_logger.debug(
  2035. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  2036. printer_id,
  2037. )
  2038. else:
  2039. try:
  2040. stopped = printer_manager.stop_print(printer_id)
  2041. if stopped:
  2042. _unauthorized_print_kill_sent.add(printer_id)
  2043. _kill_switch_stopped.add(printer_id)
  2044. printer_info = printer_manager.get_printer(printer_id)
  2045. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  2046. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  2047. notification_data = {
  2048. "status": "stopped",
  2049. "filename": state.gcode_file or state.current_print or "",
  2050. "subtask_name": state.subtask_name or "",
  2051. "progress": state.progress,
  2052. "reason": "unauthorized_print",
  2053. }
  2054. status_logger.warning(
  2055. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  2056. printer_id,
  2057. state.state,
  2058. )
  2059. try:
  2060. await ws_manager.broadcast(
  2061. {
  2062. "type": "kill_switch_triggered",
  2063. "printer_id": printer_id,
  2064. "printer_name": printer_name,
  2065. "filename": filename,
  2066. "reason": "unauthorized_print",
  2067. }
  2068. )
  2069. except Exception as e:
  2070. status_logger.warning(
  2071. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  2072. )
  2073. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  2074. if previous_task is not None and not previous_task.done():
  2075. previous_task.cancel()
  2076. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  2077. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  2078. name=f"kill-switch-notification-{printer_id}",
  2079. )
  2080. else:
  2081. status_logger.warning(
  2082. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  2083. printer_id,
  2084. state.state,
  2085. )
  2086. except Exception as e:
  2087. status_logger.warning(
  2088. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  2089. )
  2090. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  2091. try:
  2092. printer_info = printer_manager.get_printer(printer_id)
  2093. if printer_info:
  2094. await mqtt_relay.on_printer_status(
  2095. printer_id,
  2096. state,
  2097. printer_info.name,
  2098. printer_info.serial_number,
  2099. printer_manager.is_awaiting_plate_clear(printer_id),
  2100. )
  2101. except Exception:
  2102. pass # Don't fail status callback if MQTT fails
  2103. if _last_status_broadcast.get(printer_id) == status_key:
  2104. return # No change, skip WebSocket broadcast
  2105. _last_status_broadcast[printer_id] = status_key
  2106. # Check for progress milestone notifications (25%, 50%, 75%)
  2107. progress = state.progress or 0
  2108. is_printing = state.state in ("RUNNING", "PRINTING")
  2109. if is_printing and progress > 0:
  2110. current_milestone = _progress_milestone_to_notify(printer_id, state)
  2111. if current_milestone is not None:
  2112. try:
  2113. from backend.app.models.printer import Printer
  2114. # Read the printer in a short session and release the connection
  2115. # BEFORE the ~15s camera snapshot below — holding it across the grab
  2116. # pinned a pooled connection per milestone, per printer (issue #2572).
  2117. async with async_session() as db:
  2118. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2119. printer = result.scalar_one_or_none()
  2120. printer_name = printer.name if printer else f"Printer {printer_id}"
  2121. filename = state.subtask_name or state.gcode_file or "Unknown"
  2122. # remaining_time is in minutes, convert to seconds for notification
  2123. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  2124. # Capture camera snapshot for notification image attachment (no DB held).
  2125. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  2126. # Notification send needs a session (provider/template lookups).
  2127. async with async_session() as db:
  2128. await notification_service.on_print_progress(
  2129. printer_id,
  2130. printer_name,
  2131. filename,
  2132. current_milestone,
  2133. db,
  2134. remaining_time_seconds,
  2135. image_data=image_data,
  2136. )
  2137. except Exception as e:
  2138. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  2139. elif progress < 5:
  2140. # Reset milestone tracking when print restarts or new print begins
  2141. _last_progress_milestone[printer_id] = 0
  2142. _first_layer_notified[printer_id] = False
  2143. # HMS error codes that should not trigger notifications even though they
  2144. # have known descriptions (e.g. user-initiated actions, not real errors).
  2145. _HMS_NOTIFICATION_SUPPRESS = {
  2146. "0500_400E", # Printing was cancelled (user action, not an error)
  2147. }
  2148. # Check for new HMS errors and send notifications
  2149. current_hms_errors = getattr(state, "hms_errors", []) or []
  2150. if current_hms_errors:
  2151. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  2152. if new_errors:
  2153. try:
  2154. from backend.app.models.printer import Printer
  2155. # Read the printer in a short session and release the connection
  2156. # BEFORE the ~15s camera snapshot below (issue #2572).
  2157. async with async_session() as db:
  2158. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2159. printer = result.scalar_one_or_none()
  2160. printer_name = printer.name if printer else f"Printer {printer_id}"
  2161. # Format error details for notification
  2162. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  2163. module_names = {
  2164. 0x03: "Print/Task",
  2165. 0x05: "Nozzle/Extruder",
  2166. 0x07: "AMS/Filament",
  2167. 0x0C: "Motion Controller",
  2168. 0x12: "Chamber",
  2169. }
  2170. # Capture camera snapshot once for all error notifications (no DB held).
  2171. error_image_data = await _capture_snapshot_for_notification(
  2172. printer_id, printer, logging.getLogger(__name__)
  2173. )
  2174. # Notification sends need a session (provider/template lookups).
  2175. async with async_session() as db:
  2176. sent_count = 0
  2177. for error in new_errors:
  2178. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  2179. # Build short code like "0700_8010"
  2180. # Mask to 16 bits to handle printers that send larger values
  2181. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  2182. error_code_masked = error_code_int & 0xFFFF
  2183. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  2184. # Only notify for errors Bambu publishes text for — printers
  2185. # send undocumented codes that aren't real errors, and Bambu
  2186. # lists some with empty text. Resolved at parse time (#2926);
  2187. # short_code is still needed for the suppression set below.
  2188. description = error.description
  2189. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  2190. continue
  2191. error_type = f"{module_name} Error"
  2192. error_detail = description
  2193. await notification_service.on_printer_error(
  2194. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  2195. )
  2196. sent_count += 1
  2197. if sent_count:
  2198. logging.getLogger(__name__).info(
  2199. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  2200. )
  2201. # Also publish to MQTT relay (no DB): every new fault that
  2202. # counts, with or without text, the same set the UI counts.
  2203. printer_info = printer_manager.get_printer(printer_id)
  2204. if printer_info:
  2205. errors_data = [
  2206. {
  2207. "code": e.code,
  2208. "attr": e.attr,
  2209. "module": e.module,
  2210. "severity": e.severity,
  2211. }
  2212. for e in new_errors
  2213. ]
  2214. await mqtt_relay.on_printer_error(
  2215. printer_id, printer_info.name, printer_info.serial_number, errors_data
  2216. )
  2217. except Exception as e:
  2218. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  2219. else:
  2220. # No HMS errors: nothing to send, but faults gone long enough (or gone
  2221. # across a print state change) are forgotten. Some codes, e.g. chamber
  2222. # temperature regulation during PETG prints, toggle every few seconds.
  2223. _take_new_hms_faults(printer_id, [], state.state)
  2224. await ws_manager.send_printer_status(
  2225. printer_id,
  2226. printer_state_to_dict(
  2227. state,
  2228. printer_id,
  2229. printer_manager.get_model(printer_id),
  2230. printer_manager.get_drying_targets(printer_id),
  2231. ),
  2232. )
  2233. def _is_bambu_uuid(tray_uuid: str) -> bool:
  2234. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  2235. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  2236. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  2237. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  2238. K-profiles are per-nozzle and the printer's calibration table is numbered
  2239. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  2240. switch's other inlet therefore silently invalidates every configured slot in
  2241. it: the index stays put and now resolves against the other nozzle's table.
  2242. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  2243. and 0.020 on the right kept the left profile after the move, and a manual
  2244. RFID re-read only re-asserted the same wrong one.
  2245. Configuring a slot is a deliberate preparation step, so this re-selects
  2246. rather than re-configures: only the calibration binding moves, and only for
  2247. slots whose spool already has a stored profile for the new nozzle. A slot
  2248. Bambuddy knows nothing about is left exactly as the operator left it.
  2249. """
  2250. logger = logging.getLogger(__name__)
  2251. target_extruder = extruder_for_inlet(inlet)
  2252. if target_extruder is None:
  2253. return
  2254. client = printer_manager.get_client(printer_id)
  2255. state = printer_manager.get_status(printer_id)
  2256. if not client or not state or not state.raw_data:
  2257. return
  2258. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  2259. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  2260. # the nozzle width, which changes both the K profile to select and the
  2261. # preset the slot should carry.
  2262. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  2263. ams_raw = state.raw_data.get("ams")
  2264. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2265. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  2266. if not unit:
  2267. return
  2268. try:
  2269. async with async_session() as db:
  2270. for tray in unit.get("tray", []):
  2271. tray_id = int(tray.get("id", -1))
  2272. if tray_id < 0 or not tray.get("tray_type"):
  2273. continue
  2274. current_idx = tray.get("cali_idx")
  2275. profile = await find_slot_kprofile_for_extruder(
  2276. db,
  2277. printer_id,
  2278. ams_id,
  2279. tray_id,
  2280. target_extruder,
  2281. nozzle_diameter,
  2282. printer_manager.get_model(printer_id),
  2283. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2284. )
  2285. if profile is None or profile.cali_idx is None:
  2286. continue
  2287. if current_idx == profile.cali_idx:
  2288. continue # Already on the right one.
  2289. logger.info(
  2290. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2291. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2292. printer_id,
  2293. ams_id,
  2294. tray_id,
  2295. inlet,
  2296. target_extruder,
  2297. profile.name,
  2298. current_idx,
  2299. profile.cali_idx,
  2300. profile.k_value,
  2301. )
  2302. client.extrusion_cali_sel(
  2303. ams_id=ams_id,
  2304. tray_id=tray_id,
  2305. cali_idx=profile.cali_idx,
  2306. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2307. nozzle_diameter=nozzle_diameter,
  2308. )
  2309. except Exception as e:
  2310. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2311. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2312. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2313. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2314. from the delayed re-check -- which is why it takes the AMS data and print
  2315. state as arguments instead of reading them from the push (#3186).
  2316. """
  2317. logger = logging.getLogger(__name__)
  2318. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2319. # Auto-unlink spool assignments with stale fingerprints. Under the
  2320. # per-printer assignment lock since #3186: the held-removal re-check runs
  2321. # this outside any MQTT push, so it can now overlap one.
  2322. try:
  2323. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2324. from sqlalchemy.orm import selectinload
  2325. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2326. from backend.app.models.spool import Spool as _Spool
  2327. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2328. from backend.app.services.ams_slot_presence import spool_present
  2329. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2330. # Built-in assignments only. Since #2812 they survive a switch to
  2331. # Spoolman mode rather than being deleted by it, and this pass ends
  2332. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2333. # time as the AMS contents changed under the other mode, undoing the
  2334. # preservation more slowly but just as completely.
  2335. assignments = []
  2336. if not await spoolman_owns_assignments(db):
  2337. result = await db.execute(
  2338. select(SA)
  2339. .where(SA.printer_id == printer_id)
  2340. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2341. )
  2342. assignments = result.scalars().all()
  2343. # ``printing_now`` (top of this function) keeps a runout from
  2344. # unlinking the spool that fed the print — the next idle-time pass
  2345. # unlinks it if the user really did take it out.
  2346. stale = []
  2347. # Removals this pass is holding rather than unlinking (#3186).
  2348. held: set[tuple] = set()
  2349. for assignment in assignments:
  2350. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2351. if assignment.ams_id == 255:
  2352. ps = printer_manager.get_status(printer_id)
  2353. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2354. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2355. current_tray = None
  2356. for vt in vt_tray_raw:
  2357. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2358. current_tray = vt
  2359. break
  2360. if not current_tray:
  2361. # vt_tray data may not have arrived yet — keep assignment
  2362. continue
  2363. else:
  2364. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2365. if not current_tray:
  2366. if printing_now:
  2367. logger.info(
  2368. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2369. assignment.spool_id,
  2370. assignment.ams_id,
  2371. assignment.tray_id,
  2372. )
  2373. continue
  2374. # A whole AMS unit can drop out of one push and come back in
  2375. # the next; only a slot that stays gone is a removal (#3186).
  2376. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2377. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2378. held.add(hold_key)
  2379. logger.info(
  2380. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2381. "unlinking if it is still gone in %ds",
  2382. assignment.spool_id,
  2383. assignment.ams_id,
  2384. assignment.tray_id,
  2385. int(slot_unlink_grace.GRACE_SECONDS),
  2386. )
  2387. continue
  2388. logger.info(
  2389. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2390. assignment.spool_id,
  2391. assignment.ams_id,
  2392. assignment.tray_id,
  2393. )
  2394. stale.append(assignment) # Slot empty
  2395. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2396. # A Bambu Lab spool is in this slot — check if it's the same spool
  2397. # that's currently assigned. If yes, keep the assignment (avoids
  2398. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2399. # the printer's filament preset on every startup).
  2400. tray_uuid = current_tray.get("tray_uuid", "")
  2401. tag_uid = current_tray.get("tag_uid", "")
  2402. spool = assignment.spool
  2403. spool_matches = False
  2404. if spool:
  2405. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2406. spool.tag_uid
  2407. and tag_uid
  2408. and tag_uid != "0000000000000000"
  2409. and spool.tag_uid.upper() == tag_uid.upper()
  2410. ):
  2411. spool_matches = True
  2412. if spool_matches:
  2413. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2414. cur_color = current_tray.get("tray_color", "")
  2415. cur_type = current_tray.get("tray_type", "")
  2416. fp_color = assignment.fingerprint_color or ""
  2417. fp_type = assignment.fingerprint_type or ""
  2418. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2419. assignment.fingerprint_color = cur_color
  2420. assignment.fingerprint_type = cur_type
  2421. logger.debug(
  2422. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2423. assignment.spool_id,
  2424. assignment.ams_id,
  2425. assignment.tray_id,
  2426. )
  2427. continue
  2428. # Different BL spool or unrecognized — unlink so auto-assign can match
  2429. logger.info(
  2430. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2431. assignment.spool_id,
  2432. assignment.ams_id,
  2433. assignment.tray_id,
  2434. tray_uuid,
  2435. )
  2436. stale.append(assignment)
  2437. else:
  2438. cur_color = current_tray.get("tray_color", "")
  2439. cur_type = current_tray.get("tray_type", "")
  2440. cur_state = current_tray.get("state")
  2441. fp_color = assignment.fingerprint_color or ""
  2442. fp_type = assignment.fingerprint_type or ""
  2443. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2444. # the slot was empty when the user pre-assigned via SpoolBuddy
  2445. # (the firmware drops ams_filament_setting on empty slots, so
  2446. # MQTT was deferred). The moment any filament gets inserted
  2447. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2448. # reconfigured spool — fire the deferred configuration.
  2449. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2450. # extruder" code) OR, on firmwares that don't use the state
  2451. # enum meaningfully, a non-empty tray_type when state is
  2452. # NOT one of the firmware's explicit empty signals (9, 10).
  2453. # state-only was wrong for firmwares that never set 11 — A1
  2454. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2455. # always report state=3 — so the replay never fired for them
  2456. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2457. # explicit "empty" signals authoritative over any stale
  2458. # tray_type that might survive the relay's auto-clearing.
  2459. #
  2460. # tray_exist_bits comes first because that guard cannot tell
  2461. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2462. # writes state=9 when the bit is 0 and leaves it there when the
  2463. # bit returns. A non-RFID spool inserted into a pre-assigned
  2464. # slot brings no tray_type with it, so the stale 9 made this
  2465. # expression false forever and the deferred config never fired
  2466. # — the deadlock #1322 removed from the assign path, still in
  2467. # place here (#3084, #3100).
  2468. loaded = spool_present(current_tray) is True or (
  2469. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2470. )
  2471. if not fp_type.strip() and loaded and assignment.spool:
  2472. # The fingerprint ends this replay. Not recorded when nothing
  2473. # could be sent (no MQTT client while the printer reconnects),
  2474. # so the next AMS change tries again. An attempt that raised is
  2475. # recorded as before: it may have sent part of the commands and
  2476. # would raise again on every change, remain% steps included.
  2477. configured: bool | None = False
  2478. try:
  2479. from backend.app.api.routes.inventory import (
  2480. apply_spool_to_slot_via_mqtt,
  2481. )
  2482. configured = await apply_spool_to_slot_via_mqtt(
  2483. db=db,
  2484. current_user=None,
  2485. spool=assignment.spool,
  2486. printer_id=printer_id,
  2487. ams_id=assignment.ams_id,
  2488. tray_id=assignment.tray_id,
  2489. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2490. current_tray_type=cur_type,
  2491. current_tray_sub_brands=current_tray.get("tray_sub_brands", ""),
  2492. )
  2493. except Exception:
  2494. logger.exception(
  2495. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2496. assignment.spool_id,
  2497. printer_id,
  2498. assignment.ams_id,
  2499. assignment.tray_id,
  2500. )
  2501. configured = None
  2502. if configured is False:
  2503. logger.warning(
  2504. "Pre-config not sent for spool %d on printer %d AMS%d-T%d (no MQTT client); "
  2505. "retrying on the next AMS change",
  2506. assignment.spool_id,
  2507. printer_id,
  2508. assignment.ams_id,
  2509. assignment.tray_id,
  2510. )
  2511. else:
  2512. if configured:
  2513. logger.info(
  2514. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2515. assignment.spool_id,
  2516. printer_id,
  2517. assignment.ams_id,
  2518. assignment.tray_id,
  2519. )
  2520. assignment.fingerprint_color = cur_color
  2521. assignment.fingerprint_type = cur_type
  2522. continue
  2523. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2524. # Blank tray data mid-print is a runout, not a swap: the
  2525. # firmware clears colour and type when it unloads a spool
  2526. # it just emptied. Unlinking here would erase the record
  2527. # of which spool fed the print so far.
  2528. if printing_now and not cur_color.strip() and not cur_type.strip():
  2529. logger.info(
  2530. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2531. "(runout?)",
  2532. assignment.spool_id,
  2533. assignment.ams_id,
  2534. assignment.tray_id,
  2535. )
  2536. continue
  2537. # Same reasoning off the print, on firmware's own say-so:
  2538. # a blank tray report from a slot whose tray_exist_bits
  2539. # bit is set describes a spool the AMS cannot identify —
  2540. # a non-RFID one, or one whose slot was reset — not a
  2541. # spool that was taken out. Deleting the assignment there
  2542. # threw away the identity the user had supplied, which is
  2543. # the only place it existed (#3100). A slot the bit calls
  2544. # empty, or one that carries no bit at all, still unlinks.
  2545. #
  2546. # Unless the slot was reported empty first: a removal
  2547. # already held means a spool came out and another went
  2548. # in, so the blank report keeps the hold running below
  2549. # rather than cancelling it (#3186).
  2550. if (
  2551. spool_present(current_tray) is True
  2552. and not cur_color.strip()
  2553. and not cur_type.strip()
  2554. and not slot_unlink_grace.is_held(
  2555. printer_id,
  2556. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2557. )
  2558. ):
  2559. logger.info(
  2560. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2561. "tray reports no filament data yet",
  2562. assignment.spool_id,
  2563. assignment.ams_id,
  2564. assignment.tray_id,
  2565. )
  2566. continue
  2567. # A blank report the presence bit does not vouch for is
  2568. # still only one push. An idle X1C cleared a whole AMS
  2569. # unit's bits, colour and type for a moment and lost
  2570. # four saved assignments that way (#3186); unlink only
  2571. # if the slot is still blank after the grace period.
  2572. if not cur_color.strip() and not cur_type.strip():
  2573. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2574. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2575. held.add(hold_key)
  2576. logger.info(
  2577. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2578. "unlinking if it is still blank in %ds",
  2579. assignment.spool_id,
  2580. assignment.ams_id,
  2581. assignment.tray_id,
  2582. int(slot_unlink_grace.GRACE_SECONDS),
  2583. )
  2584. continue
  2585. # Fingerprint mismatch — but check if tray now matches the
  2586. # assigned spool (e.g. auto-configure changed the tray).
  2587. # Both sides are reduced to the type the slot can carry
  2588. # before comparing: the assign path writes that rather
  2589. # than the spool's raw material (#2902), so a spool whose
  2590. # material is a product line — "PLA+", "HTPLA" — reports
  2591. # back as "PLA" and would otherwise fail this check and
  2592. # be auto-unlinked from the slot it was just assigned to.
  2593. # Reducing the printer's side too keeps slots configured
  2594. # by an older Bambuddy, still reporting "PLA+", matching.
  2595. spool = assignment.spool
  2596. if spool:
  2597. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2598. # Two ways the assign path can have arrived at the
  2599. # slot's type, so both count as "we wrote this".
  2600. # The material column is one; the spool's preset is
  2601. # the other, and it outranks the material when the
  2602. # spool has one -- a spool whose material says PLA
  2603. # and whose preset is "Bambu PLA Aero" puts
  2604. # PLA-AERO in the slot (#2902). Read from the stored
  2605. # preset name rather than resolving the preset,
  2606. # because this runs on every AMS push and a cloud
  2607. # lookup here would be both slow and unavailable on
  2608. # the unauthenticated replay path.
  2609. spool_types = {printer_filament_type(spool.material).upper()}
  2610. if spool.slicer_filament_name:
  2611. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2612. # An imported local preset stores its type outright,
  2613. # which is what the assign path used -- and the name
  2614. # above may be unset. One keyed read, and only on a
  2615. # mismatch, which is rare.
  2616. #
  2617. # slicer_filament is free text up to fifty characters,
  2618. # so the digits have to be checked against the range
  2619. # of the integer primary key they are about to be
  2620. # compared with. Postgres raises on an out-of-range
  2621. # integer rather than simply not matching, and that
  2622. # would poison this session and abandon the rest of
  2623. # the cleanup pass.
  2624. lp_ref = (spool.slicer_filament or "").strip()
  2625. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2626. from backend.app.models.local_preset import LocalPreset as _LP
  2627. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2628. if lp_type:
  2629. spool_types.add(printer_filament_type(lp_type).upper())
  2630. if (
  2631. _colors_similar(cur_color, spool_color)
  2632. and printer_filament_type(cur_type).upper() in spool_types
  2633. ):
  2634. logger.info(
  2635. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2636. assignment.spool_id,
  2637. assignment.ams_id,
  2638. assignment.tray_id,
  2639. )
  2640. assignment.fingerprint_color = cur_color
  2641. assignment.fingerprint_type = cur_type
  2642. continue
  2643. logger.info(
  2644. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2645. assignment.spool_id,
  2646. assignment.ams_id,
  2647. assignment.tray_id,
  2648. cur_color,
  2649. cur_type,
  2650. fp_color,
  2651. fp_type,
  2652. spool.rgba if spool else "?",
  2653. spool.material if spool else "?",
  2654. )
  2655. stale.append(assignment) # Spool changed
  2656. slot_unlink_grace.settle(printer_id, "inventory", held)
  2657. # Snapshot slots before delete — ORM attribute access after the
  2658. # commit would refresh against a deleted row.
  2659. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2660. for a in stale:
  2661. await db.delete(a)
  2662. if stale:
  2663. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2664. # Commit any changes (stale deletions and/or fingerprint updates)
  2665. await db.commit()
  2666. # Tell open browsers the assignment is gone (#2575). Only the manual
  2667. # REST assign/unassign endpoints broadcast this event; without it the
  2668. # frontend's spool-assignments cache keeps rendering the unlinked
  2669. # spool on the slot until an unrelated refetch — which reads exactly
  2670. # like "the fix didn't work" (reporter verified: a browser refresh
  2671. # after the swap showed the correct state all along).
  2672. for ams_id, tray_id in unlinked_slots:
  2673. await ws_manager.broadcast(
  2674. {
  2675. "type": "spool_assignment_changed",
  2676. "printer_id": printer_id,
  2677. "ams_id": ams_id,
  2678. "tray_id": tray_id,
  2679. }
  2680. )
  2681. except Exception as e:
  2682. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2683. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2684. """Delete Spoolman slot rows whose held removal has run its grace period.
  2685. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2686. talks to Spoolman for every tray; this only needs the local rows, so it
  2687. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2688. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2689. not in a slot the presence bit calls occupied -- and nothing else.
  2690. """
  2691. logger = logging.getLogger(__name__)
  2692. try:
  2693. async with async_session() as db:
  2694. from backend.app.api.routes.settings import get_setting
  2695. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2696. from backend.app.services.ams_slot_presence import spool_present
  2697. enabled = await get_setting(db, "spoolman_enabled")
  2698. if not enabled or enabled.lower() != "true":
  2699. return
  2700. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2701. if sync_mode and sync_mode != "auto":
  2702. return
  2703. trays: dict[tuple[int, int], dict] = {}
  2704. for ams_unit in ams_data or []:
  2705. if not isinstance(ams_unit, dict):
  2706. continue
  2707. for tray in ams_unit.get("tray", []):
  2708. if isinstance(tray, dict):
  2709. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2710. rows = (
  2711. (
  2712. await db.execute(
  2713. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2714. )
  2715. )
  2716. .scalars()
  2717. .all()
  2718. )
  2719. held: set[tuple] = set()
  2720. expired: list[tuple[int, int]] = []
  2721. for row in rows:
  2722. tray = trays.get((row.ams_id, row.tray_id))
  2723. if tray is None or printing_now:
  2724. continue
  2725. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2726. continue
  2727. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2728. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2729. continue
  2730. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2731. expired.append((row.ams_id, row.tray_id))
  2732. else:
  2733. held.add(hold_key)
  2734. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2735. if not expired:
  2736. return
  2737. # A statement rather than ORM deletes, like the sync pass: the two
  2738. # can overlap, and a row the other already removed must not fail
  2739. # this commit.
  2740. for ams_id, tray_id in expired:
  2741. await db.execute(
  2742. delete(SpoolmanSlotAssignment).where(
  2743. SpoolmanSlotAssignment.printer_id == printer_id,
  2744. SpoolmanSlotAssignment.ams_id == ams_id,
  2745. SpoolmanSlotAssignment.tray_id == tray_id,
  2746. )
  2747. )
  2748. await db.commit()
  2749. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2750. for ams_id, tray_id in expired:
  2751. await ws_manager.broadcast(
  2752. {
  2753. "type": "spool_assignment_changed",
  2754. "printer_id": printer_id,
  2755. "ams_id": ams_id,
  2756. "tray_id": tray_id,
  2757. }
  2758. )
  2759. except Exception as e:
  2760. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2761. async def _recheck_held_unlinks(printer_id: int) -> None:
  2762. """Re-run just the slot cleanup against the printer's current AMS state.
  2763. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2764. passes otherwise run only when the AMS hash changes, and a slot that went
  2765. empty and stayed empty may never change it again.
  2766. """
  2767. status = printer_manager.get_status(printer_id)
  2768. # A disconnected printer's state is its last report, not a new one: acting
  2769. # on it would "confirm" a removal nobody has seen for the whole grace
  2770. # period. Leave the holds; the first push after reconnecting decides.
  2771. if status is None or not status.connected:
  2772. return
  2773. ams_raw = status.raw_data.get("ams")
  2774. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2775. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2776. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2777. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2778. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2779. async def on_ams_change(printer_id: int, ams_data: list):
  2780. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2781. logger = logging.getLogger(__name__)
  2782. # Snapshot BEFORE any await: if a print is active, or a finished one is
  2783. # still being charged, skip weight sync later. on_print_complete may pop
  2784. # _active_sessions during our awaits (#880).
  2785. from backend.app.services.usage_tracker import printer_is_charging
  2786. _print_active = printer_is_charging(printer_id)
  2787. # A slot that reports empty while a print is running is a filament runout,
  2788. # not a spool swap: the spool is still physically in the AMS, just
  2789. # consumed. Dropping either inventory backend's slot link there loses the
  2790. # only record of which spool fed the print, so the completion path can't
  2791. # charge the runout segment to anything. Both cleanup passes below consult
  2792. # this; computed once, up front, so neither depends on the other having run.
  2793. _unlink_state = printer_manager.get_status(printer_id)
  2794. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2795. # The session alone is not enough: a restart that finds a stale persisted
  2796. # session registers none for the print that is running.
  2797. _print_active = _print_active or printing_now
  2798. # MQTT relay - publish AMS change
  2799. try:
  2800. printer_info = printer_manager.get_printer(printer_id)
  2801. if printer_info:
  2802. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2803. except Exception:
  2804. pass # Don't fail AMS callback if MQTT fails
  2805. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2806. # This ensures frontend gets immediate updates when AMS slots are configured
  2807. try:
  2808. state = printer_manager.get_status(printer_id)
  2809. if state:
  2810. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2811. await ws_manager.send_printer_status(
  2812. printer_id,
  2813. printer_state_to_dict(
  2814. state,
  2815. printer_id,
  2816. printer_manager.get_model(printer_id),
  2817. printer_manager.get_drying_targets(printer_id),
  2818. ),
  2819. )
  2820. except Exception as e:
  2821. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2822. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2823. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2824. # Serialised per-printer via services/ams_assignment_lock: MQTT bursts can deliver
  2825. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2826. # "no existing assignment" for the same (printer, ams, tray) and race to
  2827. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2828. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2829. # bug stayed latent there. See services/ams_assignment_lock for details.
  2830. try:
  2831. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2832. from sqlalchemy.orm import selectinload
  2833. from backend.app.api.routes.settings import get_setting
  2834. from backend.app.models.spool import Spool
  2835. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2836. from backend.app.services.spool_tag_matcher import (
  2837. auto_assign_spool,
  2838. create_spool_from_tray,
  2839. find_matching_untagged_spool,
  2840. get_spool_by_tag,
  2841. is_bambu_tag,
  2842. is_valid_tag,
  2843. link_tag_to_inventory_spool,
  2844. tag_belongs_to_archived_spool,
  2845. )
  2846. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2847. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2848. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2849. if not _spoolman_on or _spoolman_on.lower() != "true":
  2850. for ams_unit in ams_data:
  2851. if not isinstance(ams_unit, dict):
  2852. continue
  2853. ams_id = int(ams_unit.get("id", 0))
  2854. for tray in ams_unit.get("tray", []):
  2855. if not isinstance(tray, dict):
  2856. continue
  2857. tray_id = int(tray.get("id", 0))
  2858. tag_uid = tray.get("tag_uid", "")
  2859. tray_uuid = tray.get("tray_uuid", "")
  2860. tray_info_idx = tray.get("tray_info_idx", "")
  2861. if not tray.get("tray_type"):
  2862. # Slot reported empty — drop any cached unknown-tag
  2863. # broadcast so reinserting the same spool re-prompts.
  2864. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2865. continue # Empty slot
  2866. # Check if assignment already exists for this slot
  2867. existing = await db.execute(
  2868. select(SA)
  2869. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2870. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2871. )
  2872. existing_assignment = existing.scalar_one_or_none()
  2873. if existing_assignment:
  2874. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2875. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2876. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2877. # Skip during active prints: the usage tracker handles deduction
  2878. # precisely via 3MF data on print completion. Without this guard the
  2879. # AMS remain% SET and the usage tracker ADD both fire from the same
  2880. # MQTT message, doubling the deduction (#880).
  2881. if _print_active:
  2882. continue
  2883. remain_raw = tray.get("remain")
  2884. if (
  2885. remain_raw is not None
  2886. and existing_assignment.spool
  2887. and not existing_assignment.spool.weight_locked
  2888. ):
  2889. try:
  2890. remain_val = int(remain_raw)
  2891. except (TypeError, ValueError):
  2892. remain_val = -1
  2893. if 1 <= remain_val <= 100:
  2894. lw = existing_assignment.spool.label_weight or 1000
  2895. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2896. current_used = existing_assignment.spool.weight_used or 0
  2897. if new_used > current_used + 1:
  2898. # Rechecked in the statement: the spool was loaded
  2899. # before this, and a weight set by hand (or weighed)
  2900. # and locked since then must stay (WL-6).
  2901. result = cast(
  2902. CursorResult,
  2903. await db.execute(
  2904. update(Spool)
  2905. .where(
  2906. Spool.id == existing_assignment.spool_id,
  2907. Spool.weight_locked.is_not(True),
  2908. func.coalesce(Spool.weight_used, 0) < new_used - 1,
  2909. )
  2910. .values(weight_used=new_used)
  2911. ),
  2912. )
  2913. await db.commit()
  2914. if result.rowcount:
  2915. logger.info(
  2916. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2917. existing_assignment.spool_id,
  2918. current_used,
  2919. new_used,
  2920. remain_val,
  2921. )
  2922. await ws_manager.broadcast({"type": "inventory_changed"})
  2923. # A K-profile the slot lost (the default K after a reset or
  2924. # power cycle) is put back by kprofile_drift on the next idle
  2925. # push; a different real profile was picked on purpose and
  2926. # stays (#3219, item 44).
  2927. continue
  2928. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2929. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2930. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2931. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  2932. # An archived spool still in the AMS: the slot
  2933. # stays free rather than adopting its tag.
  2934. continue
  2935. if not spool:
  2936. # Try matching an untagged inventory spool (same material/color)
  2937. spool = await find_matching_untagged_spool(db, tray)
  2938. if spool:
  2939. await link_tag_to_inventory_spool(db, spool, tray)
  2940. elif _auto_add_unknown:
  2941. spool = await create_spool_from_tray(db, tray)
  2942. else:
  2943. # Auto-add disabled: surface the slot so the
  2944. # user can add it manually via the UI.
  2945. await _broadcast_unknown_tag(
  2946. printer_id=printer_id,
  2947. ams_id=ams_id,
  2948. tray_id=tray_id,
  2949. tag_uid=tag_uid,
  2950. tray_uuid=tray_uuid,
  2951. tray_type=tray.get("tray_type"),
  2952. tray_color=tray.get("tray_color"),
  2953. tray_sub_brands=tray.get("tray_sub_brands"),
  2954. tray_count=len(ams_unit.get("tray", [])),
  2955. )
  2956. continue
  2957. # Slot matched (existing tag, untagged inventory
  2958. # match, or freshly auto-created spool) — drop any
  2959. # stale dedup so a future tag swap re-prompts.
  2960. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2961. await auto_assign_spool(
  2962. printer_id,
  2963. ams_id,
  2964. tray_id,
  2965. spool,
  2966. printer_manager,
  2967. db,
  2968. tray_info_idx=tray_info_idx,
  2969. )
  2970. await db.commit()
  2971. await ws_manager.broadcast(
  2972. {
  2973. "type": "spool_auto_assigned",
  2974. "printer_id": printer_id,
  2975. "ams_id": ams_id,
  2976. "tray_id": tray_id,
  2977. "spool_id": spool.id,
  2978. }
  2979. )
  2980. logger.info(
  2981. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2982. spool.id,
  2983. printer_id,
  2984. ams_id,
  2985. tray_id,
  2986. )
  2987. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  2988. db, tag_uid, tray_uuid
  2989. ):
  2990. # Non-BL spool with some tag — let user choose (not
  2991. # an archived one's, whose slot stays free)
  2992. await _broadcast_unknown_tag(
  2993. printer_id=printer_id,
  2994. ams_id=ams_id,
  2995. tray_id=tray_id,
  2996. tag_uid=tag_uid,
  2997. tray_uuid=tray_uuid,
  2998. tray_type=tray.get("tray_type"),
  2999. tray_color=tray.get("tray_color"),
  3000. tray_sub_brands=tray.get("tray_sub_brands"),
  3001. tray_count=len(ams_unit.get("tray", [])),
  3002. )
  3003. # No-tag slots (generic non-RFID filament) are left alone:
  3004. # nothing to identify, prompting "+ Add" would just create
  3005. # ghost spools with empty tags on every confirm.
  3006. except Exception as e:
  3007. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  3008. try:
  3009. async with async_session() as db:
  3010. from backend.app.api.routes.settings import get_setting
  3011. from backend.app.models.printer import Printer
  3012. # Check if Spoolman is enabled
  3013. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  3014. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  3015. return
  3016. # Check sync mode
  3017. sync_mode = await get_setting(db, "spoolman_sync_mode")
  3018. if sync_mode and sync_mode != "auto":
  3019. return # Only sync on auto mode
  3020. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  3021. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  3022. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  3023. # always owned by per-print tracking, never by AMS auto-sync. The
  3024. # setting is still read by the settings UI for backwards compat but
  3025. # has no effect on the sync path here.
  3026. # Get Spoolman URL
  3027. spoolman_url = await get_setting(db, "spoolman_url")
  3028. if not spoolman_url:
  3029. return
  3030. # Get or create Spoolman client
  3031. client = await get_spoolman_client()
  3032. if not client:
  3033. try:
  3034. client = await init_spoolman_client(spoolman_url)
  3035. except ValueError as exc:
  3036. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  3037. return
  3038. # Check if Spoolman is reachable
  3039. if not await client.health_check():
  3040. logger.warning("Spoolman not reachable at %s", spoolman_url)
  3041. return
  3042. # Get printer name for location
  3043. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3044. printer = result.scalar_one_or_none()
  3045. printer_name = printer.name if printer else f"Printer {printer_id}"
  3046. # OPTIMIZATION: Fetch all spools once before processing trays
  3047. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  3048. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  3049. try:
  3050. cached_spools = await client.get_spools()
  3051. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  3052. except Exception as e:
  3053. logger.error(
  3054. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  3055. printer_id,
  3056. e,
  3057. )
  3058. return
  3059. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  3060. from sqlalchemy.orm import selectinload
  3061. from backend.app.models.spool_assignment import SpoolAssignment
  3062. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  3063. from backend.app.services.ams_slot_presence import spool_present
  3064. from backend.app.services.inventory_mode import spoolman_owns_assignments
  3065. # Built-in remaining weight, used by sync_ams_tray only when the
  3066. # firmware reports an unusable remain%/tray_weight for a slot.
  3067. #
  3068. # Left empty since #2812. This block runs in Spoolman mode only,
  3069. # and until then the built-in table was emptied on the switch, so
  3070. # there was never anything here to read and the fallback was inert.
  3071. # Preserving those rows makes it live again, and it is keyed by slot
  3072. # rather than by spool: after a mode switch the tray may well hold
  3073. # different filament, and ``create_spool`` writes ``remaining_weight``
  3074. # unconditionally, so a stale figure would be seeded into a brand new
  3075. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  3076. # intent survives for whoever revisits the cross-mode fallback.
  3077. inventory_weights: dict[tuple[int, int], float] = {}
  3078. if not await spoolman_owns_assignments(db):
  3079. try:
  3080. assign_result = await db.execute(
  3081. select(SpoolAssignment)
  3082. .options(selectinload(SpoolAssignment.spool))
  3083. .where(SpoolAssignment.printer_id == printer_id)
  3084. )
  3085. for assignment in assign_result.scalars().all():
  3086. spool = assignment.spool
  3087. if spool and spool.label_weight > 0:
  3088. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  3089. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  3090. except Exception as e:
  3091. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  3092. # Load existing Spoolman slot assignments for the no-RFID fallback path
  3093. spoolman_slot_map: dict[tuple[int, int], int] = {}
  3094. slot_map_read = False
  3095. try:
  3096. slot_result = await db.execute(
  3097. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  3098. )
  3099. for slot in slot_result.scalars().all():
  3100. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  3101. slot_map_read = True
  3102. except Exception as e:
  3103. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  3104. # Sync each AMS tray and collect slot changes for DB persistence
  3105. synced = 0
  3106. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  3107. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  3108. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  3109. for ams_unit in ams_data:
  3110. if not isinstance(ams_unit, dict):
  3111. continue
  3112. ams_id = int(ams_unit.get("id", 0))
  3113. trays = ams_unit.get("tray", [])
  3114. for tray_data in trays:
  3115. if not isinstance(tray_data, dict):
  3116. continue
  3117. tray_id_raw = int(tray_data.get("id", 0))
  3118. tray = client.parse_ams_tray(ams_id, tray_data)
  3119. if not tray:
  3120. # Empty tray slot — record for local assignment cleanup
  3121. # and drop any cached unknown-tag broadcast so a
  3122. # reinserted spool re-prompts.
  3123. #
  3124. # Not during a running print: a slot that empties there
  3125. # is a filament runout, and the spool is still in the
  3126. # AMS. `spoolman_slot_assignments` is how a tag-less
  3127. # spool assigned through the Bambuddy UI is resolved at
  3128. # completion (#1459), so deleting the row mid-print
  3129. # loses the runout segment's usage — the same failure
  3130. # the internal inventory's auto-unlink had.
  3131. #
  3132. # Nor when firmware's presence bit says the slot is
  3133. # occupied. parse_ams_tray calls a tray with no type or
  3134. # no colour empty, and a spool the AMS cannot read has
  3135. # neither until something configures it — so a tag-less
  3136. # spool assigned through the UI had its row deleted by
  3137. # the first idle push after it was inserted. Same
  3138. # deletion as the internal inventory's in #3100, same
  3139. # answer, so the two modes stay in step.
  3140. #
  3141. # And only once the slot has stayed empty for the grace
  3142. # period -- the internal inventory's #3186 answer, for
  3143. # the same one-push blank.
  3144. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  3145. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  3146. if not printing_now and (
  3147. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  3148. ):
  3149. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  3150. empty_slots.append((ams_id, tray_id_raw))
  3151. else:
  3152. spoolman_held.add(hold_key)
  3153. logger.info(
  3154. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  3155. "unlinking if it is still empty in %ds",
  3156. ams_id,
  3157. tray_id_raw,
  3158. linked_spool,
  3159. int(slot_unlink_grace.GRACE_SECONDS),
  3160. )
  3161. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  3162. continue
  3163. spool_tag = (
  3164. tray.tray_uuid
  3165. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  3166. else tray.tag_uid
  3167. )
  3168. # Provide the hint only when no RFID is available
  3169. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  3170. try:
  3171. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  3172. result = await client.sync_ams_tray(
  3173. tray,
  3174. printer_name,
  3175. db,
  3176. # Per-print tracking is the only weight writer (#1119).
  3177. # AMS auto-sync still maintains spool metadata / slot
  3178. # assignments but no longer touches remaining_weight.
  3179. disable_weight_sync=True,
  3180. cached_spools=cached_spools,
  3181. inventory_remaining=inv_remaining,
  3182. spoolman_spool_id_hint=hint,
  3183. auto_add_unknown_rfid=auto_add_unknown_rfid,
  3184. )
  3185. if result is None and spool_tag and not auto_add_unknown_rfid:
  3186. # Spoolman skipped auto-create per user setting — surface
  3187. # the slot so the UI can offer "+ Add to inventory".
  3188. await _broadcast_unknown_tag(
  3189. printer_id=printer_id,
  3190. ams_id=ams_id,
  3191. tray_id=tray.tray_id,
  3192. tag_uid=tray.tag_uid or "",
  3193. tray_uuid=tray.tray_uuid or "",
  3194. tray_type=tray.tray_type,
  3195. tray_color=tray.tray_color,
  3196. tray_sub_brands=tray.tray_sub_brands,
  3197. tray_count=len(trays),
  3198. )
  3199. elif result:
  3200. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  3201. if result:
  3202. synced += 1
  3203. if result.get("id"):
  3204. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  3205. # If a new spool was created, add it to the cache
  3206. # so subsequent trays can find it if they reference the same tag
  3207. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  3208. if not spool_exists:
  3209. cached_spools.append(result)
  3210. logger.debug(
  3211. "[Printer %s] Added newly created spool %s to cache",
  3212. printer_id,
  3213. result["id"],
  3214. )
  3215. # Reconcile slot_preset_mappings (the same row internal
  3216. # mode keeps in sync via inventory + spool_tag_matcher).
  3217. # Without this the slot card surfaces the previous spool's
  3218. # preset name — same bug shape, different inventory mode.
  3219. from backend.app.services.slot_preset_writer import (
  3220. upsert_slot_preset_for_spoolman_spool,
  3221. )
  3222. await upsert_slot_preset_for_spoolman_spool(
  3223. db=db,
  3224. spoolman_spool=result,
  3225. tray_info_idx=tray.tray_info_idx or "",
  3226. tray_sub_brands=tray.tray_sub_brands or "",
  3227. tray_type=tray.tray_type or "",
  3228. printer_id=printer_id,
  3229. ams_id=ams_id,
  3230. tray_id=tray.tray_id,
  3231. )
  3232. except Exception as e:
  3233. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3234. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3235. if synced > 0:
  3236. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3237. # Persist slot assignment changes to the local table: only slots
  3238. # whose spool this pass changed, and only while they still hold what
  3239. # it read before awaiting Spoolman, so a spool assigned by hand in
  3240. # between stays (SSA-3). The changed slots are announced: the slot
  3241. # card reads slot_preset_mappings (rewritten above) ahead of the live
  3242. # tray, so with no event it kept the previous spool's preset name.
  3243. if slot_changes or empty_slots:
  3244. from backend.app.services.spoolman_slot_sync import write_slot_results
  3245. try:
  3246. await write_slot_results(
  3247. db,
  3248. {(printer_id, a_id, t_id): spool_id for (a_id, t_id), spool_id in spoolman_slot_map.items()}
  3249. if slot_map_read
  3250. else None,
  3251. [(printer_id, a_id, t_id, spool_id) for a_id, t_id, spool_id in slot_changes],
  3252. [(printer_id, a_id, t_id) for a_id, t_id in empty_slots],
  3253. )
  3254. except Exception as e:
  3255. await db.rollback()
  3256. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3257. except Exception as e:
  3258. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3259. # Largest finish photo attached to a notification; a bigger one is still linked.
  3260. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3261. async def _finish_photo_for_notification(
  3262. db, archive, archive_id: int, filename: str
  3263. ) -> tuple[str | None, bytes | None]:
  3264. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3265. With authentication off the link is the archive's own photo route, as it
  3266. always was: it opens without a login and doesn't expire. With
  3267. authentication on that route needs a media token, which nothing tapping a
  3268. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3269. link only ever answered 401. The photo is then saved as a notification
  3270. photo as well (utils/notification_photos.py) and the link points there: an
  3271. unguessable name that opens this one photo and nothing else, for 3 days.
  3272. The link is relative when no External URL is set. Bytes over
  3273. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3274. ``(None, None)`` when the photo can't be found.
  3275. """
  3276. from backend.app.api.routes.settings import get_setting
  3277. from backend.app.core.auth import is_auth_enabled
  3278. from backend.app.utils.archive_paths import find_archive_photo
  3279. from backend.app.utils.notification_photos import save_notification_photo
  3280. log = logging.getLogger(__name__)
  3281. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3282. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3283. photo_bytes: bytes | None = None
  3284. try:
  3285. photo_path = find_archive_photo(archive, filename)
  3286. if photo_path is not None:
  3287. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3288. except Exception as e:
  3289. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3290. try:
  3291. auth_on = await is_auth_enabled(db)
  3292. except Exception:
  3293. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3294. if auth_on:
  3295. url = None
  3296. if photo_bytes:
  3297. try:
  3298. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3299. url = f"{base}/api/v1/notifications/photos/{name}"
  3300. except Exception as e:
  3301. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3302. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3303. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3304. return url, None
  3305. if photo_bytes:
  3306. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3307. return url, photo_bytes
  3308. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3309. """Capture a camera snapshot for notification image attachment.
  3310. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3311. Uses: external camera > buffered frame > fresh capture.
  3312. Turns the chamber light on for the picture when the printer asks for it
  3313. (#1655). ``light=False`` is for callers that capture all through a print,
  3314. where the light would flash with every frame.
  3315. """
  3316. if not printer:
  3317. return None
  3318. async with camera_light(printer if light else None):
  3319. return await _capture_snapshot_frame(printer_id, printer, logger)
  3320. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3321. """The capture behind ``_capture_snapshot_for_notification``."""
  3322. try:
  3323. from backend.app.api.routes.settings import get_setting
  3324. async with async_session() as db:
  3325. capture_enabled = await get_setting(db, "capture_finish_photo")
  3326. if capture_enabled is not None and capture_enabled.lower() != "true":
  3327. return None
  3328. # Try external camera first
  3329. if printer.external_camera_enabled and printer.external_camera_url:
  3330. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3331. from backend.app.api.routes.camera import live_frame_for_capture
  3332. from backend.app.services.external_camera import capture_frame
  3333. # An external camera allows one reader, so capturing while a viewer
  3334. # is attached fails (#2707). A None here falls through to the paths
  3335. # below exactly as a failed capture did.
  3336. defer, buffered = live_frame_for_capture(printer_id)
  3337. if defer:
  3338. frame_data = buffered
  3339. else:
  3340. frame_data = await capture_frame(
  3341. printer.external_camera_url,
  3342. printer.external_camera_type or "mjpeg",
  3343. snapshot_url=printer.external_camera_snapshot_url,
  3344. )
  3345. if frame_data and len(frame_data) <= 2_500_000:
  3346. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3347. return _apply_camera_rotation(frame_data, printer, logger)
  3348. # Try buffered frame from active stream
  3349. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3350. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3351. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3352. buffered_frame = get_buffered_frame(printer_id)
  3353. if (active_for_printer or active_chamber) and buffered_frame:
  3354. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3355. if len(buffered_frame) <= 2_500_000:
  3356. return _apply_camera_rotation(buffered_frame, printer, logger)
  3357. # Fresh capture from printer camera
  3358. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3359. from backend.app.services.camera import capture_camera_frame_bytes
  3360. frame_data = await capture_camera_frame_bytes(
  3361. printer.ip_address, printer.access_code, printer.model, timeout=15
  3362. )
  3363. if frame_data and len(frame_data) <= 2_500_000:
  3364. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3365. return _apply_camera_rotation(frame_data, printer, logger)
  3366. except Exception as e:
  3367. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3368. return None
  3369. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3370. """#1867: bank a recent in-print camera frame for the finish photo.
  3371. Called on every layer change and (#2547) on every print-progress advance.
  3372. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3373. path has a pre-End-G-code image for prints that end with a plate swap.
  3374. Both drivers are print telemetry that stops the instant printing ends: no
  3375. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3376. plate swap) executes. So the last banked frame is always the finished print,
  3377. never the swapped plate — that property is what the #1867 path relies on and
  3378. it must survive any change to the throttle below.
  3379. Layer changes alone were not enough: they stop when the *final* layer
  3380. begins, which on a three-minute last layer left the bank stale by the whole
  3381. length of that layer (#2547). Progress keeps ticking through it.
  3382. Best-effort: any failure just leaves the previous banked frame.
  3383. """
  3384. logger = logging.getLogger(__name__)
  3385. client = printer_manager.get_client(printer_id)
  3386. state = client.state if client else None
  3387. if not state or state.state != "RUNNING":
  3388. return
  3389. # Only during actual extrusion — firmware ticks layer_num during the
  3390. # pre-print calibration sequence, whose sub-stages are non-zero.
  3391. if state.mc_print_sub_stage not in (None, 0):
  3392. return
  3393. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3394. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3395. # now that progress advances also drive banking, that exemption would fire a
  3396. # camera grab on every percent tick of the last layer. Bambu printers accept
  3397. # one RTSP client at a time, so each grab contends with the live view.
  3398. now = time.monotonic()
  3399. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3400. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3401. return
  3402. total = state.total_layers or 0
  3403. try:
  3404. async with async_session() as db:
  3405. from backend.app.models.printer import Printer
  3406. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3407. printer = result.scalar_one_or_none()
  3408. if not printer:
  3409. return
  3410. # Reuses the notification snapshot path, which honours the
  3411. # `capture_finish_photo` setting (returns None when disabled) so we
  3412. # don't bank frames the user never asked for. Without the chamber light
  3413. # (#1655): this runs every 25 seconds for the whole print.
  3414. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3415. if frame:
  3416. _inprint_frame_bank[printer_id] = frame
  3417. _inprint_frame_bank_ts[printer_id] = now
  3418. logger.debug(
  3419. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3420. printer_id,
  3421. layer_num,
  3422. total,
  3423. len(frame),
  3424. )
  3425. except Exception as e:
  3426. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3427. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3428. """Apply camera rotation to snapshot image if configured."""
  3429. from backend.app.services.camera import apply_camera_rotation
  3430. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3431. async def _send_print_start_notification(
  3432. printer_id: int,
  3433. data: dict,
  3434. archive_data: dict | None = None,
  3435. logger=None,
  3436. ):
  3437. """Helper to send print start notification with optional archive data."""
  3438. if logger is None:
  3439. logger = logging.getLogger(__name__)
  3440. try:
  3441. async with async_session() as db:
  3442. from backend.app.models.printer import Printer
  3443. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3444. printer = result.scalar_one_or_none()
  3445. printer_name = printer.name if printer else f"Printer {printer_id}"
  3446. # Capture camera snapshot for notification image attachment
  3447. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3448. if image_data:
  3449. if archive_data is None:
  3450. archive_data = {}
  3451. archive_data["image_data"] = image_data
  3452. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3453. # Send user-specific email notification for print start
  3454. if archive_data and archive_data.get("created_by_id"):
  3455. await notification_service.send_user_print_email(
  3456. event_type="user_print_start",
  3457. created_by_id=archive_data["created_by_id"],
  3458. printer_name=printer_name,
  3459. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3460. db=db,
  3461. )
  3462. except Exception as e:
  3463. logger.warning("Notification on_print_start failed: %s", e)
  3464. async def _dispatch_user_print_email(
  3465. status: str,
  3466. created_by_id: int | None,
  3467. printer_name: str,
  3468. filename: str,
  3469. db,
  3470. image_data: bytes | None = None,
  3471. finish_photo_url: str | None = None,
  3472. ) -> None:
  3473. """Send a user-specific print-completion email based on print status.
  3474. Maps the normalised print status to the correct event type and delegates
  3475. to :meth:`NotificationService.send_user_print_email`. A single helper
  3476. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3477. "stopped"`` dispatch block at every call site.
  3478. Does nothing if *created_by_id* is ``None``.
  3479. """
  3480. if created_by_id is None:
  3481. return
  3482. if status == "completed":
  3483. event_type = "user_print_complete"
  3484. elif status == "failed":
  3485. event_type = "user_print_failed"
  3486. elif status in ("stopped", "aborted", "cancelled"):
  3487. event_type = "user_print_stopped"
  3488. else:
  3489. return
  3490. await notification_service.send_user_print_email(
  3491. event_type=event_type,
  3492. created_by_id=created_by_id,
  3493. printer_name=printer_name,
  3494. filename=filename,
  3495. db=db,
  3496. image_data=image_data,
  3497. finish_photo_url=finish_photo_url,
  3498. )
  3499. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3500. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3501. try:
  3502. from backend.app.services.archive import extract_printable_objects_from_archive
  3503. client = printer_manager.get_client(printer_id)
  3504. if not client:
  3505. return
  3506. # Extract with positions for UI overlay, scoped to the plate that
  3507. # is printing — resolve_plate_id is the same resolver /cover uses,
  3508. # so the object list can't disagree with the thumbnail it is drawn
  3509. # over (#2522).
  3510. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3511. app_settings.base_dir / archive.file_path,
  3512. plate_number=resolve_plate_id(client.state),
  3513. )
  3514. if printable_objects:
  3515. client.state.printable_objects = printable_objects
  3516. client.state.printable_objects_bbox_all = bbox_all
  3517. client.state.skipped_objects = []
  3518. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3519. except Exception as e:
  3520. logger.debug("Failed to extract printable objects from archive: %s", e)
  3521. def _load_pauses_from_3mf(threemf_path, printer_id: int, *, warned_layers=(), passed_through_layer: int = 0) -> None:
  3522. """Read the running print's slicer pauses from its 3MF, in the background (#2984).
  3523. In a thread: a plate's G-code runs to tens of MB, and the print-start
  3524. handler must not wait for it. Kept only while the printer is still on
  3525. the print they were read for: a new print replaces the list.
  3526. ``warned_layers``: pauses this print was already warned about, kept on its
  3527. archive, so a restart does not send the heads-up again.
  3528. ``passed_through_layer``: for a print resumed after a restart, the layer it
  3529. is on. Its pauses up to there are behind it, though the printer's layer
  3530. reads 0 until it reports the next one.
  3531. """
  3532. client = printer_manager.get_client(printer_id)
  3533. if not client:
  3534. return
  3535. state = client.state
  3536. read_for = state.pause_points
  3537. try:
  3538. plate_id = resolve_plate_id(state)
  3539. except Exception:
  3540. # Never at the cost of the print-start handler this runs inside.
  3541. logging.getLogger(__name__).warning("[Printer %s] Could not tell the plate to read pauses for", printer_id)
  3542. return
  3543. async def _load() -> None:
  3544. from backend.app.utils.threemf_tools import extract_pause_points_from_3mf
  3545. points = await asyncio.to_thread(extract_pause_points_from_3mf, Path(threemf_path), plate_id)
  3546. if state.pause_points is not read_for:
  3547. return
  3548. state.pause_points = [p for p in points if p.layer > passed_through_layer]
  3549. state.pause_warned_layers = set(state.pause_warned_layers) | set(warned_layers)
  3550. if points:
  3551. logging.getLogger(__name__).info(
  3552. "Loaded %s slicer pause(s) for printer %s at layer(s) %s",
  3553. len(points),
  3554. printer_id,
  3555. [p.layer for p in points],
  3556. )
  3557. spawn_background_task(_load(), name=f"load-pauses-{printer_id}")
  3558. def _load_pauses_from_resumed_archive(archive, printer_id: int) -> None:
  3559. """Pauses for a print start taken as the resumption of a running print.
  3560. A restart while the print was paused makes its resume look like a new
  3561. print (#2984): the pauses warned about and passed are kept from before.
  3562. """
  3563. client = printer_manager.get_client(printer_id)
  3564. state = client.state if client else None
  3565. _load_pauses_from_3mf(
  3566. app_settings.base_dir / archive.file_path,
  3567. printer_id,
  3568. warned_layers=pause_eta.warned_layers_of(archive, state) if state is not None else (),
  3569. passed_through_layer=getattr(client, "layer_before_new_print", 0) if client else 0,
  3570. )
  3571. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3572. """Put the skip-objects list back after a restart mid-print.
  3573. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3574. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3575. which the #1304 guard suppresses on the first RUNNING push after startup.
  3576. Everything else this hook restores (the archive, the usage-tracking session,
  3577. the timelapse baseline) was already handled; the object list was not, so a
  3578. restart mid-print took skip-objects away for the rest of that print.
  3579. Nothing recovered it either: the printer card gates its Skip button on the
  3580. object count, and the one endpoint that can rebuild the list is reachable
  3581. only from the modal that button opens.
  3582. The archive is the running print's as ``running_print_archive`` finds it:
  3583. by subtask_id, or for a print that reports none by the archive bound to it
  3584. (#3327), never by name: a leftover ``status="printing"`` row from a
  3585. completion we never saw must not hand this print someone else's objects.
  3586. After a restart that binding exists only for Bambuddy's own prints, so a
  3587. print that reports no subtask_id loads nothing rather than a guess; the
  3588. reload path on ``GET /print/objects`` covers that case on demand.
  3589. """
  3590. client = printer_manager.get_client(printer_id)
  3591. if client is None or (client.state.printable_objects and client.state.pause_points):
  3592. return
  3593. archive = await running_print_archive(db, printer_id, state, printing_only=True, by_name=False)
  3594. if archive is not None and archive.file_path:
  3595. if not client.state.printable_objects:
  3596. _load_objects_from_archive(archive, printer_id, logger)
  3597. # The slicer's pauses are in-memory only as well (#2984).
  3598. if not client.state.pause_points:
  3599. _load_pauses_from_3mf(
  3600. app_settings.base_dir / archive.file_path,
  3601. printer_id,
  3602. warned_layers=pause_eta.warned_layers_of(archive, state),
  3603. )
  3604. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3605. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3606. # past it; the second covers a handshake that failed again on the way back and
  3607. # armed a fresh one. Module-level so tests can shrink them.
  3608. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3609. # Retry ladder for the other temporary give-up: the file service answered and
  3610. # the transfer still did not finish, which at print start is usually the printer
  3611. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3612. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3613. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3614. # two cover a printer that stays busy well into the print.
  3615. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3616. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3617. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3618. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3619. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3620. # by view, so two views race), the cool-off retry task, and print completion.
  3621. # Without this they each read file_path == "" and each run a full copy, so the row
  3622. # ends up pointing at one timestamped directory while the others sit orphaned.
  3623. #
  3624. # Keyed by printer rather than archive because a printer runs one print at a time,
  3625. # which makes the two equally strong here — and it bounds the dict by printer
  3626. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3627. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3628. # resuming, so "no waiters" is not a question this API can answer.
  3629. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3630. # How many of a printer's newest archives a touchscreen reprint is compared
  3631. # against (#3307). A repeat is usually of a recent job; the bound keeps a
  3632. # print start from reading a long history's extra_data.
  3633. _REPEAT_LOOKBACK = 200
  3634. async def _archived_3mf_for_repeat(
  3635. db, printer_id: int, subtask_name: str | None, gcode_file: str | None, total_layers: int | None
  3636. ):
  3637. """The newest archive of the job this printer is running again, with its 3MF.
  3638. A "Print again" on the printer's screen never names the file on the card:
  3639. it reports its own history copy under a generic name
  3640. (``file:///userdata/project_file.gcode.3mf``), the 3MF's internal title as
  3641. ``subtask_name`` and the plate as ``gcode_file`` -- and the title is often
  3642. not the card file's name, so every lookup built from it misses (#3307).
  3643. An earlier run that was archived recorded that same title and plate in its
  3644. ``_print_data``, and holds the 3MF.
  3645. Same printer, same title, same plate, a 3MF still on disk. A layer count
  3646. known on both sides must agree: the same title and plate re-sliced is
  3647. another job. None when nothing matches.
  3648. """
  3649. from backend.app.models.archive import PrintArchive
  3650. if not subtask_name or not gcode_file:
  3651. return None
  3652. rows = (
  3653. (
  3654. await db.execute(
  3655. select(PrintArchive)
  3656. .where(
  3657. PrintArchive.printer_id == printer_id,
  3658. PrintArchive.deleted_at.is_(None),
  3659. PrintArchive.file_path.isnot(None),
  3660. PrintArchive.file_path != "",
  3661. )
  3662. .order_by(PrintArchive.created_at.desc(), PrintArchive.id.desc())
  3663. .limit(_REPEAT_LOOKBACK)
  3664. )
  3665. )
  3666. .scalars()
  3667. .all()
  3668. )
  3669. for archive in rows:
  3670. extra = archive.extra_data if isinstance(archive.extra_data, dict) else {}
  3671. run = extra.get("_print_data")
  3672. if not isinstance(run, dict):
  3673. continue
  3674. if run.get("subtask_name") != subtask_name or run.get("filename") != gcode_file:
  3675. continue
  3676. if total_layers and archive.total_layers and archive.total_layers != total_layers:
  3677. continue
  3678. if not (app_settings.base_dir / archive.file_path).is_file():
  3679. continue
  3680. return archive
  3681. return None
  3682. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True) -> bool:
  3683. """Fill in a no-3MF archive from a 3MF that turned up later.
  3684. Returns True when the row was upgraded. Safe to call speculatively: it
  3685. verifies the archive still exists, is still a fallback, and that the file
  3686. is a readable 3MF before touching anything.
  3687. Serialised per printer — see ``_fallback_recovery_locks``.
  3688. """
  3689. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3690. async with lock:
  3691. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id, price=price)
  3692. async def _recover_fallback_archive_locked(
  3693. archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True
  3694. ) -> bool:
  3695. """The body of :func:`_recover_fallback_archive`, under its per-printer lock.
  3696. ``price`` is False when the print's end is being handled: the archive
  3697. still reads "printing" then, and its end prices it.
  3698. """
  3699. import zipfile
  3700. from backend.app.models.archive import PrintArchive
  3701. from backend.app.services.archive import ArchiveService
  3702. logger = logging.getLogger(__name__)
  3703. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3704. return False
  3705. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3706. # A truncated or half-written download is worse than no download: it
  3707. # would replace an honest empty archive with wrong metadata.
  3708. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3709. return False
  3710. async with async_session() as db:
  3711. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3712. if archive is None or archive.deleted_at is not None:
  3713. return False
  3714. if archive.file_path:
  3715. # Already recovered, or never was a fallback. Either way there is a
  3716. # real 3MF attached and overwriting it is not this function's job.
  3717. return False
  3718. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3719. service = ArchiveService(db)
  3720. recovered = await service.archive_print(
  3721. printer_id=printer_id,
  3722. source_file=source_3mf,
  3723. print_data={**print_data, "status": archive.status or "printing"},
  3724. subtask_id=archive.subtask_id,
  3725. update_archive_id=archive.id,
  3726. )
  3727. if recovered is None:
  3728. return False
  3729. logger.info(
  3730. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3731. archive_id,
  3732. source_3mf,
  3733. recovered.file_size,
  3734. )
  3735. # Spoolman's tracking stored no 3MF usage at print start and would
  3736. # charge the AMS remain% change; the built-in tracker reads the archive
  3737. # at completion and needs nothing. Also at the print's end (``price``
  3738. # False): that recovery runs inside the close-out, before the charge.
  3739. try:
  3740. from backend.app.services.spoolman_tracking import attach_recovered_3mf
  3741. from backend.app.services.usage_tracker import is_completing
  3742. await attach_recovered_3mf(
  3743. printer_id,
  3744. recovered.id,
  3745. recovered.file_path,
  3746. db,
  3747. printer_manager,
  3748. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3749. may_start=not price or (recovered.status == "printing" and not is_completing(printer_id)),
  3750. )
  3751. except Exception:
  3752. logger.warning(
  3753. "[RECOVER] Archive %s: could not add the 3MF to Spoolman's usage tracking", archive_id, exc_info=True
  3754. )
  3755. if price and recovered.status == "printing" and recovered.file_path:
  3756. # Print start had no 3MF to read the slicer's pauses from (#2984).
  3757. _load_pauses_from_3mf(app_settings.base_dir / recovered.file_path, printer_id)
  3758. if price and recovered.status == "printing":
  3759. # Print start priced it from the default rate, having no 3MF to
  3760. # estimate from; now it has one. An ended print is left alone: its
  3761. # end prices it. A print Bambuddy didn't dispatch has no start
  3762. # plate; the one the archive just read from the 3MF stands in.
  3763. _schedule_archive_cost_estimate(
  3764. printer_id,
  3765. recovered.id,
  3766. printer_manager,
  3767. ams_mapping=_get_start_ams_mapping(print_data, printer_id, recovered.id),
  3768. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3769. session_factory=async_session,
  3770. )
  3771. # `archive_updated`, not `archive_created` — the row was already on the
  3772. # Archives page as an empty card and is now filled in, not new.
  3773. await ws_manager.send_archive_updated(
  3774. {
  3775. "id": recovered.id,
  3776. "printer_id": recovered.printer_id,
  3777. "filename": recovered.filename,
  3778. "print_name": recovered.print_name,
  3779. "status": recovered.status,
  3780. }
  3781. )
  3782. return True
  3783. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path, *, price: bool = True) -> bool:
  3784. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3785. Called from the paths that pull a 3MF for a print that is already under way
  3786. — chiefly the cover endpoint, which downloads the very file the archive flow
  3787. could not get and, before #2957, used it for a thumbnail and nothing else.
  3788. The bytes are already local, so this costs a parse and a row update.
  3789. No-op when the running print has a real archive, which is the common case.
  3790. """
  3791. from backend.app.models.archive import PrintArchive
  3792. logger = logging.getLogger(__name__)
  3793. # `_active_prints` is keyed on the raw names seen at print start — the
  3794. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3795. # Callers here arrive with whichever variant their own path produced, so
  3796. # match on the same normalization the download cache uses rather than on an
  3797. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3798. # endpoint find an archive registered under "Desktop_Goose".
  3799. wanted = normalize_3mf_name(name)
  3800. archive_id = None
  3801. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3802. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3803. archive_id = value
  3804. break
  3805. if archive_id is None:
  3806. return False
  3807. async with async_session() as db:
  3808. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3809. # Cheap pre-check so the common case (a normal archive) does no work.
  3810. if archive is None or archive.file_path or archive.deleted_at is not None:
  3811. return False
  3812. try:
  3813. return await _recover_fallback_archive(archive_id, path, printer_id, price=price)
  3814. except Exception as e:
  3815. # Recovery is opportunistic. A failure here must never take down the
  3816. # caller, which is usually just trying to render a thumbnail.
  3817. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3818. return False
  3819. def _schedule_fallback_3mf_retry(
  3820. printer_id: int,
  3821. archive_id: int,
  3822. filenames: list[str],
  3823. delays: tuple[float, ...] | None = None,
  3824. reason: str = REASON_FTPS_COOLOFF,
  3825. ) -> None:
  3826. """Re-attempt the 3MF download after a temporary give-up.
  3827. ``reason`` says which give-up this is, and picks the default ladder: an
  3828. FTPS cool-off has to be waited out, while a transfer that timed out under
  3829. contention is worth asking about again straight away (#3063). It is only
  3830. read for the ladder and the log line -- the retry itself is identical, since
  3831. in both cases the file is on the printer and the last attempt at it failed
  3832. for a reason that does not last.
  3833. """
  3834. logger = logging.getLogger(__name__)
  3835. if delays is None:
  3836. delays = (
  3837. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3838. if reason == REASON_FTP_TRANSFER_FAILED
  3839. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3840. )
  3841. async def _retry() -> None:
  3842. from backend.app.models.archive import PrintArchive
  3843. from backend.app.models.printer import Printer
  3844. for delay in delays:
  3845. await asyncio.sleep(delay)
  3846. async with async_session() as db:
  3847. archive = (
  3848. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3849. ).scalar_one_or_none()
  3850. if archive is None or archive.deleted_at is not None or archive.file_path:
  3851. return
  3852. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3853. if printer is None:
  3854. return
  3855. # Read the fields while the session is open rather than touching
  3856. # a detached instance minutes later, mid-download.
  3857. printer_ip = printer.ip_address
  3858. printer_code = printer.access_code
  3859. printer_model = printer.model
  3860. # Someone else may have fetched it in the meantime — the cover
  3861. # endpoint routinely does, and its copy is the same bytes.
  3862. for name in filenames:
  3863. cached = get_cached_3mf(printer_id, name)
  3864. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3865. return
  3866. if ftps_handshake_blocked(printer_ip):
  3867. logger.info(
  3868. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3869. printer_id,
  3870. archive_id,
  3871. )
  3872. continue
  3873. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3874. for candidate in filenames:
  3875. # Bare name only. These come from the print-start flow, which
  3876. # already strips the path, but the local temp write must not
  3877. # depend on that holding for every future caller — a name that
  3878. # is absolute or contains ".." would otherwise escape the data
  3879. # volume via the `/` operator.
  3880. name = Path(candidate).name
  3881. if not name or name in (".", ".."):
  3882. continue
  3883. if not name.endswith(".3mf"):
  3884. name = f"{name}.3mf"
  3885. temp_path = app_settings.archive_dir / "temp" / name
  3886. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3887. try:
  3888. hit = await download_file_try_paths_async(
  3889. printer_ip,
  3890. printer_code,
  3891. ftp_probe_paths(name),
  3892. temp_path,
  3893. socket_timeout=ftp_timeout,
  3894. printer_model=printer_model,
  3895. max_total_timeout=RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  3896. )
  3897. except Exception as e:
  3898. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3899. continue
  3900. if not hit:
  3901. continue
  3902. cache_3mf_download(printer_id, name, temp_path)
  3903. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3904. return
  3905. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3906. async def _guarded() -> None:
  3907. try:
  3908. await _retry()
  3909. except asyncio.CancelledError:
  3910. raise
  3911. except Exception as e:
  3912. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3913. finally:
  3914. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3915. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3916. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3917. if existing and not existing.done():
  3918. existing.cancel()
  3919. task = asyncio.create_task(_guarded())
  3920. _fallback_3mf_retry_tasks[printer_id] = task
  3921. logger.info(
  3922. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3923. archive_id,
  3924. reason,
  3925. printer_id,
  3926. ", ".join(f"{d:g}s" for d in delays),
  3927. )
  3928. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3929. """Whether an archive created here should ask for the print's outcome (#1898).
  3930. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3931. branches below: a queued job already has its archive and takes the
  3932. expected-print branch, where the queue item's own ``confirm_outcome``
  3933. decides. The queue is still consulted, because a restart mid-print empties
  3934. ``_expected_prints`` — without the check the setting could override a queue
  3935. item that deliberately has the flag off. Any failure answers "don't ask":
  3936. an unwanted prompt is worse than a missing one, and this must never be the
  3937. reason a print goes unarchived.
  3938. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3939. leaves one behind when a completion cannot be matched to it
  3940. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3941. only takes it back once the printer has sat connected and terminal for
  3942. minutes. Until then every screen-started print on that printer would
  3943. silently lose its prompt, so the row is held against ``observed_name`` by
  3944. the same comparison a completion uses: a positive disagreement means the row
  3945. is about some other run and this print is external after all.
  3946. """
  3947. logger = logging.getLogger(__name__)
  3948. try:
  3949. # A savepoint rather than a rollback of the caller's transaction on
  3950. # failure: a failed statement leaves the transaction unusable, but a
  3951. # full rollback also expires every object the caller has loaded (the
  3952. # printer, the archive it just created), and on an async session the
  3953. # next attribute read then raises instead of reloading. Everything here
  3954. # is a read, so undoing the savepoint loses nothing.
  3955. async with db.begin_nested():
  3956. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3957. except Exception as e:
  3958. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3959. return False
  3960. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3961. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3962. from backend.app.api.routes.settings import get_setting, setting_is_true
  3963. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3964. return False
  3965. from backend.app.models.print_queue import PrintQueueItem
  3966. dispatched_here = await db.scalar(
  3967. select(PrintQueueItem)
  3968. .where(
  3969. PrintQueueItem.printer_id == printer_id,
  3970. PrintQueueItem.status == "printing",
  3971. )
  3972. .limit(1)
  3973. )
  3974. if dispatched_here is None:
  3975. return True
  3976. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3977. observed = (observed_name or "").strip()
  3978. if not expected or not observed or _subtask_names_match(expected, observed):
  3979. logger.info(
  3980. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3981. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3982. printer_id,
  3983. dispatched_here.id,
  3984. )
  3985. return False
  3986. logger.info(
  3987. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3988. "%r; treating this as an externally started print.",
  3989. dispatched_here.id,
  3990. printer_id,
  3991. expected,
  3992. observed,
  3993. )
  3994. return True
  3995. async def _dispatch_outcome_confirmation_safely(
  3996. db,
  3997. printer_id: int,
  3998. printer_name: str,
  3999. data: dict,
  4000. archive_id: int,
  4001. archive_data: dict | None = None,
  4002. run_id: int | None = None,
  4003. ) -> None:
  4004. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  4005. The completion task sends the per-user print email on the same session
  4006. right after the prompt. A failed statement in the prompt leaves that
  4007. session needing a rollback, and without one the email step fails with
  4008. PendingRollbackError; the prompt is the optional part, so it must not be
  4009. the reason the email never goes out.
  4010. """
  4011. try:
  4012. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data, run_id=run_id)
  4013. except Exception as e:
  4014. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  4015. try:
  4016. await db.rollback()
  4017. except Exception:
  4018. pass
  4019. async def _outcome_answerers(db, owner_id: int | None) -> set[int] | None:
  4020. """Who may answer a print's outcome prompt in the app: its owner and anyone
  4021. who may change everyone's archives. None (everyone on the printer) with auth
  4022. off, or for a print nobody owns."""
  4023. from sqlalchemy.orm import selectinload
  4024. from backend.app.core.auth import is_auth_enabled
  4025. from backend.app.core.permissions import Permission
  4026. from backend.app.models.user import User
  4027. if owner_id is None or not await is_auth_enabled(db):
  4028. return None
  4029. users = (await db.execute(select(User).options(selectinload(User.groups)).where(User.is_active))).scalars().all()
  4030. return {owner_id} | {u.id for u in users if u.has_permission(Permission.ARCHIVES_UPDATE_ALL.value)}
  4031. async def dispatch_outcome_confirmation(
  4032. db,
  4033. printer_id: int,
  4034. printer_name: str,
  4035. data: dict,
  4036. archive_id: int,
  4037. archive_data: dict | None = None,
  4038. *,
  4039. run_id: int | None = None,
  4040. ) -> bool:
  4041. """Emit the post-print outcome prompt for a completed print (#1898).
  4042. Gated on the run that ended (``run_id``): ``confirm_requested`` is the
  4043. opt-in (from the queue item, or from ``confirm_outcome_external_prints``
  4044. for a print Bambuddy did not start, copied onto the run at its start) and
  4045. ``user_verdict`` being unset is what makes the question still open. Mints
  4046. the run's capability token the one-tap verdict links carry: plates of one
  4047. archive each have their own question. Without a run, the archive's, as
  4048. before runs.
  4049. Lives here rather than inline in ``on_print_complete``'s notification task
  4050. because that task swallows every exception: extracted, the gate and the two
  4051. emissions can be driven by a test, which is the only thing standing between
  4052. a regression here and a farm that quietly stops asking.
  4053. Returns whether a prompt was sent.
  4054. """
  4055. logger = logging.getLogger(__name__)
  4056. from backend.app.models.archive import PrintArchive
  4057. from backend.app.models.print_log import PrintLogEntry
  4058. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  4059. if confirm_archive is None:
  4060. return False
  4061. run = await db.get(PrintLogEntry, run_id) if run_id is not None else None
  4062. if run is not None and run.archive_id != archive_id:
  4063. run = None
  4064. # The run carries the opt-in from its start; one logged before it did
  4065. # (None) asks as its archive does.
  4066. asks = confirm_archive if run is None or run.confirm_requested is None else run
  4067. holder = run if run is not None else confirm_archive
  4068. if not (asks.confirm_requested and holder.user_verdict is None):
  4069. return False
  4070. import secrets as _secrets
  4071. # A spent token stays on the row so the one-tap route can recognise it, so
  4072. # "has a token" no longer means "answerable". A prompt going out now needs a
  4073. # live one: mint a new token whenever the stored one is already spent, or
  4074. # every button in the new message would land on the already-answered page.
  4075. if not holder.confirm_token or holder.confirm_token_used_at is not None:
  4076. holder.confirm_token = _secrets.token_urlsafe(32)
  4077. holder.confirm_token_used_at = None
  4078. await db.commit()
  4079. from backend.app.api.routes.settings import get_external_base_url, get_setting
  4080. base = await get_external_base_url(db)
  4081. if not await get_setting(db, "external_url"):
  4082. # Both the Telegram inline keyboard and the ntfy action buttons need an
  4083. # absolute URL, so an unconfigured install used to get a message body
  4084. # with two unusable relative paths and no buttons at all. The shared
  4085. # fallback at least produces tappable links; say which setting makes
  4086. # them resolve from a phone.
  4087. logger.warning(
  4088. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  4089. "Set Settings → External URL so they resolve away from this host.",
  4090. base,
  4091. )
  4092. token = holder.confirm_token
  4093. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  4094. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  4095. confirm_url = f"{base}/archives?confirm={archive_id}" + (f"&run={run.id}" if run is not None else "")
  4096. await ws_manager.send_print_confirm_request(
  4097. printer_id,
  4098. {
  4099. "archive_id": archive_id,
  4100. "run_id": run.id if run is not None else None,
  4101. "print_name": confirm_archive.print_name or confirm_archive.filename,
  4102. },
  4103. user_ids=await _outcome_answerers(db, confirm_archive.created_by_id),
  4104. )
  4105. await notification_service.on_print_confirm_request(
  4106. printer_id,
  4107. printer_name,
  4108. data,
  4109. db,
  4110. archive_data=archive_data,
  4111. good_url=good_url,
  4112. reject_url=reject_url,
  4113. confirm_url=confirm_url,
  4114. archive_id=archive_id,
  4115. run_id=run.id if run is not None else None,
  4116. )
  4117. return True
  4118. async def _printer_gone(db, printer_id: int) -> bool:
  4119. """Whether the printer was deleted. A column read: the session's loaded
  4120. Printer would otherwise answer for the database."""
  4121. from backend.app.models.printer import Printer
  4122. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  4123. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  4124. """Remove the archive just written if its printer was deleted meanwhile.
  4125. The delete route sweeps the printer's archives before it commits, so a row
  4126. committed after that sweep (the check before writing passed while the
  4127. delete was still uncommitted) is left for a printer that will never report
  4128. the print's end. A row the sweep reached is the route's: deleted with the
  4129. printer's archives, or detached (printer_id NULL) when the user kept them,
  4130. and then left as it is. Either way nothing is registered for it. Run after
  4131. the archive's commit, before anything is registered for it.
  4132. """
  4133. from backend.app.models.archive import PrintArchive
  4134. if not await _printer_gone(db, printer_id):
  4135. return False
  4136. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  4137. if owner == printer_id:
  4138. logging.getLogger(__name__).info(
  4139. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  4140. )
  4141. await ArchiveService(db).delete_archive(archive_id)
  4142. await forget_printer(printer_id)
  4143. return True
  4144. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  4145. """After an IntegrityError on a print start's archive write: whether it was
  4146. the printer being deleted, forgotten then (the caller returns).
  4147. PostgreSQL: the delete route locks the printer from its archive sweep to its
  4148. commit, so an archive written or adopted for it meanwhile (one that sets
  4149. printer_id) waits and the printer's foreign key then refuses it. That is
  4150. the printer being deleted, not an error; anything else is re-raised by the
  4151. caller.
  4152. """
  4153. await db.rollback()
  4154. if not await _printer_gone(db, printer_id):
  4155. return False
  4156. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  4157. await forget_printer(printer_id)
  4158. return True
  4159. async def _forget_if_printer_gone(printer_id: int) -> None:
  4160. """At the end of a print start: the slow steps after the last check (smart
  4161. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  4162. printer's delete and its forget_printer, and then wrote state back.
  4163. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  4164. SQLite; PostgreSQL refuses it.)
  4165. Its own session: those steps can leave the handler's needing a rollback (a
  4166. write to the archive the delete removed). Never raises: it runs inside the
  4167. fallback branch's try, whose except reports the archive as failed.
  4168. """
  4169. try:
  4170. async with async_session() as db:
  4171. gone = await _printer_gone(db, printer_id)
  4172. if gone:
  4173. await forget_printer(printer_id)
  4174. except Exception:
  4175. logging.getLogger(__name__).warning(
  4176. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  4177. )
  4178. async def _announce_plate_check_failed(printer_id: int, printer_name: str, reason: str) -> None:
  4179. """Tell the UI a plate check could not run. It does not block the print,
  4180. but an unchecked plate is not an empty one."""
  4181. try:
  4182. await ws_manager.broadcast(
  4183. {"type": "plate_check_failed", "printer_id": printer_id, "printer_name": printer_name, "reason": reason}
  4184. )
  4185. except Exception as e:
  4186. logging.getLogger(__name__).warning("[PLATE CHECK] Could not announce the failed check: %s", e)
  4187. def _expected_print_keys(printer_id: int, filename: str | None, subtask_name: str | None) -> list[tuple[int, str]]:
  4188. """The ``_expected_prints`` keys a print start may be registered under."""
  4189. keys: list[tuple[int, str]] = []
  4190. if subtask_name:
  4191. keys.append((printer_id, subtask_name))
  4192. keys.append((printer_id, f"{subtask_name}.3mf"))
  4193. keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  4194. if filename:
  4195. fname = filename.split("/")[-1] if "/" in filename else filename
  4196. keys.append((printer_id, fname))
  4197. # Strip extensions to match
  4198. base = fname.replace(".gcode", "").replace(".3mf", "")
  4199. keys.append((printer_id, base))
  4200. keys.append((printer_id, f"{base}.3mf"))
  4201. return keys
  4202. async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, subtask_name: str | None) -> bool:
  4203. """Whether this print start is one Bambuddy sent to the printer."""
  4204. if any(key in _expected_prints for key in _expected_print_keys(printer_id, filename, subtask_name)):
  4205. return True
  4206. from backend.app.models.archive import PrintArchive
  4207. from backend.app.models.print_queue import PrintQueueItem
  4208. # The queue row the scheduler sets to printing before it sends -- but only
  4209. # when it was sent as this print: a row left printing by a run whose end
  4210. # was missed names another file.
  4211. dispatched_names = (
  4212. await db.execute(
  4213. select(PrintArchive.filename)
  4214. .join(PrintQueueItem, PrintQueueItem.archive_id == PrintArchive.id)
  4215. .where(PrintQueueItem.printer_id == printer_id, PrintQueueItem.status == "printing")
  4216. )
  4217. ).scalars()
  4218. observed = [name for name in (subtask_name, (filename or "").rsplit("/", 1)[-1]) if name]
  4219. return any(
  4220. _subtask_names_match(_subtask_name_from_filename(dispatched), _subtask_name_from_filename(seen))
  4221. for dispatched in dispatched_names
  4222. if dispatched
  4223. for seen in observed
  4224. )
  4225. async def on_print_start(printer_id: int, data: dict):
  4226. """Handle print start - archive the 3MF file immediately."""
  4227. logger = logging.getLogger(__name__)
  4228. # The print's start, before the 3MF download that the archive waits for
  4229. # (#3327): a minute of it would otherwise be missing from the print time.
  4230. detected_at = datetime.now(timezone.utc)
  4231. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  4232. try:
  4233. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  4234. except Exception:
  4235. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  4236. # Clear any stale user-stopped flag from previous print cycles
  4237. _user_stopped_printers.discard(printer_id)
  4238. _kill_switch_stopped.discard(printer_id)
  4239. # A new print starts its milestones from zero (#3211). The status path only
  4240. # resets on progress below 5 while not printing, which a printer that goes
  4241. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  4242. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  4243. # or on resume from pause, so it cannot repeat a milestone mid-print.
  4244. _last_progress_milestone[printer_id] = 0
  4245. _kill_switch_notification_tasks.pop(printer_id, None)
  4246. # #1721: drop any leftover pre-captured finish frame from a prior print
  4247. # so a never-consumed cache entry can't bleed into the new print's photo.
  4248. _stage22_finish_frames.pop(printer_id, None)
  4249. # #1867: same for the in-print frame bank — a queued print must not reuse
  4250. # the previous job's banked frame.
  4251. _inprint_frame_bank.pop(printer_id, None)
  4252. _inprint_frame_bank_ts.pop(printer_id, None)
  4253. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  4254. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  4255. # print's flag instead of inheriting it.
  4256. print_dispatch_context.adopt(printer_id)
  4257. # Cancel any active bed cooldown waiter for this printer
  4258. if _bed_cool_waiters.pop(printer_id, None):
  4259. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  4260. # Clear cached cover images so the new print's thumbnail is fetched fresh
  4261. from backend.app.api.routes.printers import clear_cover_cache
  4262. clear_cover_cache(printer_id)
  4263. await ws_manager.send_print_start(printer_id, data)
  4264. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  4265. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  4266. # MQTT relay - publish print start
  4267. try:
  4268. printer_info = printer_manager.get_printer(printer_id)
  4269. if printer_info:
  4270. await mqtt_relay.on_print_start(
  4271. printer_id,
  4272. printer_info.name,
  4273. printer_info.serial_number,
  4274. data.get("filename", ""),
  4275. data.get("subtask_name", ""),
  4276. )
  4277. except Exception:
  4278. pass # Don't fail print start callback if MQTT fails
  4279. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  4280. # and mapping, and the seeded tray-change log.
  4281. #
  4282. # Unconditional, for both inventory backends. This only *captures* — the
  4283. # writing is still split, with the internal tracker skipped at completion
  4284. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  4285. # carries its plate-scoped 3MF figures and stored mapping, but not the
  4286. # tray-change log, and that log is the only record of which spool fed
  4287. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  4288. # it on one side only would leave Spoolman users with the mid-print
  4289. # restart bug this fixes for everyone else.
  4290. try:
  4291. async with async_session() as db:
  4292. from backend.app.api.routes.settings import get_setting
  4293. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  4294. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4295. await usage_on_print_start(
  4296. printer_id,
  4297. data,
  4298. printer_manager,
  4299. db=db,
  4300. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  4301. )
  4302. except Exception as e:
  4303. logger.warning("Usage tracker on_print_start failed: %s", e)
  4304. # Track if notification was sent (to avoid sending twice)
  4305. notification_sent = False
  4306. # Smart plug automation: turn on plug when print starts
  4307. try:
  4308. async with async_session() as db:
  4309. await smart_plug_manager.on_print_start(printer_id, db)
  4310. except Exception as e:
  4311. logger.warning("Smart plug on_print_start failed: %s", e)
  4312. async with async_session() as db:
  4313. from backend.app.models.printer import Printer
  4314. from backend.app.services.bambu_ftp import list_files_async
  4315. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4316. printer = result.scalar_one_or_none()
  4317. # Plate detection check - pause if objects detected on build plate
  4318. logger.info(
  4319. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  4320. )
  4321. if printer and printer.plate_detection_enabled:
  4322. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  4323. # Release the pooled DB connection before the plate-detection camera
  4324. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  4325. # printer SELECT has run so far — nothing to persist — so this commit
  4326. # is a data-noop that ends the read transaction and returns the
  4327. # connection to the pool during the I/O (issue #2572). expire_on_commit
  4328. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  4329. # archive lookups below re-acquire a fresh connection on next execute.
  4330. await db.commit()
  4331. try:
  4332. from backend.app.services.plate_detection import check_plate_empty
  4333. # Build ROI tuple from printer settings if available
  4334. roi = None
  4335. if all(
  4336. [
  4337. printer.plate_detection_roi_x is not None,
  4338. printer.plate_detection_roi_y is not None,
  4339. printer.plate_detection_roi_w is not None,
  4340. printer.plate_detection_roi_h is not None,
  4341. ]
  4342. ):
  4343. roi = (
  4344. printer.plate_detection_roi_x,
  4345. printer.plate_detection_roi_y,
  4346. printer.plate_detection_roi_w,
  4347. printer.plate_detection_roi_h,
  4348. )
  4349. # The light is held, not switched, so a live view opened
  4350. # meanwhile keeps it when the check lets go (SP-C11). Every
  4351. # printer, whatever the camera light mode: detection needs it.
  4352. plate_photo_data = None
  4353. objects_detected = False
  4354. check_failure: str | None = None
  4355. async with camera_light(printer, any_mode=True, settle=2.5):
  4356. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  4357. plate_result = await check_plate_empty(
  4358. printer_id=printer_id,
  4359. ip_address=printer.ip_address,
  4360. access_code=printer.access_code,
  4361. model=printer.model,
  4362. include_debug_image=False,
  4363. external_camera_url=printer.external_camera_url,
  4364. external_camera_type=printer.external_camera_type,
  4365. use_external=printer.external_camera_enabled,
  4366. roi=roi,
  4367. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  4368. )
  4369. # No reference to compare against is a check that did not
  4370. # run either: say so rather than call the plate empty.
  4371. check_failure = getattr(plate_result, "failure_reason", None) or (
  4372. "not_calibrated" if plate_result.needs_calibration else None
  4373. )
  4374. objects_detected = not check_failure and not plate_result.is_empty
  4375. if objects_detected:
  4376. # Objects detected - pause the print!
  4377. logger.warning(
  4378. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  4379. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  4380. )
  4381. pause_client = printer_manager.get_client(printer_id)
  4382. if pause_client:
  4383. pause_client.pause_print()
  4384. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  4385. # Snapshot while the light's still on — restoring it first
  4386. # would leave the notification with a dark photo.
  4387. try:
  4388. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  4389. except Exception as snap_err:
  4390. logger.warning(
  4391. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  4392. )
  4393. if objects_detected:
  4394. # Send notification about plate not empty
  4395. await ws_manager.broadcast(
  4396. {
  4397. "type": "plate_not_empty",
  4398. "printer_id": printer_id,
  4399. "printer_name": printer.name,
  4400. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  4401. }
  4402. )
  4403. # Also send push notification
  4404. try:
  4405. await notification_service.on_plate_not_empty(
  4406. printer_id=printer_id,
  4407. printer_name=printer.name,
  4408. db=db,
  4409. difference_percent=plate_result.difference_percent,
  4410. image_data=plate_photo_data,
  4411. )
  4412. except Exception as notif_err:
  4413. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4414. elif check_failure:
  4415. logger.warning(
  4416. "[PLATE CHECK] Plate check could not run for printer %s (%s): %s; proceeding with print",
  4417. printer_id,
  4418. check_failure,
  4419. plate_result.message,
  4420. )
  4421. await _announce_plate_check_failed(printer_id, printer.name, check_failure)
  4422. else:
  4423. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4424. except Exception as plate_err:
  4425. # Don't block print on plate detection errors
  4426. logger.warning(
  4427. "[PLATE CHECK] Plate check could not run for printer %s: %s; proceeding with print",
  4428. printer_id,
  4429. plate_err,
  4430. )
  4431. await _announce_plate_check_failed(printer_id, printer.name, "error")
  4432. if not printer:
  4433. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4434. if not notification_sent:
  4435. await _send_print_start_notification(printer_id, data, logger=logger)
  4436. return
  4437. # Skip the printer's own jobs — a calibration run is not a user's print.
  4438. # See is_internal_printer_job for what counts and why both fields are
  4439. # tested; the pressure-advance line reports as a subtask name with no
  4440. # /usr/ path, which the old prefix-only test here missed entirely.
  4441. #
  4442. # No notification either. The event describes the printer calibrating
  4443. # itself, so "Print started" is as wrong as the archive was, and the
  4444. # matching completion is suppressed in on_print_complete for the same
  4445. # reason. Checked before the auto-archive switches, whose "off" path
  4446. # still notifies.
  4447. # A /usr/ path is the printer's own file. A name alone is not proof: a
  4448. # print Bambuddy dispatched is never one, whatever it is called.
  4449. # Dispatched = an expected print, or, after a restart that lost those,
  4450. # a queue job printing on the printer.
  4451. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")) and (
  4452. (data.get("filename") or "").startswith("/usr/")
  4453. or not await _dispatched_by_bambuddy(db, printer_id, data.get("filename", ""), data.get("subtask_name", ""))
  4454. ):
  4455. logger.info(
  4456. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4457. data.get("filename", ""),
  4458. data.get("subtask_name", ""),
  4459. )
  4460. return
  4461. # The global switch is the master: off, no printer archives prints
  4462. # started outside Bambuddy; on, each printer's own switch decides.
  4463. from backend.app.api.routes.settings import get_setting
  4464. _global_auto_archive = await get_setting(db, "auto_archive")
  4465. archives_prints = printer.auto_archive and (
  4466. _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4467. )
  4468. if not archives_prints:
  4469. # auto-archive disabled — check if there's an expected print (dispatched
  4470. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4471. # If so, fall through to the expected-print handling below so the archive
  4472. # is tracked in _active_prints and usage tracking works at completion.
  4473. _fn = data.get("filename", "")
  4474. _sn = data.get("subtask_name", "")
  4475. _check_keys: list[tuple[int, str]] = []
  4476. if _sn:
  4477. _check_keys += [
  4478. (printer_id, _sn),
  4479. (printer_id, f"{_sn}.3mf"),
  4480. (printer_id, f"{_sn}.gcode.3mf"),
  4481. ]
  4482. if _fn:
  4483. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4484. _check_keys.append((printer_id, _base_fn))
  4485. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4486. _check_keys += [
  4487. (printer_id, _no_archive_base),
  4488. (printer_id, f"{_no_archive_base}.3mf"),
  4489. ]
  4490. _has_expected = any(k in _expected_prints for k in _check_keys)
  4491. if not _has_expected:
  4492. # No expected print — truly external print (started from slicer/touchscreen)
  4493. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4494. if not notification_sent:
  4495. _no_archive_creator: int | None = None
  4496. for _key in _check_keys:
  4497. _expected_prints.pop(_key, None)
  4498. _expected_print_registered_at.pop(_key, None)
  4499. popped_creator = _expected_print_creators.pop(_key, None)
  4500. if _no_archive_creator is None:
  4501. _no_archive_creator = popped_creator
  4502. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4503. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4504. return
  4505. else:
  4506. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4507. # Get the filename and subtask_name
  4508. filename = data.get("filename", "")
  4509. subtask_name = data.get("subtask_name", "")
  4510. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4511. # present, it lets us match an archive across a backend restart (#972):
  4512. # same id → same print → resume the existing row instead of cancelling
  4513. # it and recreating from scratch (which loses started_at). Treat "0"
  4514. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4515. raw_mqtt = data.get("raw_data") or {}
  4516. subtask_id = raw_mqtt.get("subtask_id")
  4517. if subtask_id is not None:
  4518. subtask_id = str(subtask_id).strip()
  4519. if subtask_id in ("", "0"):
  4520. subtask_id = None
  4521. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4522. if not filename and not subtask_name:
  4523. # Send notification without archive data (no filename)
  4524. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4525. if not notification_sent:
  4526. await _send_print_start_notification(printer_id, data, logger=logger)
  4527. return
  4528. # Check if this is an expected print from reprint/scheduled
  4529. expected_keys = _expected_print_keys(printer_id, filename, subtask_name)
  4530. expected_archive_id = None
  4531. # Who queued it, taken with the entries it was registered beside: left
  4532. # behind once those are gone (the archive deleted mid-dispatch, or the
  4533. # start notification already sent), the expiry never saw it, and an
  4534. # unrelated later print of that name was attributed to that user (EP-2).
  4535. fallback_creator = None
  4536. for key in expected_keys:
  4537. expected_archive_id = _expected_prints.pop(key, None)
  4538. _expected_print_registered_at.pop(key, None)
  4539. if expected_archive_id:
  4540. # Clean up other possible keys for this print
  4541. for other_key in expected_keys:
  4542. _expected_prints.pop(other_key, None)
  4543. _expected_print_registered_at.pop(other_key, None)
  4544. creator = _expected_print_creators.pop(other_key, None)
  4545. if fallback_creator is None:
  4546. fallback_creator = creator
  4547. break
  4548. if expected_archive_id:
  4549. # This is a reprint/scheduled print - use existing archive, don't create new one
  4550. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4551. # Bambuddy dispatched it: the kill switch's fast path keeps it as
  4552. # Bambuddy's once the expected entry is consumed here.
  4553. _owned_print_archive_ids.add(expected_archive_id)
  4554. from backend.app.models.archive import PrintArchive
  4555. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4556. archive = result.scalar_one_or_none()
  4557. # Deleted after this handler loaded it (the plate check waits
  4558. # seconds) but before the route forgot the expected print: the
  4559. # archive the route kept or deleted is left as the route left it.
  4560. if archive and await _printer_gone(db, printer_id):
  4561. logger.info(
  4562. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4563. )
  4564. await forget_printer(printer_id)
  4565. return
  4566. if archive:
  4567. # As it was before this adoption: put back if the printer turns
  4568. # out to have been deleted while it was adopted (below).
  4569. before_adoption = {
  4570. attr.columns[0].name: getattr(archive, attr.key)
  4571. for attr in sa_inspect(PrintArchive).column_attrs
  4572. if attr.key != "id"
  4573. }
  4574. # Update archive status to printing
  4575. archive.status = "printing"
  4576. archive.started_at = datetime.now(timezone.utc)
  4577. # The previous run's outcome is not this one's: a reprint that
  4578. # completes must not keep showing why the last one failed.
  4579. archive.failure_reason = None
  4580. archive.completed_at = None
  4581. # The previous run's answer is still on this row and the
  4582. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4583. # so without a reset the second run inherits the first run's
  4584. # verdict: no prompt at all, and a green "good" badge on a run
  4585. # nobody ever judged.
  4586. if archive.confirm_requested:
  4587. archive.user_verdict = None
  4588. archive.user_verdict_source = None
  4589. archive.user_verdict_at = None
  4590. archive.confirm_token = None
  4591. archive.confirm_token_used_at = None
  4592. # Reprint of an archive reuses the source row. Without resetting
  4593. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4594. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4595. # extracts the *original* print's last frame, which then ships in
  4596. # the completion notification (#1707). Clear the path so the
  4597. # scanner runs fresh; also unlink the old video file so reprints
  4598. # don't accumulate orphans in the archive directory. Photos list
  4599. # is left alone — accumulating one finish photo per run is fine.
  4600. # The print-start baseline (#2704) is stale for the same reason:
  4601. # it describes the printer before the previous run. The capture
  4602. # below overwrites it, but clear it here too so an early failure
  4603. # can't leave the scan diffing against the wrong snapshot.
  4604. #
  4605. # Unlinked only when it is the same plate printing again. Every
  4606. # plate of a Send All shares this archive, and the video on it
  4607. # can be the only copy of another plate's run -- the printer's
  4608. # was deleted once it attached (#3275). That one is left in the
  4609. # archive directory, which goes with the archive. A video whose
  4610. # plate is not on record (attached by hand, or before the
  4611. # column existed) is kept too where the 3MF has other plates,
  4612. # or cannot be read: nothing tells it apart from another plate's,
  4613. # and keeping costs one file where deleting can cost the only
  4614. # copy. On an archive with exactly one plate it is that plate's.
  4615. archive.timelapse_baseline = None
  4616. stale_timelapse_relpath = archive.timelapse_path
  4617. stale_timelapse_plate_id = archive.timelapse_plate_id
  4618. starting_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4619. if stale_timelapse_relpath:
  4620. archive.timelapse_path = None
  4621. archive.timelapse_plate_id = None
  4622. stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
  4623. if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
  4624. from backend.app.services.archive import plate_indexes_in_3mf
  4625. plates = await asyncio.to_thread(
  4626. plate_indexes_in_3mf,
  4627. app_settings.base_dir / archive.file_path, # SEC-PATH-OK: stored relative archive path
  4628. )
  4629. stale_is_this_plates = len(plates) == 1
  4630. if stale_timelapse_relpath and not stale_is_this_plates:
  4631. logger.info(
  4632. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4633. stale_timelapse_relpath,
  4634. stale_timelapse_plate_id,
  4635. expected_archive_id,
  4636. starting_plate_id,
  4637. )
  4638. # The video is deleted once the adoption stands (below).
  4639. delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
  4640. # Persist a restart-stable id so a later restart resumes this
  4641. # archive by subtask_id instead of name-matching + duplicating
  4642. # it (#1485). The printer often hasn't echoed subtask_id back
  4643. # this soon after dispatch, so fall back to the id Bambuddy
  4644. # minted when it sent the print command. Scoped to this
  4645. # expected-print branch on purpose: an expected match means
  4646. # Bambuddy dispatched this exact print in this process, so the
  4647. # client's last-dispatch id genuinely belongs to it — using it
  4648. # for an externally-started print could mis-tag the archive.
  4649. effective_subtask_id = subtask_id
  4650. if not effective_subtask_id:
  4651. _client = printer_manager.get_client(printer_id)
  4652. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4653. if _dispatched:
  4654. effective_subtask_id = str(_dispatched).strip() or None
  4655. # Update on first-set OR on reprint (the queue dispatcher mints
  4656. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4657. # the rewrite for reprints leaves the archive holding the FIRST
  4658. # run's id; if MQTT then reconnects mid-print, the reconciler
  4659. # (#1542) compares the stale stored id against the printer's
  4660. # live id, sees a mismatch, and synthesises a bogus PRINT
  4661. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4662. # in #1807. Inequality check preserves the noop-on-stable-push
  4663. # behaviour the earlier `not archive.subtask_id` guard provided.
  4664. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4665. archive.subtask_id = effective_subtask_id
  4666. # #1403 follow-up: VP-queue archives are created with
  4667. # printer_id=None at queue-add time (we don't know which
  4668. # printer will run the job yet). When the print actually
  4669. # starts on a specific printer the expected-archive lookup
  4670. # used to skip this assignment, leaving printer_id=None
  4671. # forever — which then disables the "Scan for timelapse"
  4672. # button in ArchivesPage (gated on !archive.printer_id).
  4673. if archive.printer_id != printer_id:
  4674. archive.printer_id = printer_id
  4675. adopting_id = archive.id # a rollback expires the object
  4676. try:
  4677. await db.commit()
  4678. except (IntegrityError, StaleDataError):
  4679. # The archive stays unchanged, or is gone: "delete archives"
  4680. # removed the row under the adoption, which then matched no
  4681. # row (StaleDataError) rather than being refused.
  4682. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4683. return
  4684. raise
  4685. # The printer can be deleted between the check above and this
  4686. # commit (the route's transaction lasts seconds), and the commit
  4687. # then adopted the archive anyway: status, verdict and timelapse
  4688. # changed, and the deleted printer's id written on a row the
  4689. # route had detached or never touched. Undo the adoption.
  4690. if await _printer_gone(db, printer_id):
  4691. logger.info(
  4692. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4693. printer_id,
  4694. archive.id,
  4695. )
  4696. # Everything as before this adoption. The printer it had
  4697. # then stays, unless it was the deleted one: the route
  4698. # detached that row (kept) or deleted it (no row matches).
  4699. previous_printer = before_adoption["printer_id"]
  4700. await db.execute(
  4701. update(PrintArchive)
  4702. .where(PrintArchive.id == archive.id)
  4703. .values(
  4704. {
  4705. **before_adoption,
  4706. "printer_id": None if previous_printer == printer_id else previous_printer,
  4707. }
  4708. )
  4709. )
  4710. await db.commit()
  4711. await forget_printer(printer_id)
  4712. return
  4713. if delete_stale_video and stale_timelapse_relpath:
  4714. try:
  4715. stale_path = app_settings.base_dir / stale_timelapse_relpath
  4716. if stale_path.is_file():
  4717. stale_path.unlink()
  4718. logger.info(
  4719. "Deleted stale timelapse %s on reprint of archive %s",
  4720. stale_timelapse_relpath,
  4721. expected_archive_id,
  4722. )
  4723. except OSError as e:
  4724. logger.warning(
  4725. "Failed to delete stale timelapse %s on reprint: %s",
  4726. stale_timelapse_relpath,
  4727. e,
  4728. )
  4729. # Track as active print
  4730. _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
  4731. await _open_run_for(archive.id, printer_id, subtask_id)
  4732. # Start timelapse session if external camera is enabled (#1353).
  4733. # Queue / VP-dispatched prints land here in the expected-archive
  4734. # branch and used to skip start_session entirely — frames were
  4735. # never captured and the post-print stitch silently returned None.
  4736. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4737. # Inject ams_mapping into usage tracker session — the session was created
  4738. # before expected-print promotion, so it may have ams_mapping=None when
  4739. # the MQTT request topic subscription failed (common on P1S/A1).
  4740. _stored_map = _print_ams_mappings.get((printer_id, expected_archive_id))
  4741. _stored_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4742. if _stored_map or _stored_plate_id is not None:
  4743. try:
  4744. from backend.app.services.usage_tracker import _active_sessions
  4745. _ut_session = _active_sessions.get(printer_id)
  4746. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4747. _ut_session.ams_mapping = _stored_map
  4748. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4749. # plate_id injection covers direct-Print of plate N of a multi-plate
  4750. # 3MF — queue prints already capture it via the on_print_start queue
  4751. # lookup, but direct-Print never goes through the queue (#1697).
  4752. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4753. _ut_session.plate_id = _stored_plate_id
  4754. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4755. except Exception:
  4756. pass
  4757. # Set up energy tracking (#941: persist start on archive row)
  4758. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4759. await ws_manager.send_archive_updated(
  4760. {
  4761. "id": archive.id,
  4762. "status": "printing",
  4763. }
  4764. )
  4765. # Send notification with archive data (reprint/scheduled)
  4766. if not notification_sent:
  4767. # Use archive's created_by_id; fall back to the creator registered via
  4768. # register_expected_print (handles library-file-based queue items where
  4769. # the freshly-created archive has no created_by_id yet), taken above.
  4770. archive_data = {
  4771. "print_time_seconds": archive.print_time_seconds,
  4772. "created_by_id": archive.created_by_id or fallback_creator,
  4773. }
  4774. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4775. # Extract printable objects from the archived 3MF file
  4776. _load_objects_from_archive(archive, printer_id, logger)
  4777. if archive.file_path:
  4778. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  4779. # Store Spoolman tracking data for per-filament usage reporting
  4780. try:
  4781. await _store_spoolman_print_data(
  4782. printer_id,
  4783. archive.id,
  4784. archive.file_path,
  4785. db,
  4786. printer_manager,
  4787. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4788. plate_id=_get_start_plate_id(printer_id, archive.id),
  4789. )
  4790. except Exception as e:
  4791. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4792. # Price the print from its spools now rather than only at completion (#3261)
  4793. _schedule_archive_cost_estimate(
  4794. printer_id,
  4795. archive.id,
  4796. printer_manager,
  4797. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4798. plate_id=_get_start_plate_id(printer_id, archive.id),
  4799. session_factory=async_session,
  4800. )
  4801. # Capture timelapse file baseline for snapshot-diff on completion
  4802. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4803. # hit this branch — without the baseline the completion-time scan
  4804. # falls into its "take baseline now" fallback, which snapshots
  4805. # AFTER the new MP4 already exists and never matches a diff
  4806. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4807. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4808. await _forget_if_printer_gone(printer_id)
  4809. return # Skip creating a new archive
  4810. # The archive was deleted after the job was queued.
  4811. if not archives_prints:
  4812. # Only the expected print brought a printer that does not
  4813. # archive this far; with it gone, nothing is archived.
  4814. return
  4815. # Otherwise archive the print anew rather than drop it, so it still
  4816. # gets its notification, usage tracking and history.
  4817. logger.warning(
  4818. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4819. expected_archive_id,
  4820. printer_id,
  4821. )
  4822. # Check if there's already a "printing" archive for this printer/file
  4823. # This prevents duplicates when backend restarts during an active print
  4824. from backend.app.models.archive import PrintArchive
  4825. existing_archive: PrintArchive | None = None
  4826. resumed_by_run = False
  4827. # Best match: this job's run, open on the printer since the print
  4828. # started. The archive row is shared by every plate of it, and its
  4829. # printer, job id and status are the latest start's, which may be
  4830. # another printer's.
  4831. if subtask_id:
  4832. from backend.app.services.print_log import open_run_on_printer
  4833. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  4834. if run is not None and run.archive_id is not None:
  4835. existing_archive = await db.scalar(
  4836. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  4837. )
  4838. resumed_by_run = existing_archive is not None
  4839. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4840. # across a backend restart for the same print, so this is the most
  4841. # reliable way to reattach. Only a row still printing: a cancelled one
  4842. # has been through completion (usage, history, notifications) already,
  4843. # and reopening it would count the print twice.
  4844. if subtask_id and existing_archive is None:
  4845. by_id = await db.execute(
  4846. select(PrintArchive)
  4847. .where(PrintArchive.printer_id == printer_id)
  4848. .where(PrintArchive.subtask_id == subtask_id)
  4849. .where(PrintArchive.status == "printing")
  4850. .order_by(PrintArchive.created_at.desc())
  4851. .limit(1)
  4852. )
  4853. existing_archive = by_id.scalar_one_or_none()
  4854. # Fallback match: name-based lookup. Kept as-is for prints whose
  4855. # subtask_id is missing ("0" / local / non-cloud prints).
  4856. if existing_archive is None:
  4857. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4858. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4859. # A print started from the printer's screen names its file in full,
  4860. # so the forms above double its extension. The file itself is the
  4861. # one exact match, and nothing looser is added (#3009).
  4862. if _subtask_is_the_file(subtask_name, filename):
  4863. archive_filenames.append(subtask_name)
  4864. existing = await db.execute(
  4865. select(PrintArchive)
  4866. .where(PrintArchive.printer_id == printer_id)
  4867. .where(PrintArchive.status == "printing")
  4868. .where(
  4869. or_(
  4870. PrintArchive.print_name == check_name,
  4871. PrintArchive.filename.in_(archive_filenames),
  4872. )
  4873. )
  4874. .order_by(PrintArchive.created_at.desc())
  4875. .limit(1)
  4876. )
  4877. existing_archive = existing.scalar_one_or_none()
  4878. if existing_archive:
  4879. # subtask_id match → always resume, regardless of age. Same print,
  4880. # just a backend restart.
  4881. subtask_match = resumed_by_run or bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4882. if subtask_match:
  4883. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4884. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4885. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  4886. _mark_owned_if_dispatched(existing_archive)
  4887. if await _run_needs_energy_start(existing_archive, printer_id, db):
  4888. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4889. if not notification_sent:
  4890. archive_data = {
  4891. "print_time_seconds": existing_archive.print_time_seconds,
  4892. "created_by_id": existing_archive.created_by_id,
  4893. }
  4894. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4895. _load_objects_from_archive(existing_archive, printer_id, logger)
  4896. if existing_archive.file_path:
  4897. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  4898. return
  4899. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4900. # stale from the printer's *current* progress, not wall-clock age.
  4901. # A genuinely long print used to trip a blind 4h cutoff and have its
  4902. # live archive cancelled + duplicated on every backend restart
  4903. # (#1485). If the printer reports real progress, this name-matched
  4904. # 'printing' archive IS that ongoing print — resume it whatever its
  4905. # age. Only treat it as a stale leftover when the printer clearly
  4906. # shows a different, freshly-started print: near-0% progress on an
  4907. # archive far too old to still be at 0%. Unknown progress (printer
  4908. # not connected) never cancels — resuming is the safe default.
  4909. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4910. live_status = printer_manager.get_status(printer_id)
  4911. live_progress = getattr(live_status, "progress", None) if live_status else None
  4912. looks_stale = (
  4913. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4914. )
  4915. # Two subtask ids are two prints, however young the archive: one
  4916. # whose completion was missed must not swallow the next print of
  4917. # the same file. Except Bambuddy's own reprint, which reuses the
  4918. # row and mints a fresh id (#1807): the id it last sent says so,
  4919. # and after a restart, which forgets it, this printer's queue job
  4920. # running the archive.
  4921. if (
  4922. not looks_stale
  4923. and subtask_id
  4924. and existing_archive.subtask_id
  4925. and existing_archive.subtask_id != subtask_id
  4926. ):
  4927. _client = printer_manager.get_client(printer_id)
  4928. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  4929. if _dispatched:
  4930. looks_stale = _dispatched != subtask_id
  4931. else:
  4932. from backend.app.models.print_queue import PrintQueueItem as _PQI
  4933. queue_run = await db.scalar(
  4934. select(_PQI.id)
  4935. .where(_PQI.archive_id == existing_archive.id)
  4936. .where(_PQI.printer_id == printer_id)
  4937. .where(_PQI.status == "printing")
  4938. .limit(1)
  4939. )
  4940. looks_stale = queue_run is None
  4941. if looks_stale:
  4942. logger.warning(
  4943. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  4944. " — marking cancelled and creating new archive",
  4945. existing_archive.id,
  4946. archive_age,
  4947. live_progress,
  4948. existing_archive.subtask_id,
  4949. subtask_id,
  4950. )
  4951. existing_archive.status = "cancelled"
  4952. # Canonical key, not a sentence (issue #2974). "No status update
  4953. # received" is what both stale paths actually observed; which of
  4954. # the two it was is already carried by ``status`` -- cancelled
  4955. # here, the reconciled outcome at the reconnect site -- so one
  4956. # key loses no information and gives the Statistics breakdown a
  4957. # single bucket instead of two untranslatable prose strings.
  4958. existing_archive.failure_reason = "noStatusUpdate"
  4959. # And its run, as before runs were opened at the start: a new
  4960. # print starts on the printer, so whatever is open there ended
  4961. # unseen. Left open, the next reconnect would close it again.
  4962. from backend.app.services.print_log import discard_open_runs
  4963. await discard_open_runs(db, printer_id)
  4964. await db.commit()
  4965. # Its print keys go with it; the new archive registers its own.
  4966. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id and k[0] == printer_id]:
  4967. del _active_prints[_key]
  4968. # Fall through to create new archive (don't return)
  4969. else:
  4970. logger.info(
  4971. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4972. )
  4973. # Track this as the active print
  4974. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4975. _mark_owned_if_dispatched(existing_archive)
  4976. # Attach subtask_id retroactively so future restarts can resume.
  4977. # Compare for inequality (not "is empty") to also pick up reprint
  4978. # dispatches that mint a fresh id — see #1807 for the bogus
  4979. # "Print Stopped" the strict-empty guard caused on reconnect.
  4980. if subtask_id and existing_archive.subtask_id != subtask_id:
  4981. existing_archive.subtask_id = subtask_id
  4982. await db.commit()
  4983. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  4984. # Also set up energy tracking if not already tracked (#941: persisted column)
  4985. if await _run_needs_energy_start(existing_archive, printer_id, db):
  4986. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4987. # Send notification with archive data (existing archive)
  4988. if not notification_sent:
  4989. archive_data = {
  4990. "print_time_seconds": existing_archive.print_time_seconds,
  4991. "created_by_id": existing_archive.created_by_id,
  4992. }
  4993. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4994. # Extract printable objects from the archived 3MF file
  4995. _load_objects_from_archive(existing_archive, printer_id, logger)
  4996. if existing_archive.file_path:
  4997. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  4998. return
  4999. # Build list of possible 3MF filenames to try
  5000. possible_names = []
  5001. # Bambu printers typically store files as "Name.gcode.3mf"
  5002. # The subtask_name is usually the best source for the filename
  5003. if subtask_name:
  5004. if _subtask_is_the_file(subtask_name, filename):
  5005. # A print started from the printer's own screen reports the
  5006. # file's full name, extension included. That is the file, so
  5007. # no extension is appended to it (#3009).
  5008. possible_names.append(subtask_name)
  5009. else:
  5010. # Try common Bambu naming patterns
  5011. possible_names.append(f"{subtask_name}.gcode.3mf")
  5012. possible_names.append(f"{subtask_name}.3mf")
  5013. # Try original filename with .3mf extension
  5014. if filename:
  5015. # Extract just the filename part, not the full path
  5016. fname = filename.split("/")[-1] if "/" in filename else filename
  5017. if fname.endswith(".3mf"):
  5018. possible_names.append(fname)
  5019. elif fname.endswith(".gcode"):
  5020. base = fname.rsplit(".", 1)[0]
  5021. possible_names.append(f"{base}.gcode.3mf")
  5022. possible_names.append(f"{base}.3mf")
  5023. else:
  5024. possible_names.append(f"{fname}.gcode.3mf")
  5025. possible_names.append(f"{fname}.3mf")
  5026. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  5027. space_variants = []
  5028. for name in possible_names:
  5029. if " " in name:
  5030. space_variants.append(name.replace(" ", "_"))
  5031. possible_names.extend(space_variants)
  5032. # Remove duplicates while preserving order
  5033. seen = set()
  5034. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  5035. logger.info("Trying filenames: %s", possible_names)
  5036. # Release the pooled DB connection before the 3MF FTP download. Reaching
  5037. # here means none of the expected-/existing-archive write branches ran
  5038. # (they all return earlier) — only SELECTs have executed on this path, so
  5039. # this commit persists nothing; it ends the read transaction so the
  5040. # connection returns to the pool during the download. That download tries
  5041. # up to five remote paths per candidate filename with retry/backoff and
  5042. # can run for minutes under FTP contention; holding the session across it
  5043. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  5044. # work runs during the download — the new-archive writes below re-acquire
  5045. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  5046. await db.commit()
  5047. # Try to find and download the 3MF file
  5048. temp_path = None
  5049. downloaded_filename = None
  5050. # Cache check: cover endpoint may have already pulled this 3MF during
  5051. # the print (frontend opens the card and shows the thumbnail) — reuse
  5052. # that file instead of re-downloading 36MB over the same FTP link that
  5053. # just served it (#972). The cache keys on a normalized filename so
  5054. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  5055. for try_filename in possible_names:
  5056. if not try_filename.endswith(".3mf"):
  5057. continue
  5058. cached = get_cached_3mf(printer_id, try_filename)
  5059. if cached:
  5060. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  5061. temp_path = cached
  5062. downloaded_filename = try_filename
  5063. break
  5064. # Does this printer keep the sliced file somewhere FTPS can reach? On
  5065. # H2-series and P2S the answer is routinely no — the file stays on
  5066. # internal eMMC and port 990 only ever serves external storage — and
  5067. # then the whole sweep below (six filenames x five directories x four
  5068. # retries, then the directory walk) is ~110 connections that cannot
  5069. # succeed. Skip it and say why (#2780).
  5070. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  5071. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  5072. # running rather than because the file is somewhere unreachable. The
  5073. # distinction is the whole of #2957: one is permanent, the other clears
  5074. # in minutes with the file still sitting on the printer.
  5075. blocked_by_ftps_cooloff = False
  5076. # Set when a probe reached the printer and still came back without the
  5077. # file -- a timeout mid-transfer, a refused connection, anything that is
  5078. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  5079. # caught by name below, so a file that genuinely is not on the card
  5080. # leaves this False and schedules nothing. Anything else means the
  5081. # transfer, not the file, is what failed, and that does not last (#3063).
  5082. ftp_transfer_failed = False
  5083. # The narrower case of the above: the directory walk *listed* a file
  5084. # for this print and could not fetch it, so the file is on the card
  5085. # under a name that matches. The only failure that rules out an
  5086. # earlier run's 3MF standing in for it (#3307).
  5087. walk_transfer_failed = False
  5088. # Paths the sweep reached and could not transfer -- a timeout, not a
  5089. # 550. The directory walk lists the same folders and would download
  5090. # the same file again: on a slow A1 that was a second 300 s on the
  5091. # printer's one FTPS slot, at print start, for a file the recovery
  5092. # retry fetches with a deadline twice as long (#3308).
  5093. sweep_failed_paths: set[str] = set()
  5094. # The print's name, for a fallback archive whose `subtask_name` the
  5095. # plate guard below had to disown. Display only, and deliberately kept
  5096. # apart from `subtask_name`: that variable is what every file lookup
  5097. # here is built from, and once a name has been shown to fetch another
  5098. # plate's 3MF it must not key `_active_prints` either, or the cover
  5099. # endpoint hands the same contradicted file to
  5100. # `_recover_fallback_archive` and fills the row in with it (#3126).
  5101. display_name_after_plate_reject: str | None = None
  5102. # Get FTP retry settings
  5103. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  5104. # ...but "the printer put it on eMMC" is where it went, not whether we
  5105. # can read it. An H2D with a card in mirrors the job to /cache and
  5106. # serves it happily, and skipping on the URL alone cost that reporter
  5107. # every archive for two days (#2856). So ask the printer instead of
  5108. # guessing: the dispatch named the exact file, which is one connection
  5109. # walking five paths rather than the sweep's ~110. Only when the probe
  5110. # comes back empty does the verdict's reason stand.
  5111. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  5112. if ftps_handshake_blocked(printer.ip_address):
  5113. # Deliberately NOT recorded as a cool-off give-up. This branch
  5114. # only runs on an unreachable verdict, and that verdict is the
  5115. # honest, permanent reason the archive is empty — the probe was
  5116. # a long shot on top of it. Blaming the cool-off here would
  5117. # schedule a retry for a file sitting on internal eMMC, which is
  5118. # the sweep #2780 removed (#2957).
  5119. logger.debug(
  5120. "Not probing for %s on printer %s: its file service is not answering over TLS",
  5121. storage.probe_filename,
  5122. printer_id,
  5123. )
  5124. else:
  5125. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  5126. probe_path.parent.mkdir(parents=True, exist_ok=True)
  5127. try:
  5128. probe_hit = await download_file_try_paths_async(
  5129. printer.ip_address,
  5130. printer.access_code,
  5131. ftp_probe_paths(storage.probe_filename),
  5132. probe_path,
  5133. socket_timeout=ftp_timeout,
  5134. printer_model=printer.model,
  5135. )
  5136. except Exception as e:
  5137. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  5138. probe_hit = False
  5139. if probe_hit:
  5140. downloaded_filename = storage.probe_filename
  5141. temp_path = probe_path
  5142. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  5143. # Naming the path, not just the file: a printer that keeps
  5144. # uploads around for weeks can serve a same-named copy of an
  5145. # earlier slice, and without the directory in the log that
  5146. # mismatch is invisible rather than merely rare (#1820).
  5147. logger.info(
  5148. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  5149. downloaded_filename,
  5150. probe_hit,
  5151. printer_id,
  5152. storage.reason,
  5153. )
  5154. if not storage.reachable and not downloaded_filename:
  5155. # Same opening words whether or not a probe ran, because that is
  5156. # the phrase support asks people to grep for — only the tail says
  5157. # which of the two happened.
  5158. logger.info(
  5159. "Skipping the 3MF lookup for printer %s: %s — %s",
  5160. printer_id,
  5161. storage.reason,
  5162. "no copy of it on external storage either"
  5163. if storage.probe_filename
  5164. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  5165. )
  5166. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  5167. if not try_filename.endswith(".3mf"):
  5168. continue
  5169. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  5170. # printers, so try it first — deferring it to last cost #972's reporter
  5171. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  5172. # landing on the path that actually had the file.
  5173. remote_paths = [
  5174. f"/{try_filename}",
  5175. f"/cache/{try_filename}",
  5176. f"/model/{try_filename}",
  5177. f"/data/{try_filename}",
  5178. f"/data/Metadata/{try_filename}",
  5179. ]
  5180. temp_path = app_settings.archive_dir / "temp" / try_filename
  5181. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5182. for remote_path in remote_paths:
  5183. if ftps_handshake_blocked(printer.ip_address):
  5184. # The printer's FTPS service is not completing a TLS
  5185. # handshake, so it has no path we could reach — walking the
  5186. # remaining candidates only re-runs the same failure
  5187. # (#2780). Fall through to the no-3MF archive now.
  5188. #
  5189. # Remember *why*, though. This is the one give-up that is
  5190. # temporary: the cool-off clears in minutes and the file was
  5191. # on the printer the whole time. The fallback archive is
  5192. # stamped with it so a retry can be scheduled, and so the
  5193. # Archives banner stops blaming storage (#2957).
  5194. blocked_by_ftps_cooloff = True
  5195. logger.warning(
  5196. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  5197. printer_id,
  5198. )
  5199. break
  5200. logger.debug("Trying FTP download: %s", remote_path)
  5201. try:
  5202. if ftp_retry_enabled:
  5203. downloaded = await with_ftp_retry(
  5204. download_file_async,
  5205. printer.ip_address,
  5206. printer.access_code,
  5207. remote_path,
  5208. temp_path,
  5209. timeout=ftp_timeout,
  5210. socket_timeout=ftp_timeout,
  5211. printer_model=printer.model,
  5212. max_retries=ftp_retry_count,
  5213. retry_delay=ftp_retry_delay,
  5214. operation_name=f"Download 3MF from {remote_path}",
  5215. cooloff_ip=printer.ip_address,
  5216. non_retry_exceptions=(FileNotOnPrinterError,),
  5217. )
  5218. else:
  5219. downloaded = await download_file_async(
  5220. printer.ip_address,
  5221. printer.access_code,
  5222. remote_path,
  5223. temp_path,
  5224. timeout=ftp_timeout,
  5225. socket_timeout=ftp_timeout,
  5226. printer_model=printer.model,
  5227. )
  5228. if downloaded:
  5229. downloaded_filename = try_filename
  5230. logger.info("Downloaded: %s", remote_path)
  5231. # Populate shared cache so the cover endpoint (if it
  5232. # runs next) doesn't refetch the same 36MB over FTP.
  5233. cache_3mf_download(printer_id, try_filename, temp_path)
  5234. break
  5235. # with_ftp_retry returns None once it has spent its budget,
  5236. # and download_file_async returns False on a timeout, so an
  5237. # exhausted transfer arrives here rather than as an
  5238. # exception (#3063).
  5239. ftp_transfer_failed = True
  5240. sweep_failed_paths.add(remote_path)
  5241. except FileNotOnPrinterError:
  5242. # 550 — file isn't at this path. Advance to next candidate
  5243. # without burning the retry budget.
  5244. logger.debug("3MF not at %s (550), trying next path", remote_path)
  5245. except Exception as e:
  5246. ftp_transfer_failed = True
  5247. sweep_failed_paths.add(remote_path)
  5248. logger.debug("FTP download failed for %s: %s", remote_path, e)
  5249. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  5250. break
  5251. # If still not found, try listing directories to find matching file
  5252. # Different printer models use different directory structures. Skipped
  5253. # when the printer's FTPS handshake is failing — the directory walk is
  5254. # five more connections that cannot get further than the download did.
  5255. if (
  5256. not downloaded_filename
  5257. and storage.reachable
  5258. and (filename or subtask_name)
  5259. and not ftps_handshake_blocked(printer.ip_address)
  5260. ):
  5261. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  5262. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  5263. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  5264. # Every folder is listed before one file is picked, so a file named
  5265. # for the print in a later folder wins over one that merely
  5266. # contains the name in an earlier folder.
  5267. listed_paths: list[str] = []
  5268. for search_dir in search_dirs:
  5269. try:
  5270. dir_files = await list_files_async(
  5271. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  5272. )
  5273. except Exception as e:
  5274. logger.debug("Failed to list %s: %s", search_dir, e)
  5275. continue
  5276. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  5277. if threemf_files:
  5278. logger.info(
  5279. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  5280. )
  5281. listed_paths += [
  5282. posixpath.join(search_dir, f.get("name", "")) for f in dir_files if not f.get("is_directory")
  5283. ]
  5284. for remote_full_path in _3mf_files_for_print(listed_paths, search_term):
  5285. if remote_full_path in sweep_failed_paths:
  5286. # Listed for this print, and its transfer already failed:
  5287. # the same as a failed walk download, without spending a
  5288. # second deadline on it. Skipping it cannot hand the walk a
  5289. # look-alike: while a file of the print's own name is
  5290. # listed, files that merely contain the name are not.
  5291. logger.info(
  5292. "Not downloading %s again: its transfer already failed; the recovery retry will fetch it",
  5293. remote_full_path,
  5294. )
  5295. walk_transfer_failed = True
  5296. continue
  5297. fname = posixpath.basename(remote_full_path)
  5298. logger.info("Found matching file: %s", remote_full_path)
  5299. temp_path = app_settings.archive_dir / "temp" / fname
  5300. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5301. try:
  5302. if ftp_retry_enabled:
  5303. downloaded = await with_ftp_retry(
  5304. download_file_async,
  5305. printer.ip_address,
  5306. printer.access_code,
  5307. remote_full_path,
  5308. temp_path,
  5309. timeout=ftp_timeout,
  5310. socket_timeout=ftp_timeout,
  5311. printer_model=printer.model,
  5312. max_retries=ftp_retry_count,
  5313. retry_delay=ftp_retry_delay,
  5314. operation_name=f"Download 3MF from {remote_full_path}",
  5315. cooloff_ip=printer.ip_address,
  5316. )
  5317. else:
  5318. downloaded = await download_file_async(
  5319. printer.ip_address,
  5320. printer.access_code,
  5321. remote_full_path,
  5322. temp_path,
  5323. timeout=ftp_timeout,
  5324. socket_timeout=ftp_timeout,
  5325. printer_model=printer.model,
  5326. )
  5327. except Exception as e:
  5328. logger.debug("Failed to download %s: %s", remote_full_path, e)
  5329. continue
  5330. if downloaded:
  5331. downloaded_filename = fname
  5332. logger.info("Found and downloaded: %s", remote_full_path)
  5333. cache_3mf_download(printer_id, fname, temp_path)
  5334. break
  5335. # The listing named the file, so it is on the card;
  5336. # only the transfer failed (#3063).
  5337. ftp_transfer_failed = True
  5338. walk_transfer_failed = True
  5339. # A "Print again" on the printer's screen names no file Bambuddy can
  5340. # find: only its history copy under a generic name, and the 3MF's
  5341. # internal title (#3307). When an earlier run of the same job was
  5342. # archived, its 3MF is the one being printed again. Not when the
  5343. # directory walk listed a file for this print and only its transfer
  5344. # failed: that file is on the card, and the retry fetches it. A
  5345. # cool-off or a failed sweep path is no such evidence -- the retry
  5346. # tries the same names, which this print's file never had.
  5347. reused_3mf_from: int | None = None
  5348. if not downloaded_filename and not walk_transfer_failed:
  5349. reported_layers = raw_mqtt.get("total_layer_num")
  5350. earlier = await _archived_3mf_for_repeat(
  5351. db,
  5352. printer_id,
  5353. subtask_name,
  5354. filename,
  5355. reported_layers if isinstance(reported_layers, int) and reported_layers > 0 else None,
  5356. )
  5357. if earlier is not None:
  5358. reuse_name = Path(earlier.filename or "").name or f"archive_{earlier.id}.3mf"
  5359. # Per printer: two printers reprinting the same job at once
  5360. # must not write one temp file (archive_print names the
  5361. # archive after original_filename, not this path).
  5362. reuse_path = app_settings.archive_dir / "temp" / f"reprint_{printer_id}_{reuse_name}"
  5363. try:
  5364. reuse_path.parent.mkdir(parents=True, exist_ok=True)
  5365. await asyncio.to_thread(shutil.copyfile, app_settings.base_dir / earlier.file_path, reuse_path)
  5366. except OSError as e:
  5367. # A copy that fails leaves the print the fallback archive
  5368. # it would have had, not no archive at all.
  5369. logger.warning("Could not copy the 3MF of archive %s for printer %s: %s", earlier.id, printer_id, e)
  5370. else:
  5371. temp_path = reuse_path
  5372. downloaded_filename = reuse_name
  5373. reused_3mf_from = earlier.id
  5374. cache_3mf_download(printer_id, reuse_name, temp_path)
  5375. logger.info(
  5376. "No 3MF on printer %s for %s (%s); using the 3MF of archive %s, an earlier run of the same job",
  5377. printer_id,
  5378. subtask_name,
  5379. filename,
  5380. earlier.id,
  5381. )
  5382. # Validate the downloaded 3MF actually matches the plate that's running
  5383. # (#1204): subtask_name lags across consecutive plates of the same model,
  5384. # so the first FTP candidate (built from subtask_name) can land on the
  5385. # previous plate's still-resident upload. Cross-check the slice_info
  5386. # plate index against the plate parsed from gcode_file (always fresh —
  5387. # it's the field whose change triggered this callback).
  5388. if downloaded_filename and temp_path:
  5389. expected_plate = parse_plate_id(filename)
  5390. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  5391. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  5392. logger.warning(
  5393. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  5394. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  5395. downloaded_filename,
  5396. actual_plate,
  5397. expected_plate,
  5398. subtask_name,
  5399. )
  5400. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  5401. retry_succeeded = False
  5402. if corrected_subtask and corrected_subtask != subtask_name:
  5403. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  5404. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  5405. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  5406. for remote_path in (
  5407. f"/{try_filename}",
  5408. f"/cache/{try_filename}",
  5409. f"/model/{try_filename}",
  5410. f"/data/{try_filename}",
  5411. f"/data/Metadata/{try_filename}",
  5412. ):
  5413. try:
  5414. if ftp_retry_enabled:
  5415. downloaded = await with_ftp_retry(
  5416. download_file_async,
  5417. printer.ip_address,
  5418. printer.access_code,
  5419. remote_path,
  5420. retry_temp_path,
  5421. timeout=ftp_timeout,
  5422. socket_timeout=ftp_timeout,
  5423. printer_model=printer.model,
  5424. max_retries=ftp_retry_count,
  5425. retry_delay=ftp_retry_delay,
  5426. operation_name=f"Re-download 3MF from {remote_path}",
  5427. cooloff_ip=printer.ip_address,
  5428. non_retry_exceptions=(FileNotOnPrinterError,),
  5429. )
  5430. else:
  5431. downloaded = await download_file_async(
  5432. printer.ip_address,
  5433. printer.access_code,
  5434. remote_path,
  5435. retry_temp_path,
  5436. timeout=ftp_timeout,
  5437. socket_timeout=ftp_timeout,
  5438. printer_model=printer.model,
  5439. )
  5440. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  5441. logger.info(
  5442. "[CALLBACK] Re-download succeeded with corrected name %s "
  5443. "(plate %s) — replacing wrong file",
  5444. try_filename,
  5445. expected_plate,
  5446. )
  5447. try:
  5448. temp_path.unlink(missing_ok=True)
  5449. except OSError:
  5450. pass
  5451. temp_path = retry_temp_path
  5452. downloaded_filename = try_filename
  5453. subtask_name = corrected_subtask
  5454. cache_3mf_download(printer_id, try_filename, temp_path)
  5455. retry_succeeded = True
  5456. break
  5457. elif downloaded:
  5458. # Wrong plate again — discard and keep trying
  5459. try:
  5460. retry_temp_path.unlink(missing_ok=True)
  5461. except OSError:
  5462. pass
  5463. except FileNotOnPrinterError:
  5464. continue
  5465. except Exception as e:
  5466. logger.debug("Re-download failed for %s: %s", remote_path, e)
  5467. if retry_succeeded:
  5468. break
  5469. # If the retry didn't find a matching file, drop the wrong 3MF
  5470. # so the no-3MF fallback below creates an archive whose name
  5471. # at least reflects the right plate.
  5472. if not retry_succeeded:
  5473. logger.warning(
  5474. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  5475. expected_plate,
  5476. )
  5477. try:
  5478. temp_path.unlink(missing_ok=True)
  5479. except OSError:
  5480. pass
  5481. temp_path = None
  5482. downloaded_filename = None
  5483. # Whatever the sweep's transport did earlier, it is not why
  5484. # this archive ends up empty: a 3MF downloaded fine, it was
  5485. # just the wrong plate. Retrying would re-fetch that same
  5486. # contradicted file under the same stale names and hand it
  5487. # to _recover_fallback_archive, which checks that a
  5488. # candidate is a readable 3MF but not which plate it is --
  5489. # so the row would be filled in with another plate's
  5490. # filament and cost, the exact swap #2957 removed (#3063).
  5491. ftp_transfer_failed = False
  5492. # Disown the name for *lookups*: it has just been shown to
  5493. # fetch another plate's 3MF, and it keys `_active_prints`
  5494. # below, where the cover endpoint's own download of that
  5495. # same name would find this archive and fill it in with the
  5496. # file we are discarding here.
  5497. #
  5498. # Keep it for the *title*, which is a separate question.
  5499. # ``swap_plate_suffix`` returns None both for a name that
  5500. # carries no "- Plate N" / "_plate_N" suffix and for no
  5501. # name at all, and those are not the same situation: a name
  5502. # without a suffix holds no stale plate number to be wrong
  5503. # about. Blanking both uses at once dropped the project
  5504. # name too, and the row fell through to the gcode_file path
  5505. # titled "plate_1" though the real name was in hand.
  5506. # #1204's own premise is consecutive plates *of the same
  5507. # model*, so the project part is right either way (#3126).
  5508. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  5509. subtask_name = corrected_subtask or ""
  5510. # Deleted while the 3MF was being fetched (that can take minutes): no
  5511. # archive, timelapse or tracking for a printer that will never report
  5512. # the print's end. forget_printer again: the download registered its
  5513. # 3MF cache entry after the delete cleared the id. (A delete committing
  5514. # while the archive is written is caught after its commit.)
  5515. if await _printer_gone(db, printer_id):
  5516. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  5517. await forget_printer(printer_id)
  5518. return
  5519. if not downloaded_filename or not temp_path:
  5520. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  5521. # Create a fallback archive without 3MF data so the print is still tracked
  5522. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  5523. try:
  5524. from backend.app.models.archive import PrintArchive
  5525. # Why the card is empty. The two temporary causes outrank the
  5526. # storage verdict because they say the sweep never got a fair
  5527. # answer: a cool-off skipped it at the transport, and a failed
  5528. # transfer reached the printer but never finished. Either way
  5529. # the file is still on the card, so reporting where the printer
  5530. # files its jobs would describe a setting that is not the
  5531. # problem (#2957, #3063).
  5532. if blocked_by_ftps_cooloff:
  5533. no_3mf_reason = REASON_FTPS_COOLOFF
  5534. elif storage.reachable and ftp_transfer_failed:
  5535. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5536. else:
  5537. no_3mf_reason = storage.reason
  5538. # Derive print name from subtask_name or filename. The
  5539. # plate guard's disowned name comes second: it is a real name
  5540. # for a real print, and only the gcode_file path is left
  5541. # otherwise -- which titles the row "plate_1" (#3126).
  5542. print_name = subtask_name or display_name_after_plate_reject or filename
  5543. if print_name:
  5544. # Clean up the name (remove extensions, path parts)
  5545. print_name = print_name.split("/")[-1]
  5546. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5547. else:
  5548. print_name = "Unknown Print"
  5549. # Recover estimated print time from MQTT (best-effort for notifications)
  5550. fallback_print_time = None
  5551. mqtt_remaining = data.get("remaining_time")
  5552. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5553. fallback_print_time = int(mqtt_remaining)
  5554. if fallback_print_time is None:
  5555. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5556. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5557. fallback_print_time = int(mc_remaining * 60)
  5558. # Best-effort filament metadata from MQTT — see
  5559. # _extract_filament_data_from_mqtt. Without this the fallback
  5560. # archive's filament fields stayed NULL even though the AMS
  5561. # state at print start was sitting right there in `data`.
  5562. # The slicer's ams_mapping (when present) narrows the result
  5563. # to slots actually used by the print (#1533).
  5564. mqtt_filament_meta = _extract_filament_data_from_mqtt(
  5565. data, _get_start_ams_mapping(data, printer_id, None)
  5566. )
  5567. # Create minimal archive entry
  5568. fallback_archive = PrintArchive(
  5569. printer_id=printer_id,
  5570. filename=filename or f"{print_name}.3mf",
  5571. file_path="", # Empty - no 3MF file available
  5572. file_size=0,
  5573. print_name=print_name,
  5574. print_time_seconds=fallback_print_time,
  5575. status="printing",
  5576. started_at=detected_at,
  5577. subtask_id=subtask_id,
  5578. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5579. filament_type=mqtt_filament_meta.get("filament_type"),
  5580. filament_color=mqtt_filament_meta.get("filament_color"),
  5581. extra_data={
  5582. "no_3mf_available": True,
  5583. # Why the card is empty, when we know -- see above. The
  5584. # banner reads this to stop telling H2/P2 owners to
  5585. # switch on a setting that is already on and would not
  5586. # have helped (#2780).
  5587. "no_3mf_reason": no_3mf_reason,
  5588. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5589. "_print_data": data,
  5590. },
  5591. )
  5592. db.add(fallback_archive)
  5593. try:
  5594. await db.commit()
  5595. except IntegrityError:
  5596. # Not "Failed to create fallback archive" below, and no
  5597. # start notification for a printer that is gone.
  5598. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5599. return
  5600. raise
  5601. await db.refresh(fallback_archive)
  5602. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5603. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5604. return
  5605. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5606. # Track as active print
  5607. _bind_active_print(printer_id, fallback_archive.id, fallback_archive.filename, filename, subtask_name)
  5608. await _open_run_for(fallback_archive.id, printer_id, subtask_id)
  5609. # Record starting energy if smart plug available (#941: persisted column)
  5610. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5611. # Send WebSocket notification
  5612. await ws_manager.send_archive_created(
  5613. {
  5614. "id": fallback_archive.id,
  5615. "printer_id": fallback_archive.printer_id,
  5616. "filename": fallback_archive.filename,
  5617. "print_name": fallback_archive.print_name,
  5618. "status": fallback_archive.status,
  5619. }
  5620. )
  5621. # MQTT relay - publish archive created
  5622. try:
  5623. await mqtt_relay.on_archive_created(
  5624. archive_id=fallback_archive.id,
  5625. print_name=fallback_archive.print_name,
  5626. printer_name=printer.name,
  5627. status=fallback_archive.status,
  5628. )
  5629. except Exception:
  5630. pass # Don't fail if MQTT fails
  5631. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5632. try:
  5633. await _store_spoolman_print_data(
  5634. printer_id,
  5635. fallback_archive.id,
  5636. fallback_archive.file_path,
  5637. db,
  5638. printer_manager,
  5639. ams_mapping=_get_start_ams_mapping(data, printer_id, fallback_archive.id),
  5640. plate_id=_get_start_plate_id(printer_id, fallback_archive.id),
  5641. )
  5642. except Exception as e:
  5643. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5644. # Both temporary give-ups are worth coming back for, and for
  5645. # the same reason: the file is on the printer and the last look
  5646. # failed at the transport rather than finding nothing. One waits
  5647. # out the handshake block (#2957), the other waits for the
  5648. # printer to stop being busy (#3063). Deliberately not scheduled
  5649. # for a storage verdict: a file on internal eMMC will not appear
  5650. # at any FTPS path however long we wait, and retrying it is
  5651. # exactly the sweep #2780 removed.
  5652. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5653. # `possible_names`, not the raw MQTT strings: it is the exact
  5654. # list this flow just tried, already stripped of any path
  5655. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5656. # some firmware) and deduped.
  5657. _schedule_fallback_3mf_retry(
  5658. printer_id=printer_id,
  5659. archive_id=fallback_archive.id,
  5660. filenames=list(possible_names),
  5661. reason=no_3mf_reason,
  5662. )
  5663. # Send notification without archive data (file not found)
  5664. if not notification_sent:
  5665. await _send_print_start_notification(printer_id, data, logger=logger)
  5666. # The same baseline the other two on_print_start branches take
  5667. # (#2704), and last for the same reason they are: it lists the
  5668. # printer's timelapse directory, so a slow card must not delay
  5669. # the _active_prints registration, the energy reading, the
  5670. # archive-created event or the start notification above it.
  5671. #
  5672. # This branch never took one, so every no-3MF archive reached
  5673. # completion with no baseline in memory and none on the row, and
  5674. # the completion scan fell into its "snapshot now" fallback --
  5675. # which runs after the printer has written the video, so the new
  5676. # file landed inside the baseline and no diff ever matched
  5677. # (#2957 follow-up).
  5678. #
  5679. # Skipped when the FTPS cool-off is what produced this fallback:
  5680. # the listing needs the same connection that just failed, so it
  5681. # could only record that the card was unreadable. The scan
  5682. # handles that case by refusing to choose between candidates.
  5683. if not blocked_by_ftps_cooloff:
  5684. await _capture_timelapse_baseline_at_start(
  5685. printer, printer_id, logger, archive_id=fallback_archive.id
  5686. )
  5687. await _forget_if_printer_gone(printer_id)
  5688. return
  5689. except Exception as e:
  5690. logger.error("Failed to create fallback archive: %s", e)
  5691. # Send notification without archive data (file not found)
  5692. if not notification_sent:
  5693. await _send_print_start_notification(printer_id, data, logger=logger)
  5694. return
  5695. try:
  5696. # Archive the file with status "printing"
  5697. service = ArchiveService(db)
  5698. try:
  5699. archive = await service.archive_print(
  5700. printer_id=printer_id,
  5701. source_file=temp_path,
  5702. print_data={
  5703. **data,
  5704. "status": "printing",
  5705. # Where the 3MF came from when the printer had none to
  5706. # give (#3307), for whoever reads this archive later.
  5707. **({"_3mf_from_archive": reused_3mf_from} if reused_3mf_from is not None else {}),
  5708. },
  5709. subtask_id=subtask_id,
  5710. started_at=detected_at,
  5711. # The reused copy's temp name carries the printer id; a
  5712. # download's is the file's own name, as before.
  5713. original_filename=downloaded_filename if reused_3mf_from is not None else None,
  5714. )
  5715. except IntegrityError:
  5716. # archive_print removed the folder it had copied the 3MF into.
  5717. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5718. return
  5719. raise
  5720. if archive:
  5721. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5722. # Set on the row rather than passed to archive_print, which also
  5723. # serves the queue dispatcher — there the queue item decides.
  5724. # Guarded because this branch has no ``except``: an unhandled
  5725. # write error would take the _active_prints registration, the
  5726. # start notification, the energy reading and the timelapse
  5727. # baseline below it with it, and a missing prompt is by far the
  5728. # cheaper failure.
  5729. archive_id = archive.id
  5730. try:
  5731. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5732. archive.confirm_requested = True
  5733. await db.commit()
  5734. except Exception as e:
  5735. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5736. # The rollback expires every loaded object, and on an async
  5737. # session reading one afterwards raises instead of
  5738. # reloading, so the two this branch goes on to use are
  5739. # fetched again. The archive itself was committed by
  5740. # archive_print; only the flag is lost.
  5741. try:
  5742. await db.rollback()
  5743. archive = await db.get(PrintArchive, archive_id)
  5744. printer = await db.get(Printer, printer_id)
  5745. except Exception as reload_error:
  5746. logger.warning(
  5747. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5748. )
  5749. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5750. return
  5751. # Track this active print (use both original filename and downloaded filename)
  5752. _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
  5753. await _open_run_for(archive_id, printer_id, subtask_id)
  5754. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5755. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5756. # Record starting energy from smart plug if available (#941: persisted column)
  5757. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5758. await ws_manager.send_archive_created(
  5759. {
  5760. "id": archive.id,
  5761. "printer_id": archive.printer_id,
  5762. "filename": archive.filename,
  5763. "print_name": archive.print_name,
  5764. "status": archive.status,
  5765. }
  5766. )
  5767. # MQTT relay - publish archive created
  5768. try:
  5769. await mqtt_relay.on_archive_created(
  5770. archive_id=archive.id,
  5771. print_name=archive.print_name,
  5772. printer_name=printer.name,
  5773. status=archive.status,
  5774. )
  5775. except Exception:
  5776. pass # Don't fail if MQTT fails
  5777. # Send notification with archive data (new archive created)
  5778. if not notification_sent:
  5779. archive_data = {
  5780. "print_time_seconds": archive.print_time_seconds,
  5781. "created_by_id": archive.created_by_id,
  5782. }
  5783. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5784. # Extract printable objects for skip object functionality
  5785. try:
  5786. from backend.app.services.archive import extract_printable_objects_from_3mf
  5787. client = printer_manager.get_client(printer_id)
  5788. if client:
  5789. with open(temp_path, "rb") as f:
  5790. threemf_data = f.read()
  5791. # Extract with positions for UI overlay, scoped to the
  5792. # plate that is printing — an all-plates 3MF carries
  5793. # every plate's objects (#2522).
  5794. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5795. threemf_data,
  5796. plate_number=resolve_plate_id(client.state),
  5797. include_positions=True,
  5798. )
  5799. if printable_objects:
  5800. # Store objects in printer state
  5801. client.state.printable_objects = printable_objects
  5802. client.state.printable_objects_bbox_all = bbox_all
  5803. client.state.skipped_objects = [] # Reset skipped objects for new print
  5804. logger.info(
  5805. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5806. )
  5807. except Exception as e:
  5808. logger.debug("Failed to extract printable objects: %s", e)
  5809. # From the archived copy: the downloaded one may be removed
  5810. # below while the pauses are still being read.
  5811. if archive is not None and archive.file_path:
  5812. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  5813. # Store Spoolman tracking data for per-filament usage reporting
  5814. try:
  5815. await _store_spoolman_print_data(
  5816. printer_id,
  5817. archive.id,
  5818. archive.file_path,
  5819. db,
  5820. printer_manager,
  5821. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5822. plate_id=_get_start_plate_id(printer_id, archive_id),
  5823. )
  5824. except Exception as e:
  5825. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5826. # Price the print from its spools now rather than only at completion (#3261)
  5827. _schedule_archive_cost_estimate(
  5828. printer_id,
  5829. archive.id,
  5830. printer_manager,
  5831. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5832. plate_id=_get_start_plate_id(printer_id, archive_id),
  5833. session_factory=async_session,
  5834. )
  5835. # Capture timelapse file baseline for snapshot-diff on completion
  5836. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5837. await _forget_if_printer_gone(printer_id)
  5838. finally:
  5839. # Keep temp_path around until print completes so the cover endpoint
  5840. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5841. # the file. If the cache entry was evicted early (file vanished),
  5842. # clean up any stragglers here to avoid leaking disk on retries.
  5843. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5844. if temp_path and temp_path.exists() and cached_now != temp_path:
  5845. temp_path.unlink()
  5846. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5847. _TIMELAPSE_DIRECTORIES = ("/timelapse", "/timelapse/video", "/record", "/recording")
  5848. # A baseline that could not be read at print start is read again on this
  5849. # schedule while the print runs (#3412). The printer writes the video only once
  5850. # the print has ended, so a reading taken mid-print is as good as one taken at
  5851. # the start. The interval is shorter than the FTPS handshake cool-off (300 s),
  5852. # which is what usually makes the card unreadable, so the first reading after
  5853. # it ends is not long behind; while the cool-off runs a round costs nothing, as
  5854. # no connection is opened. The cap bounds a print that never reports an end.
  5855. _TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS = 120.0
  5856. _TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS = 720
  5857. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5858. # tests can shrink them without waiting out real delays.
  5859. #
  5860. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  5861. # looking. Across 247 support bundles the attempt that found the video was #1
  5862. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  5863. # decaying one, which is the signature of a budget that expires while files are
  5864. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  5865. # prints make big videos and the printer writes them after the print ends, so
  5866. # the poll now runs for minutes and costs one FTP LIST per round.
  5867. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  5868. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  5869. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  5870. def _timelapse_scan_max_attempts() -> int:
  5871. """Round cap for the poll, derived from the wall-clock budget.
  5872. The deadline alone is not a sufficient bound: it assumes each round really
  5873. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5874. and an FTP list that fails immediately would otherwise spin against the
  5875. printer at full speed for the whole window. Whichever bound is reached
  5876. first ends the poll.
  5877. """
  5878. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5879. # A zero interval makes the wall-clock budget meaningless; fall back to
  5880. # the round count the production interval would have given.
  5881. return 32
  5882. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5883. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  5884. """Video filenames already attached to some other archive of this printer.
  5885. Used to disambiguate when more than one file is new since the baseline —
  5886. which happens when a previous print's video landed after this print's
  5887. baseline was taken. Ordering the candidates would be the obvious fix and is
  5888. the wrong one: it can only be done on mtime or on the filename timestamp,
  5889. both of which come from the printer's own clock, and a LAN-only printer
  5890. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  5891. ``attach_timelapse`` saves the video into the archive directory under the
  5892. printer's original filename, and the later MP4 conversion keeps the stem,
  5893. so the stem of ``timelapse_path`` recovers what was claimed.
  5894. """
  5895. from backend.app.models.archive import PrintArchive
  5896. rows = await db.execute(
  5897. select(PrintArchive.timelapse_path).where(
  5898. PrintArchive.printer_id == printer_id,
  5899. PrintArchive.id != exclude_archive_id,
  5900. PrintArchive.timelapse_path.is_not(None),
  5901. )
  5902. )
  5903. return {Path(p).stem for p in rows.scalars().all() if p}
  5904. async def _read_timelapse_baseline(printer) -> tuple[set[str], bool]:
  5905. """The video names on *printer*'s card, and whether the card was read.
  5906. ``_list_timelapse_videos`` answers ``[]`` when its connect fails rather
  5907. than raising, so a card behind the FTPS handshake cool-off, or one whose
  5908. listing timed out, is indistinguishable from one holding no videos.
  5909. Everywhere that only wants to know "is there a video yet" the difference
  5910. does not matter -- both mean "not yet, retry".
  5911. It matters where an empty listing is recorded as a *baseline*. Recording
  5912. "the card held nothing" for a card that was never read means every video on
  5913. it counts as new, and the completion scan then attaches a stale video to
  5914. this print and deletes it from the printer (#2957 follow-up, #3412). So an
  5915. empty listing is asked again here in a way that tells the two apart: the
  5916. card counts as read only when every directory walked answered, with a
  5917. listing or with "no such directory". One that failed may be the one
  5918. holding the videos.
  5919. """
  5920. from backend.app.services.bambu_ftp import ftps_handshake_blocked, list_files_result_async
  5921. files, _ = await _list_timelapse_videos(printer)
  5922. if files:
  5923. return {f.get("name", "") for f in files}, True
  5924. ip_address = getattr(printer, "ip_address", None)
  5925. printer_id = getattr(printer, "id", None)
  5926. if not ip_address:
  5927. return set(), True
  5928. # No card in the slot: nothing to read, and nothing a video could land on.
  5929. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5930. return set(), True
  5931. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  5932. if ftps_handshake_blocked(ip_address):
  5933. # Below any path: every remaining one would fail the same way.
  5934. return set(), False
  5935. listing = await list_files_result_async(
  5936. ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5937. )
  5938. if not (listing.available or listing.missing):
  5939. return set(), False
  5940. videos = [
  5941. f
  5942. for f in listing.files
  5943. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5944. ]
  5945. if videos:
  5946. return {f.get("name", "") for f in videos}, True
  5947. return set(), True
  5948. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5949. """List video files from printer's timelapse directory.
  5950. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5951. Returns (video_files, found_path) where video_files is a list of file dicts
  5952. and found_path is the directory where they were found, or ([], None).
  5953. An empty return does not distinguish "no videos" from "could not read the
  5954. card" — see :func:`_read_timelapse_baseline`, which the two baseline
  5955. callers use instead.
  5956. """
  5957. from backend.app.services.bambu_ftp import list_files_async
  5958. logger = logging.getLogger(__name__)
  5959. # No card in the slot means no /timelapse to walk — four connections that
  5960. # can only fail, on a path whose failures are swallowed and so would go on
  5961. # costing time silently forever (#2780).
  5962. #
  5963. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5964. # inside the loop's own try/except, so a caller that passed something
  5965. # unexpected used to get an empty listing rather than an exception. Keep
  5966. # that, instead of making this gate the first thing that can raise here.
  5967. printer_id = getattr(printer, "id", None)
  5968. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5969. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5970. return [], None
  5971. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  5972. try:
  5973. found_files = await list_files_async(
  5974. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5975. )
  5976. if found_files:
  5977. video_files = [
  5978. f
  5979. for f in found_files
  5980. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5981. ]
  5982. if video_files:
  5983. return video_files, timelapse_path
  5984. except Exception as e:
  5985. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5986. continue
  5987. return [], None
  5988. async def _capture_timelapse_baseline_at_start(
  5989. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5990. ) -> None:
  5991. """Snapshot the printer's timelapse directory at print start so the
  5992. completion-time scan can pick the new file by set-difference.
  5993. Must be called from every on_print_start path that proceeds to a real
  5994. print — both the new-archive branch and the expected-archive branch (which
  5995. queue / VP-dispatched prints take). Without a baseline,
  5996. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5997. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5998. so the new file ends up in the "baseline" set and no diff ever matches.
  5999. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  6000. unreliable — the snapshot-diff approach sidesteps that entirely.
  6001. When ``archive_id`` is known the baseline is also written to the archive
  6002. row, so it survives a restart and the manual "Scan for Timelapse" button
  6003. can run the same diff instead of falling back to clock-based matching
  6004. (#2704). Only baselines taken at print start are persisted — one taken at
  6005. completion already contains the new video and would poison a later scan.
  6006. """
  6007. names: set[str] | None = None
  6008. unread = False
  6009. _timelapse_baselines_unread.discard(printer_id)
  6010. try:
  6011. names, read = await _read_timelapse_baseline(printer)
  6012. unread = not read
  6013. _timelapse_baselines[printer_id] = names
  6014. if unread:
  6015. # Recorded anyway, deliberately, and marked. An empty baseline taken
  6016. # off a card we could not read is not evidence, but it is still the
  6017. # right *default*: Bambuddy deletes each video from the printer once
  6018. # it is attached, so the usual card holds exactly one video at
  6019. # completion and an empty baseline resolves it. Persisting NULL
  6020. # instead would send completion to take its own snapshot, by which
  6021. # point this print's video is on the card and would be swallowed by
  6022. # it. The mark keeps the scan from choosing between several videos
  6023. # (#3412), and the card is read again while the print runs.
  6024. _timelapse_baselines_unread.add(printer_id)
  6025. logger.warning(
  6026. "[TIMELAPSE] Baseline for printer %s taken while its card could not be read — "
  6027. "treating it as empty for now and reading it again during the print",
  6028. printer_id,
  6029. )
  6030. logger.info(
  6031. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  6032. len(names),
  6033. printer_id,
  6034. )
  6035. except Exception as e:
  6036. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  6037. run_started_at: datetime | None = None
  6038. if archive_id is not None:
  6039. try:
  6040. async with async_session() as db:
  6041. from backend.app.models.archive import PrintArchive
  6042. archive = await db.get(PrintArchive, archive_id)
  6043. if archive is not None:
  6044. # Written even when the listing failed, and then as NULL. A
  6045. # reprint reuses the archive row, so leaving the previous
  6046. # run's baseline in place would have the scan diff this print
  6047. # against the state of the printer before the *last* one —
  6048. # and a stale baseline reads as authoritative, where NULL
  6049. # correctly falls back to a fresh snapshot.
  6050. archive.timelapse_baseline = sorted(names) if names is not None else None
  6051. archive.timelapse_baseline_unread = unread
  6052. run_started_at = archive.started_at
  6053. await db.commit()
  6054. except Exception as e:
  6055. # In-memory baseline still covers the normal completion path.
  6056. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  6057. if unread and names is not None:
  6058. spawn_background_task(
  6059. _reread_unread_timelapse_baseline(printer_id, names, archive_id, run_started_at),
  6060. name=f"reread-timelapse-baseline-{printer_id}",
  6061. )
  6062. # Before the print has ended there is no video yet: a long PREPARE (heating,
  6063. # levelling) counts as much as the print itself.
  6064. _BASELINE_REREAD_STATES = _ACTIVE_PRINT_STATES | {"PREPARE", "SLICING"}
  6065. def _schedule_timelapse_scan(archive_id: int, printer_id: int, *, plate_id: int | None) -> None:
  6066. """Start the completion scan with the print-start baseline: the names, and
  6067. whether they were taken off a card that could not be read. Taking them
  6068. ends any re-read still running for it."""
  6069. unread = printer_id in _timelapse_baselines_unread
  6070. _timelapse_baselines_unread.discard(printer_id)
  6071. baseline = _timelapse_baselines.pop(printer_id, None)
  6072. spawn_background_task(
  6073. _mark_run_finishing(
  6074. archive_id,
  6075. _scan_for_timelapse_with_retries(archive_id, baseline, plate_id=plate_id, baseline_unread=unread),
  6076. ),
  6077. name=f"scan-timelapse-{archive_id}",
  6078. )
  6079. def _unread_baseline_round(printer_id: int, names: set[str]) -> bool | None:
  6080. """Whether to read an unread baseline again now: True to read, None to
  6081. skip this round, False once it is over -- the print it was taken for is
  6082. no longer the one on the printer, has stopped printing, or the baseline
  6083. has been read.
  6084. ``names`` is the very set object recorded at print start: completion pops
  6085. it and the next print records a new one, so identity marks the run. A
  6086. printer that is momentarily disconnected says nothing about its print, so
  6087. that only skips the round.
  6088. """
  6089. if _timelapse_baselines.get(printer_id) is not names or printer_id not in _timelapse_baselines_unread:
  6090. return False
  6091. state = printer_manager.get_status(printer_id)
  6092. if state is None or not state.connected:
  6093. return None
  6094. return state.state in _BASELINE_REREAD_STATES
  6095. async def _reread_unread_timelapse_baseline(
  6096. printer_id: int, names: set[str], archive_id: int | None, run_started_at: datetime | None
  6097. ) -> None:
  6098. """Read again a print-start baseline the card could not give (#3412).
  6099. The printer writes the video only once the print has ended, so the card
  6100. read at any point during the print holds exactly what it held at the
  6101. start. Each round stops once the print is no longer the one the baseline
  6102. was taken for or has stopped printing, and checks that again after the
  6103. listing returns, before anything is recorded.
  6104. """
  6105. from backend.app.models.archive import PrintArchive
  6106. from backend.app.models.printer import Printer
  6107. logger = logging.getLogger(__name__)
  6108. for _ in range(_TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS):
  6109. await asyncio.sleep(_TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS)
  6110. now = _unread_baseline_round(printer_id, names)
  6111. if now is False:
  6112. return
  6113. if now is None:
  6114. continue
  6115. try:
  6116. async with async_session() as db:
  6117. printer = await db.get(Printer, printer_id)
  6118. if printer is None:
  6119. return
  6120. fresh, read = await _read_timelapse_baseline(printer)
  6121. except Exception as e:
  6122. logger.debug("[TIMELAPSE] Re-reading the baseline for printer %s failed: %s", printer_id, e)
  6123. continue
  6124. if not read:
  6125. continue
  6126. now = _unread_baseline_round(printer_id, names)
  6127. if now is False:
  6128. return
  6129. if now is None:
  6130. # The printer dropped off while the listing was out, so nothing
  6131. # says it did not end meanwhile: keep the reading for a round that
  6132. # can vouch for it.
  6133. continue
  6134. names.update(fresh)
  6135. _timelapse_baselines_unread.discard(printer_id)
  6136. logger.info(
  6137. "[TIMELAPSE] Baseline for printer %s read during the print: %s video files",
  6138. printer_id,
  6139. len(fresh),
  6140. )
  6141. if archive_id is None:
  6142. return
  6143. try:
  6144. async with async_session() as db:
  6145. archive = await db.get(PrintArchive, archive_id)
  6146. # Only the run it was taken for: by now the row can belong to a
  6147. # reprint, whose baseline is its own.
  6148. if archive is not None and archive.started_at == run_started_at and archive.timelapse_baseline_unread:
  6149. archive.timelapse_baseline = sorted(names)
  6150. archive.timelapse_baseline_unread = False
  6151. await db.commit()
  6152. except Exception as e:
  6153. # The in-memory baseline is read now, which covers completion
  6154. # unless Bambuddy restarts first.
  6155. logger.warning("[TIMELAPSE] Failed to persist the re-read baseline for archive %s: %s", archive_id, e)
  6156. return
  6157. async def _scan_for_timelapse_with_retries(
  6158. archive_id: int,
  6159. baseline_names: set[str] | None = None,
  6160. *,
  6161. plate_id: int | None = None,
  6162. baseline_unread: bool = False,
  6163. ):
  6164. """Poll the printer for this print's timelapse and attach it.
  6165. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  6166. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  6167. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  6168. (#2704). Comparing the current listing against the set of filenames that
  6169. existed when the print started needs no clock at all, because the printer
  6170. writes the video only once the print has ended.
  6171. Baseline precedence: the caller's in-memory set, then the one persisted on
  6172. the archive at print start, then a snapshot taken now. The last of those is
  6173. a poor substitute — by completion the new video may already be on the card,
  6174. in which case it lands in the "baseline" and no diff can ever match — but it
  6175. is all that is available for a print that began before Bambuddy started.
  6176. On success the video is deleted from the printer, which keeps ``/timelapse``
  6177. down to the unclaimed files and makes the next diff unambiguous.
  6178. ``baseline_unread`` marks the caller's baseline as taken off a card that
  6179. could not be read; a stored one carries the same mark on the archive.
  6180. """
  6181. logger = logging.getLogger(__name__)
  6182. # Cleared when the baseline was taken off a card we could not read, so the
  6183. # attach step refuses to choose between several candidates (#2957, #3412).
  6184. baseline_trusted = True
  6185. # --- Phase 1: establish the baseline -------------------------------------
  6186. try:
  6187. async with async_session() as db:
  6188. from backend.app.models.printer import Printer
  6189. service = ArchiveService(db)
  6190. archive = await service.get_archive(archive_id)
  6191. if not archive:
  6192. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  6193. return
  6194. if archive.timelapse_path:
  6195. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  6196. return
  6197. if not archive.printer_id:
  6198. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  6199. return
  6200. # The run this scan is for. The archive row passes to a newer run
  6201. # when it prints again (the next plate, a reprint), and that run's
  6202. # video is its own.
  6203. run_started_at = archive.started_at
  6204. if (
  6205. baseline_names is not None
  6206. and baseline_unread
  6207. and archive.timelapse_baseline is not None
  6208. and not archive.timelapse_baseline_unread
  6209. ):
  6210. # The card was read at print start, and the in-memory copy is
  6211. # one Bambuddy took after a restart off a card it could not
  6212. # read: the stored one is this run's and is evidence.
  6213. baseline_names = set(archive.timelapse_baseline)
  6214. logger.info(
  6215. "[TIMELAPSE] Using stored baseline over an unread one: %s existing video files for archive %s",
  6216. len(baseline_names),
  6217. archive_id,
  6218. )
  6219. elif baseline_names is not None:
  6220. baseline_trusted = not baseline_unread
  6221. logger.info(
  6222. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  6223. len(baseline_names),
  6224. archive_id,
  6225. )
  6226. elif archive.timelapse_baseline is not None:
  6227. # Persisted at print start — survives a restart mid-print.
  6228. baseline_names = set(archive.timelapse_baseline)
  6229. baseline_trusted = not archive.timelapse_baseline_unread
  6230. logger.info(
  6231. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  6232. len(baseline_names),
  6233. archive_id,
  6234. )
  6235. else:
  6236. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  6237. printer = result.scalar_one_or_none()
  6238. if not printer:
  6239. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  6240. return
  6241. baseline_names, baseline_trusted = await _read_timelapse_baseline(printer)
  6242. if not baseline_trusted:
  6243. # The card is unreadable at the one moment a baseline has to
  6244. # be taken, so the empty listing means "we never looked",
  6245. # not "these are all new". Carry on with it anyway — the
  6246. # usual card holds exactly one video, which resolves
  6247. # correctly — but stop the poll from *choosing* between
  6248. # several, which is how a stale video got attached to this
  6249. # print and then deleted off the printer (#2957 follow-up).
  6250. logger.warning(
  6251. "[TIMELAPSE] Baseline for archive %s taken while printer %s's card could not be "
  6252. "read. A single new video still resolves; several will not be guessed between — "
  6253. "use Scan for Timelapse to pick one by hand",
  6254. archive_id,
  6255. archive.printer_id,
  6256. )
  6257. logger.info(
  6258. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  6259. len(baseline_names),
  6260. archive_id,
  6261. )
  6262. except Exception as e:
  6263. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  6264. return
  6265. # --- Phase 2: poll for a file that was not there when the print began -----
  6266. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  6267. max_attempts = _timelapse_scan_max_attempts()
  6268. seen_names: set[str] = set()
  6269. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  6270. attempt = 0
  6271. while True:
  6272. await asyncio.sleep(delay)
  6273. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  6274. attempt += 1
  6275. try:
  6276. from backend.app.models.printer import Printer
  6277. # Read phase: fetch archive + printer in a short session and release
  6278. # the pooled connection BEFORE the FTP list/download below. Holding it
  6279. # across the FTP round-trips left one connection idle-in-transaction per
  6280. # in-flight scan (issue #2572).
  6281. async with async_session() as db:
  6282. service = ArchiveService(db)
  6283. archive = await service.get_archive(archive_id)
  6284. if not archive:
  6285. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  6286. return
  6287. if archive.timelapse_path:
  6288. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  6289. return
  6290. if archive.started_at != run_started_at:
  6291. logger.info(
  6292. "[TIMELAPSE] Archive %s is printing again, stopping the previous run's poll", archive_id
  6293. )
  6294. return
  6295. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  6296. printer = result.scalar_one_or_none()
  6297. if not printer:
  6298. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  6299. return
  6300. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  6301. # I/O phase (no DB connection held): FTP list + download.
  6302. video_files, found_path = await _list_timelapse_videos(printer)
  6303. # The poll can run for dozens of rounds, so only narrate a round
  6304. # that saw something change. Repeating the whole listing every 30 s
  6305. # would bury the one interesting line in the support bundle.
  6306. names_now = {f.get("name", "") for f in video_files}
  6307. changed = attempt == 1 or names_now != seen_names
  6308. seen_names = names_now
  6309. speak = logger.info if changed else logger.debug
  6310. if video_files:
  6311. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  6312. if changed:
  6313. for f in video_files[:5]:
  6314. logger.info("[TIMELAPSE] - %s", f.get("name"))
  6315. attached = await _attach_first_unclaimed_timelapse(
  6316. archive_id,
  6317. printer,
  6318. video_files,
  6319. baseline_names,
  6320. claimed,
  6321. attempt,
  6322. logger,
  6323. quiet=not changed,
  6324. require_unambiguous=not baseline_trusted,
  6325. plate_id=plate_id,
  6326. run_started_at=run_started_at,
  6327. )
  6328. if attached:
  6329. return
  6330. else:
  6331. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  6332. except Exception as e:
  6333. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  6334. if attempt >= max_attempts or time.monotonic() >= deadline:
  6335. break
  6336. # No name-match fallback: it compared the print name against the filename,
  6337. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  6338. # bundles it fired 159 times and matched zero times, so all it added was a
  6339. # misleading log line before giving up.
  6340. logger.warning(
  6341. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  6342. archive_id,
  6343. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  6344. )
  6345. async def _attach_layer_timelapse(
  6346. archive_id: int, timelapse_path: Path, plate_id: int | None, run_started_at: datetime | None
  6347. ) -> None:
  6348. """Attach the external camera's stitched timelapse to the archive.
  6349. The camera's video is the one the user set up in Bambuddy, so it wins
  6350. over the printer's own when both are on: it replaces the printer's video
  6351. (usually there first; stitching takes minutes) and that file is deleted,
  6352. leaving nothing in the archive folder unreferenced. ``run_started_at`` is
  6353. the run the frames were taken for: when the archive is printing again by
  6354. the time the stitch is done, the video is not the new run's and is
  6355. dropped. The stitched file is a temporary either way.
  6356. """
  6357. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  6358. logger = logging.getLogger(__name__)
  6359. try:
  6360. async with async_session() as db:
  6361. service = ArchiveService(db)
  6362. archive = await service.get_archive(archive_id)
  6363. if archive is None:
  6364. return
  6365. if archive.started_at != run_started_at:
  6366. logger.info(
  6367. "[LAYER-TL] Archive %s is printing again; dropping the previous run's layer timelapse", archive_id
  6368. )
  6369. return
  6370. replaced = archive.timelapse_path
  6371. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  6372. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  6373. if not await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=plate_id):
  6374. return
  6375. attached = archive.timelapse_path
  6376. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  6377. if replaced and replaced != attached:
  6378. try:
  6379. old = safe_join_under(app_settings.base_dir, replaced, http=False)
  6380. except PathTraversalError:
  6381. return
  6382. await asyncio.to_thread(old.unlink, missing_ok=True)
  6383. logger.info("[LAYER-TL] Replaced the printer's timelapse %s on archive %s", replaced, archive_id)
  6384. finally:
  6385. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6386. # ``run_started_at`` not given: attach whichever run the archive is on.
  6387. _ANY_RUN = object()
  6388. async def _attach_first_unclaimed_timelapse(
  6389. archive_id: int,
  6390. printer,
  6391. video_files: list[dict],
  6392. baseline_names: set[str],
  6393. claimed: set[str],
  6394. attempt: int,
  6395. logger: logging.Logger,
  6396. *,
  6397. quiet: bool = False,
  6398. require_unambiguous: bool = False,
  6399. plate_id: int | None = None,
  6400. run_started_at: datetime | None | object = _ANY_RUN,
  6401. ) -> bool:
  6402. """Download and attach the one video that belongs to this print.
  6403. A candidate is any file absent from the print-start baseline. More than one
  6404. can qualify when a previous print's video landed late, after this print's
  6405. baseline was taken — those are filtered out by name, because they are
  6406. already attached to another archive. Sorting the candidates instead would
  6407. mean sorting on mtime or on the filename timestamp, both of which come from
  6408. the printer's unsynced clock.
  6409. Returns True once a video is attached. The printer's copy is deleted only
  6410. after the attach succeeds on bytes whose length matched the listing.
  6411. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  6412. already seen this exact listing — the poll runs for many rounds and only the
  6413. rounds where something changed are worth an INFO line.
  6414. """
  6415. from backend.app.services.bambu_ftp import (
  6416. DownloadDeadlineExceeded,
  6417. delete_archived_timelapse,
  6418. download_file_bytes_async,
  6419. remote_file_settled,
  6420. )
  6421. speak = logger.debug if quiet else logger.info
  6422. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  6423. if not new_files:
  6424. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  6425. return False
  6426. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  6427. if not candidates:
  6428. speak(
  6429. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  6430. attempt,
  6431. len(new_files),
  6432. )
  6433. return False
  6434. if len(candidates) > 1:
  6435. if require_unambiguous:
  6436. # The baseline is not evidence -- it was taken off a card that could
  6437. # not be read -- so "new since the baseline" does not narrow these
  6438. # down at all. Taking the first would attach an arbitrary video to
  6439. # this print and then delete it from the printer.
  6440. logger.warning(
  6441. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  6442. "leaving all of them on the printer for manual selection",
  6443. attempt,
  6444. len(candidates),
  6445. ", ".join(str(f.get("name")) for f in candidates),
  6446. )
  6447. return False
  6448. logger.warning(
  6449. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  6450. "the rest stay on the printer for manual selection",
  6451. attempt,
  6452. len(candidates),
  6453. ", ".join(str(f.get("name")) for f in candidates),
  6454. )
  6455. target = candidates[0]
  6456. file_name = str(target.get("name") or "") # every listed entry has one
  6457. remote_path = target.get("path") or f"/timelapse/{file_name}"
  6458. logger.info(
  6459. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  6460. attempt,
  6461. file_name,
  6462. archive_id,
  6463. )
  6464. # The listing always carries a size (`list_files` skips entries it can't
  6465. # parse), but read it explicitly: the delete below is destructive and must
  6466. # depend on a size we actually had, not on one we hoped was there.
  6467. expected_size = target.get("size")
  6468. try:
  6469. timelapse_data = await download_file_bytes_async(
  6470. printer.ip_address,
  6471. printer.access_code,
  6472. remote_path,
  6473. printer_model=printer.model,
  6474. expected_size=expected_size,
  6475. )
  6476. except DownloadDeadlineExceeded:
  6477. # Too slow for its size this round; the printer keeps its copy.
  6478. timelapse_data = None
  6479. if not timelapse_data:
  6480. # Short or failed transfer. The printer keeps its copy, so the next
  6481. # round can try again — which is exactly why the delete below is
  6482. # gated on a verified download.
  6483. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  6484. return False
  6485. # The length check above proves we got what the listing said, not that the
  6486. # printer had finished writing. A video still being written can be listed
  6487. # short, served short, and pass — so confirm it has stopped growing before
  6488. # committing to it and deleting the original (#2704).
  6489. if not await remote_file_settled(
  6490. printer.ip_address,
  6491. printer.access_code,
  6492. remote_path,
  6493. len(timelapse_data),
  6494. printer_model=printer.model,
  6495. ):
  6496. return False
  6497. # Write phase: attach in a fresh short-lived session. The download took a
  6498. # while: by now the archive may have its video, or be printing again for a
  6499. # newer run, whose video this is not. Then nothing is attached or deleted,
  6500. # and the poll ends (True).
  6501. async with async_session() as db:
  6502. service = ArchiveService(db)
  6503. if run_started_at is not _ANY_RUN:
  6504. current = await service.get_archive(archive_id)
  6505. if current is None or current.timelapse_path or current.started_at != run_started_at:
  6506. logger.info(
  6507. "[TIMELAPSE] Archive %s moved on during the download (video attached or printing again); "
  6508. "%s stays on the printer",
  6509. archive_id,
  6510. file_name,
  6511. )
  6512. return True
  6513. success = await service.attach_timelapse(archive_id, timelapse_data, file_name, plate_id=plate_id)
  6514. if not success:
  6515. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  6516. return False
  6517. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  6518. await delete_archived_timelapse(
  6519. printer.ip_address,
  6520. printer.access_code,
  6521. remote_path,
  6522. verified=expected_size is not None,
  6523. printer_model=printer.model,
  6524. printer_name=printer.name,
  6525. )
  6526. return True
  6527. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  6528. # module-level so tests can monkeypatch them down to ~0 without timing out.
  6529. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  6530. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  6531. # How long the *background* upgrade keeps waiting after the notification has
  6532. # already gone out (#2704 follow-up). The short bound above exists so a slow
  6533. # printer can't hold up the print-complete notification; this one exists so the
  6534. # archive still ends up with the better frame afterwards.
  6535. #
  6536. # Measured across 261 attaches in the support bundles, the video lands a median
  6537. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  6538. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  6539. # was 546s. Every other model was inside 26s. The long budget is therefore
  6540. # almost entirely for P1-series users; on everything else the short wait already
  6541. # wins and this task never runs.
  6542. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  6543. async def _capture_finish_photo_from_timelapse(
  6544. archive_id: int,
  6545. archive_dir: Path,
  6546. timeout: float | None = None,
  6547. rotation: int = 0,
  6548. ) -> tuple[str | None, bool]:
  6549. """Wait for the per-print timelapse to land on the archive and extract its
  6550. last frame as the finish photo (#1397).
  6551. Bambu firmware stops timelapse recording after the toolhead parks but
  6552. before the bed-drop end-gcode runs, so the last frame frames the finished
  6553. print correctly. A live camera grab at gcode_state=FINISH captures the
  6554. bed already lowered.
  6555. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  6556. ``archive.timelapse_path`` when the file lands. This function polls for
  6557. that field.
  6558. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  6559. the wait ran out with no video on the archive yet — i.e. the video may
  6560. still be coming and a later attempt could succeed. It is False when the
  6561. video landed (whether or not extraction worked), because in that case
  6562. waiting longer changes nothing. The caller uses that to decide between
  6563. falling back permanently and scheduling a background upgrade.
  6564. ``rotation`` is the printer's camera_rotation, applied to the extracted
  6565. still (#2708) so this source agrees with every other finish-photo source.
  6566. The archived video itself is the printer's own file and is left alone —
  6567. rotating it would mean re-encoding it.
  6568. """
  6569. import uuid
  6570. from backend.app.models.archive import PrintArchive
  6571. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  6572. logger = logging.getLogger(__name__)
  6573. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  6574. deadline = asyncio.get_event_loop().time() + budget
  6575. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  6576. while True:
  6577. async with async_session() as db:
  6578. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6579. archive = result.scalar_one_or_none()
  6580. timelapse_relpath = archive.timelapse_path if archive else None
  6581. if timelapse_relpath:
  6582. video_path = app_settings.base_dir / timelapse_relpath
  6583. if video_path.exists() and video_path.stat().st_size > 0:
  6584. photos_dir = archive_dir / "photos"
  6585. photos_dir.mkdir(parents=True, exist_ok=True)
  6586. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6587. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6588. output_path = photos_dir / filename
  6589. if await extract_video_last_frame(video_path, output_path):
  6590. await apply_camera_rotation_to_file(output_path, rotation, logger)
  6591. logger.info(
  6592. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  6593. video_path.name,
  6594. archive_id,
  6595. )
  6596. return filename, False
  6597. logger.warning(
  6598. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  6599. video_path.name,
  6600. archive_id,
  6601. )
  6602. return None, False
  6603. if asyncio.get_event_loop().time() >= deadline:
  6604. logger.info(
  6605. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  6606. archive_id,
  6607. budget,
  6608. )
  6609. return None, True
  6610. await asyncio.sleep(poll_interval)
  6611. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  6612. """Add the timelapse's last frame to an archive after the fact (#2704).
  6613. The print-complete notification waits only ~60s for the video, because
  6614. holding a notification for minutes is worse than sending it with a live
  6615. camera grab. On a P1-series printer the video often lands well after that,
  6616. so the archive used to be stuck with the live grab — which is taken at
  6617. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  6618. the worse photo of the two.
  6619. This keeps waiting in the background and, when the video arrives, extracts
  6620. the frame and puts it *first* in the archive's photo list, so opening the
  6621. gallery shows it. The live grab is deliberately kept: the notification that
  6622. already went out links to that exact file, and deleting it would leave a
  6623. broken image in Discord or Telegram.
  6624. """
  6625. logger = logging.getLogger(__name__)
  6626. filename, _ = await _capture_finish_photo_from_timelapse(
  6627. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  6628. )
  6629. if not filename:
  6630. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  6631. return
  6632. try:
  6633. async with async_session() as db:
  6634. from backend.app.models.archive import PrintArchive
  6635. archive = await db.get(PrintArchive, archive_id)
  6636. if archive is None:
  6637. return
  6638. photos = list(archive.photos or [])
  6639. if filename in photos:
  6640. return
  6641. # Front of the list: PhotoGalleryModal opens at index 0.
  6642. archive.photos = [filename, *photos]
  6643. await db.commit()
  6644. except Exception as e:
  6645. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  6646. return
  6647. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  6648. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  6649. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  6650. """Put the filament-attribution context back after a restart mid-print.
  6651. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  6652. both die with the process. The print keeps running, so at completion the
  6653. tracker would fall back to whatever the printer reports *now* — and AMS
  6654. filament backup makes "now" the substitute tray, charging the whole print
  6655. to the spool that only finished it.
  6656. The persisted row is only trusted when its print name still matches what
  6657. the printer says it is running: a row left behind by a completion we never
  6658. saw must not attach itself to the next print.
  6659. """
  6660. try:
  6661. from backend.app.api.routes.settings import get_setting
  6662. from backend.app.services.usage_tracker import (
  6663. clear_persisted_session,
  6664. get_persisted_ams_mapping,
  6665. get_persisted_print_name,
  6666. get_persisted_spool_change_log,
  6667. restore_session,
  6668. )
  6669. persisted_name = await get_persisted_print_name(db, printer_id)
  6670. current_name = (state.subtask_name or "").strip()
  6671. if persisted_name and current_name and persisted_name.strip() != current_name:
  6672. logger.info(
  6673. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  6674. printer_id,
  6675. persisted_name,
  6676. current_name,
  6677. )
  6678. await clear_persisted_session(db, printer_id)
  6679. # Fall through to seeding: the print on the printer is real, it just
  6680. # isn't the one the row described.
  6681. persisted_log = None
  6682. else:
  6683. # Spoolman users get the tray-change log back but no in-memory
  6684. # session — see ``on_print_start`` on why that dict is load-bearing
  6685. # for the remain%-sync guard.
  6686. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6687. persisted_log = await restore_session(
  6688. db,
  6689. printer_id,
  6690. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  6691. )
  6692. # The slot pills (#1762) read the mapping captured from the print
  6693. # command, which dies with the process as well. One this process
  6694. # has captured since is newer.
  6695. if state.print_ams_mapping is None:
  6696. state.print_ams_mapping = await get_persisted_ams_mapping(db, printer_id)
  6697. # Spools swapped on a tray before the restart (#3325); anything this
  6698. # process has recorded since goes after them.
  6699. persisted_swaps = await get_persisted_spool_change_log(db, printer_id)
  6700. if persisted_swaps:
  6701. seen = getattr(state, "spool_change_log", None) or []
  6702. state.spool_change_log = persisted_swaps + [item for item in seen if item not in persisted_swaps]
  6703. if persisted_log:
  6704. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  6705. # Anything this process already observed goes after the persisted
  6706. # history — the log is ordered by layer, and a fresh process can
  6707. # only have seen changes from later in the print.
  6708. for entry in state.tray_change_log or []:
  6709. if tuple(entry) not in restored:
  6710. restored.append(tuple(entry))
  6711. state.tray_change_log = restored
  6712. tray_now = state.tray_now
  6713. if 0 <= tray_now <= 254:
  6714. if not state.tray_change_log:
  6715. # No persisted history — a print that started before this build,
  6716. # or before the row existed. Seed with the tray feeding right
  6717. # now so the remainder of the print is at least attributable to
  6718. # the right spool.
  6719. state.tray_change_log = [(tray_now, state.layer_num)]
  6720. logger.info(
  6721. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  6722. printer_id,
  6723. tray_now,
  6724. state.layer_num,
  6725. )
  6726. # The tray handler updates ``last_loaded_tray`` on every push
  6727. # regardless of whether it logged a change, so re-align it to avoid
  6728. # a duplicate entry on the next push. Only ever with a real tray:
  6729. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  6730. # 255" fallback, and writing 255 into it would defeat that.
  6731. state.last_loaded_tray = tray_now
  6732. except Exception:
  6733. # Never let attribution recovery cost the caller its timelapse
  6734. # baseline — that capture has to happen before the printer uploads
  6735. # the in-flight MP4 and there is no second chance at it.
  6736. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  6737. async def on_print_running_observed(printer_id: int, data: dict):
  6738. """Restart-recovery for a print that started before Bambuddy came up.
  6739. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  6740. after Bambuddy startup (#1304 guard, prevents duplicate archive
  6741. creation). This hook restores the persisted archive into ``_active_prints``
  6742. and captures the timelapse baseline that normally hangs off print start.
  6743. Fires once per session, in lieu of on_print_start when restart-recovery
  6744. kicks in. The printer doesn't upload the timelapse until after PRINT
  6745. COMPLETE, so a baseline captured any time during the print is still
  6746. pre-upload.
  6747. """
  6748. logger = logging.getLogger(__name__)
  6749. async with async_session() as db:
  6750. from backend.app.models.printer import Printer
  6751. state = printer_manager.get_status(printer_id)
  6752. if state is not None:
  6753. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  6754. if authorization is True:
  6755. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  6756. await _restore_usage_tracking_session(printer_id, state, db, logger)
  6757. await _restore_printable_objects(printer_id, state, db, logger)
  6758. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6759. printer = result.scalar_one_or_none()
  6760. if not printer:
  6761. logger.warning(
  6762. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  6763. printer_id,
  6764. )
  6765. return
  6766. # Avoid double-capture: ownership reconciliation above must still run when
  6767. # a baseline already exists, but the camera work itself is one-shot.
  6768. if printer_id in _timelapse_baselines:
  6769. logger.debug(
  6770. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  6771. printer_id,
  6772. )
  6773. return
  6774. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  6775. class _RunOfArchive:
  6776. """An archive as one of its runs printed it: the run's job id, start and
  6777. plate, the rest the archive's. What the reconcile judges and closes."""
  6778. def __init__(self, archive, run):
  6779. self._archive = archive
  6780. self.subtask_id = run.subtask_id
  6781. self.started_at = run.started_at
  6782. self.plate_id = run.plate_id if run.plate_id is not None else archive.plate_id
  6783. def __getattr__(self, name):
  6784. return getattr(self._archive, name)
  6785. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  6786. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  6787. against the printer's current MQTT state.
  6788. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  6789. COMPLETE events, typically a print finishing during an MQTT disconnect
  6790. window followed by a smart-plug power cycle):
  6791. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  6792. provably not running anymore — only branch that should fire under
  6793. normal disconnect-then-reconnect timing.
  6794. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  6795. firmware mints a fresh ``subtask_id`` for each print, including the
  6796. ghost replay it runs after a power cycle from a leftover SD file —
  6797. so a mismatch unambiguously means the in-DB archive is no longer
  6798. the print on the printer.
  6799. 3. Printer is running but ``subtask_name`` is empty. The printer
  6800. doesn't know what it's running; the archive's reference to it is
  6801. already broken.
  6802. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  6803. with matching subtask_id+subtask_name is left alone. The cost of a false
  6804. positive is a print closed while it still runs: the reconcile takes its
  6805. ``_active_prints`` entry and the archive is no longer ``printing``, so
  6806. the real PRINT COMPLETE later finds no archive to close (#1679). The
  6807. cost of a false negative is the ghost-print loop in #1542. What the
  6808. archive is closed as is ``_reconciled_outcome``'s call.
  6809. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  6810. MQTT has connected but the first ``push_status`` response hasn't been
  6811. applied yet — ``PrinterState`` is sitting on its construction defaults.
  6812. The reconcile caller in ``on_printer_status_change`` is already gated
  6813. on a real ``state.state``, so in normal operation this branch is
  6814. unreachable; it's kept as belt-and-braces for future callers and for
  6815. the narrow window where a partial state update could arrive
  6816. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  6817. ``not stale`` on degenerate input is strictly conservative: a real
  6818. stale archive will still be caught by the next push_status arriving
  6819. with terminal state.
  6820. """
  6821. current_state = (state.state or "").upper()
  6822. if current_state in ("", "UNKNOWN"):
  6823. # No real push_status yet — PrinterState defaults are not evidence.
  6824. return False, ""
  6825. if current_state in ("IDLE", "FINISH", "FAILED"):
  6826. return True, f"printer state {current_state}"
  6827. # Below here the printer is in a running / pre-running state (RUNNING /
  6828. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  6829. current_subtask_id = (state.subtask_id or "").strip()
  6830. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  6831. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  6832. current_subtask_name = (state.subtask_name or "").strip()
  6833. if not current_subtask_name:
  6834. return True, "printer subtask_name empty"
  6835. return False, ""
  6836. async def prime_kprofile_table(printer_id: int) -> int:
  6837. """Read the printer's calibration table once per connection.
  6838. The AMS slot card shows a K value per slot (#2854). On the printers whose
  6839. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  6840. report ``cali_idx`` and nothing else -- that number can only come from
  6841. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  6842. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  6843. backup, or the printer answering a query BambuStudio made on the report
  6844. topic we share. A Bambuddy that nobody visited showed a card with no K
  6845. values at all.
  6846. Only the diameters actually fitted are asked for, which is one request on a
  6847. single-nozzle printer and two on a dual. Probing the four sizes blind is
  6848. what the backup does, and it is both wasteful and the thing that used to
  6849. blank the table.
  6850. Returns the number of nozzles whose table was read.
  6851. """
  6852. client = printer_manager.get_client(printer_id)
  6853. state = printer_manager.get_status(printer_id)
  6854. if client is None or state is None or not state.connected:
  6855. return 0
  6856. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  6857. # ask once, and both entries are empty until the first push_status lands.
  6858. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  6859. if not diameters:
  6860. logging.getLogger(__name__).debug(
  6861. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  6862. printer_id,
  6863. )
  6864. return 0
  6865. primed = 0
  6866. for diameter in diameters:
  6867. try:
  6868. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  6869. except Exception as exc: # noqa: BLE001
  6870. # A printer that won't answer costs the card its K values, nothing
  6871. # more — never the connection this runs on the back of.
  6872. logging.getLogger(__name__).warning(
  6873. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  6874. )
  6875. continue
  6876. primed += 1
  6877. logging.getLogger(__name__).info(
  6878. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  6879. )
  6880. return primed
  6881. def _sd_files_in_use(state) -> set[str]:
  6882. """Names of the SD-card files the printer may be printing right now (#3009).
  6883. The post-print cleanup works out what to delete from the finished archive,
  6884. not from the printer. When reconciliation closes an old archive because the
  6885. printer has moved on to a new job, and that job is the same file reprinted
  6886. from the printer's screen, the cleanup would delete the file mid-print.
  6887. Empty unless the printer is busy: on an ordinary completion the state is
  6888. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  6889. name, a path or a URL depending on firmware, and some report only the
  6890. plate's G-code, so the job name is matched as well, in the same spellings
  6891. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  6892. ignores case.
  6893. """
  6894. def _text(value) -> str:
  6895. return value.strip() if isinstance(value, str) else ""
  6896. if state is None:
  6897. return set()
  6898. current_state = _text(getattr(state, "state", None)).upper()
  6899. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  6900. return set()
  6901. in_use: set[str] = set()
  6902. gcode_file = _text(getattr(state, "gcode_file", None))
  6903. if gcode_file:
  6904. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  6905. # both legal in a file name, and raises on some inputs.
  6906. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  6907. if name:
  6908. in_use.add(name.lower())
  6909. subtask_name = _text(getattr(state, "subtask_name", None))
  6910. if subtask_name:
  6911. for name in (subtask_name, subtask_name.replace(" ", "_")):
  6912. for ext in (".3mf", ".gcode"):
  6913. in_use.add(f"{name}{ext}".lower())
  6914. return in_use
  6915. def _reconciled_outcome(archive, state) -> str:
  6916. """What a stale archive is closed as at reconnect (#3310).
  6917. A print that ends while Bambuddy restarts is never seen to end: the new
  6918. MQTT client's first status is already FINISH, which is not a transition.
  6919. The printer keeps reporting the finished job's ``subtask_id`` until the
  6920. next print, so a matching id proves the FINISH or FAILED is this
  6921. archive's. Anything else -- IDLE, another job, an id of "0" (a print
  6922. started outside the cloud) or none -- says only that the print is over,
  6923. not how, and stays ``aborted``.
  6924. """
  6925. current_state = (state.state or "").upper()
  6926. if current_state not in ("FINISH", "FAILED"):
  6927. return "aborted"
  6928. archive_id = (archive.subtask_id or "").strip()
  6929. current_id = str(state.subtask_id or "").strip()
  6930. if archive_id in ("", "0") or archive_id != current_id:
  6931. return "aborted"
  6932. return "completed" if current_state == "FINISH" else "failed"
  6933. def _reconciled_end_time(archive, now: datetime, plate_id: int | None = None) -> datetime | None:
  6934. """When a print reconciled as completed most likely ended, or None (#3310).
  6935. The printer does not say when it finished, and the reconnect can be hours
  6936. later. Its start plus the slicer's estimate for the plate it printed,
  6937. never later than now, is the best guess; None when either is missing,
  6938. and the run then keeps no duration, as an aborted one does.
  6939. ``plate_id`` is the plate this run printed, from its queue job: a reprint
  6940. of another plate reuses the archive without changing ``archive.plate_id``.
  6941. """
  6942. started = archive.started_at
  6943. if not started:
  6944. return None
  6945. if started.tzinfo is None:
  6946. started = started.replace(tzinfo=timezone.utc)
  6947. plate = plate_id if plate_id is not None else archive.plate_id
  6948. estimate = None
  6949. if archive.file_path:
  6950. from backend.app.utils.threemf_tools import extract_print_time_from_3mf
  6951. full_path = (
  6952. app_settings.base_dir / archive.file_path
  6953. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  6954. try:
  6955. estimate = extract_print_time_from_3mf(full_path, plate)
  6956. except Exception as exc: # noqa: BLE001
  6957. logging.getLogger(__name__).debug(
  6958. "Plate estimate for reconciled archive %s unreadable: %s", archive.id, exc
  6959. )
  6960. if plate is None and estimate != archive.print_time_seconds:
  6961. # Without a plate the first plate's estimate is read. The archive
  6962. # carries the sum over all plates (#1593), so a difference means
  6963. # several plates and no telling which one printed.
  6964. estimate = None
  6965. elif plate is None:
  6966. # Nothing to read the plate from; the archive's own estimate, as for
  6967. # a single-plate file.
  6968. estimate = archive.print_time_seconds
  6969. if not estimate or estimate <= 0:
  6970. return None
  6971. return min(started + timedelta(seconds=int(estimate)), now)
  6972. async def reconcile_stale_active_prints(printer_id: int) -> int:
  6973. """Synthesise ``on_print_complete`` for archives whose print can't be
  6974. running on the printer anymore.
  6975. Called once per MQTT (re)connection (from on_printer_status_change when
  6976. the connected edge flips False → True) and at Bambuddy startup (from
  6977. the FastAPI lifespan). Without this, a print that completes during a
  6978. disconnect window — followed by a smart-plug-driven power cycle — leaves
  6979. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  6980. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  6981. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  6982. power cycle until the operator notices (#1542 follow-up). Reconciliation
  6983. closes the loop by faking the missed PRINT COMPLETE — the existing
  6984. cleanup chain handles SD-file deletion, status updates, usage tracking,
  6985. and notifications.
  6986. The status is ``_reconciled_outcome``'s: ``completed`` or ``failed``
  6987. when the printer still reports the archive's own job as finished or
  6988. failed, ``aborted`` otherwise. Nothing corrects it later: the archive is
  6989. no longer ``printing``, so a later PRINT COMPLETE finds no archive, and
  6990. after a restart the printer's FINISH is not one (#3310).
  6991. Returns the number of archives reconciled.
  6992. """
  6993. state = printer_manager.get_status(printer_id)
  6994. if not state:
  6995. return 0
  6996. # Don't reconcile while disconnected — we'd be making a decision against
  6997. # stale cached state. The connected → reconcile edge handles this.
  6998. if not state.connected:
  6999. return 0
  7000. from backend.app.models.archive import PrintArchive
  7001. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
  7002. reconciled = 0
  7003. async with async_session() as db:
  7004. # The prints on this printer Bambuddy saw start: their runs open here.
  7005. # The archive row is shared by every plate of a file, its printer, job
  7006. # and start the latest start's, so each is judged as its run.
  7007. open_runs = (
  7008. await db.scalars(
  7009. select(PrintLogEntry)
  7010. .where(PrintLogEntry.printer_id == printer_id, PrintLogEntry.status == RUN_OPEN)
  7011. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7012. )
  7013. ).all()
  7014. by_run = {
  7015. archive.id: archive
  7016. for archive in (
  7017. await db.scalars(
  7018. select(PrintArchive).where(
  7019. PrintArchive.id.in_([run.archive_id for run in open_runs if run.archive_id is not None])
  7020. )
  7021. )
  7022. ).all()
  7023. }
  7024. active: list = [_RunOfArchive(by_run[run.archive_id], run) for run in open_runs if run.archive_id in by_run]
  7025. # And as before runs were opened at the start: a printing archive of
  7026. # this printer with no run open anywhere (printing since before).
  7027. archives_with_open_runs = select(PrintLogEntry.archive_id).where(
  7028. PrintLogEntry.status == RUN_OPEN, PrintLogEntry.archive_id.is_not(None)
  7029. )
  7030. result = await db.execute(
  7031. select(PrintArchive)
  7032. .where(
  7033. PrintArchive.printer_id == printer_id,
  7034. PrintArchive.status == "printing",
  7035. PrintArchive.id.not_in(archives_with_open_runs),
  7036. )
  7037. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7038. )
  7039. active.extend(result.scalars().all())
  7040. if not active:
  7041. return 0
  7042. # The plate each run printed, from its queue job (#3310).
  7043. from backend.app.models.print_queue import PrintQueueItem
  7044. async with async_session() as db:
  7045. plate_rows = await db.execute(
  7046. select(PrintQueueItem.archive_id, PrintQueueItem.plate_id).where(
  7047. PrintQueueItem.printer_id == printer_id,
  7048. PrintQueueItem.status == "printing",
  7049. PrintQueueItem.archive_id.in_([a.id for a in active]),
  7050. )
  7051. )
  7052. run_plates = {archive_id: plate for archive_id, plate in plate_rows.all() if plate is not None}
  7053. logger = logging.getLogger(__name__)
  7054. for archive in active:
  7055. is_stale, reason = _is_active_archive_stale(archive, state)
  7056. if not is_stale:
  7057. continue
  7058. logger.info(
  7059. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  7060. printer_id,
  7061. archive.id,
  7062. archive.filename,
  7063. reason,
  7064. )
  7065. # Synthesised payload: minimal fields the on_print_complete chain
  7066. # needs. `_reconciled` marker lets downstream code distinguish this
  7067. # from a real MQTT-driven completion if it ever needs to (e.g. for
  7068. # metrics / debug logging). raw_data is the live printer state so
  7069. # the usage tracker can compare end-of-print remain% against the
  7070. # captured start values.
  7071. outcome = _reconciled_outcome(archive, state)
  7072. payload = {
  7073. "status": outcome,
  7074. "filename": archive.filename,
  7075. "subtask_name": archive.print_name or "",
  7076. "subtask_id": archive.subtask_id or "",
  7077. "raw_data": state.raw_data or {},
  7078. "_reconciled": True,
  7079. }
  7080. if isinstance(archive, _RunOfArchive):
  7081. # The archive it closes, which its names and printer may not find:
  7082. # another printer's plate of it can have started since.
  7083. payload["_reconciled_archive_id"] = archive.id
  7084. if outcome != "aborted":
  7085. # The printer's progress and layer are this job's, so a partial
  7086. # run is charged what it printed rather than nothing.
  7087. if state.progress:
  7088. payload["last_progress"] = state.progress
  7089. if state.layer_num:
  7090. payload["last_layer_num"] = state.layer_num
  7091. if outcome == "failed":
  7092. payload["hms_errors"] = [e.completion_payload() for e in state.hms_errors or []]
  7093. if outcome == "completed":
  7094. ended = _reconciled_end_time(archive, datetime.now(timezone.utc), run_plates.get(archive.id))
  7095. if ended:
  7096. payload["_reconciled_completed_at"] = ended
  7097. try:
  7098. await on_print_complete(printer_id, payload)
  7099. reconciled += 1
  7100. except Exception as e:
  7101. # Catch-all: a reconciliation failure must not block the
  7102. # printer's normal status flow. The archive stays in
  7103. # ``status="printing"`` and the next reconnect retries.
  7104. logger.warning(
  7105. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  7106. archive.id,
  7107. e,
  7108. )
  7109. return reconciled
  7110. # #2547: clearance left between the nozzle and the top of the print when the
  7111. # plate is commanded back into camera framing. The nozzle is parked away from
  7112. # the part by then, so this is belt-and-braces against a max_z_height that
  7113. # under-reports (e.g. a slicer that excludes a final Z hop).
  7114. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  7115. # How far below the restored position to drop the plate again afterwards, so
  7116. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  7117. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  7118. # on machines with less headroom.
  7119. _PLATE_PARK_DROP_MM = 100.0
  7120. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  7121. # this axis, so it is a proven-safe speed for the full travel.
  7122. _PLATE_RESTORE_FEEDRATE = 600
  7123. # Time allowed for the plate to reach the restored position before the camera
  7124. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  7125. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  7126. # How long `_background_finish_photo` waits for this producer. Must cover the
  7127. # settle window plus a worst-case RTSP grab (15s), and stay below the
  7128. # notification path's own photo wait so a slow producer degrades to a
  7129. # photo-less notification rather than a missed one. The chamber light's
  7130. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  7131. # camera_light.MAX_DELAY_SECONDS stays below it.
  7132. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  7133. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  7134. """The ``_active_prints`` keys a finished print may be registered under.
  7135. Matching how they were registered in on_print_start. Shared by
  7136. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  7137. to find the same binding.
  7138. """
  7139. possible_keys = []
  7140. # Try subtask_name variations first (most reliable for matching)
  7141. if subtask_name:
  7142. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  7143. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  7144. possible_keys.append((printer_id, subtask_name))
  7145. # Try filename variations
  7146. if filename:
  7147. # Extract just the filename if it's a path
  7148. fname = filename.split("/")[-1] if "/" in filename else filename
  7149. if fname.endswith(".3mf"):
  7150. possible_keys.append((printer_id, fname))
  7151. elif fname.endswith(".gcode"):
  7152. base_name = fname.rsplit(".", 1)[0]
  7153. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  7154. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7155. possible_keys.append((printer_id, fname))
  7156. else:
  7157. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  7158. possible_keys.append((printer_id, f"{fname}.3mf"))
  7159. possible_keys.append((printer_id, fname))
  7160. # Also try full path versions
  7161. if filename.endswith(".3mf"):
  7162. possible_keys.append((printer_id, filename))
  7163. elif filename.endswith(".gcode"):
  7164. base_name = filename.rsplit(".", 1)[0]
  7165. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7166. possible_keys.append((printer_id, filename))
  7167. else:
  7168. possible_keys.append((printer_id, f"{filename}.3mf"))
  7169. possible_keys.append((printer_id, filename))
  7170. return possible_keys
  7171. def _archive_name_forms(archive) -> set[str]:
  7172. """The names an archive could be echoed back as, in normalised form (#3240).
  7173. Its print name, and its filename with and without the 3MF extension.
  7174. """
  7175. forms = set()
  7176. if archive.print_name:
  7177. forms.add(_normalise_subtask_name(archive.print_name))
  7178. if archive.filename:
  7179. forms.add(_normalise_subtask_name(archive.filename))
  7180. for suffix in (".gcode.3mf", ".3mf"):
  7181. if archive.filename.lower().endswith(suffix):
  7182. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  7183. forms.discard("")
  7184. return forms
  7185. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  7186. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  7187. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  7188. from the plate recorded when the job was dispatched. Neither is touched:
  7189. ``on_print_complete`` pops both, which is why the finish-photo producer
  7190. calls this before its first await, while they are still there.
  7191. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  7192. archive, or that it only knows by a name -- and on any error: the producer
  7193. calls this before the ``try`` that always releases the photo consumer, so
  7194. it must not raise.
  7195. """
  7196. try:
  7197. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  7198. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  7199. if archive_id is None:
  7200. return None, None
  7201. return archive_id, _print_plate_ids.get((printer_id, archive_id))
  7202. except Exception:
  7203. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  7204. return None, None
  7205. async def _max_z_for_current_print(
  7206. printer_id: int,
  7207. data: dict,
  7208. logger,
  7209. archive_id: int | None,
  7210. plate_id: int | None = None,
  7211. ) -> float | None:
  7212. """Height of the print that just finished on ``printer_id``, or None (#2547).
  7213. This number becomes the target of a real Z move, so every step here refuses
  7214. rather than guesses. A height belonging to some *other* print is the one
  7215. failure that could drive the nozzle into the model: 20 mm carried onto a
  7216. 200 mm print would command the plate up through the part.
  7217. Three independent things therefore have to agree before a height is
  7218. returned:
  7219. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  7220. when it started (see ``_bound_print``), never one found by name. A name
  7221. is not an identity: every plate of a multi-plate file shares one, and a
  7222. reprint reuses its archive row, so the newest archive with the right
  7223. name can be another plate of the same file. Support bundles show the
  7224. old name lookup doing exactly that (archive 288 for a print bound to
  7225. 169, 313 layers against 125), stopped only by the layer check below.
  7226. No binding, no move.
  7227. 2. **Identity.** The bound archive's name still has to be the finished
  7228. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  7229. because the printer echoes spaces as underscores (#3240). Exact: not a
  7230. substring, and not the completion check's tolerance for a truncated
  7231. echo.
  7232. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  7233. match the layer count the printer itself reported over MQTT for the print
  7234. that just ended. These come from genuinely different sources, so a
  7235. mismatch means the row is not this print, whatever its name says.
  7236. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  7237. plate of a multi-plate file reuses the archive row without updating its
  7238. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  7239. ``on_print_complete`` may already have flipped the status by the time we
  7240. run.
  7241. """
  7242. subtask_name = (data.get("subtask_name") or "").strip()
  7243. if not subtask_name:
  7244. # Nothing to identify the print by — refuse rather than fall back to
  7245. # "whatever ran last on this printer".
  7246. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  7247. return None
  7248. if archive_id is None:
  7249. logger.info(
  7250. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  7251. printer_id,
  7252. subtask_name,
  7253. )
  7254. return None
  7255. try:
  7256. from backend.app.models.archive import PrintArchive
  7257. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  7258. async with async_session() as db:
  7259. result = await db.execute(
  7260. select(PrintArchive).where(
  7261. PrintArchive.id == archive_id,
  7262. PrintArchive.printer_id == printer_id,
  7263. PrintArchive.status.in_(("printing", "completed")),
  7264. PrintArchive.deleted_at.is_(None),
  7265. )
  7266. )
  7267. archive = result.scalar_one_or_none()
  7268. if archive is None or not archive.file_path:
  7269. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  7270. return None
  7271. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  7272. logger.warning(
  7273. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  7274. printer_id,
  7275. archive_id,
  7276. subtask_name,
  7277. )
  7278. return None
  7279. client = printer_manager.get_client(printer_id)
  7280. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  7281. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  7282. logger.warning(
  7283. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  7284. "— refusing to move the plate on a height that may not be this print's",
  7285. printer_id,
  7286. archive.id,
  7287. archive.total_layers,
  7288. reported_layers,
  7289. )
  7290. return None
  7291. # Stored relative to the data directory, like every other archive path
  7292. # (#3240: this read a `data_dir` setting that does not exist).
  7293. path = app_settings.base_dir / archive.file_path
  7294. plate = plate_id or archive.plate_id or 1
  7295. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  7296. except Exception as e:
  7297. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  7298. return None
  7299. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  7300. """Raise the plate back into camera framing before the finish photo (#2547).
  7301. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  7302. the time ``gcode_state`` reaches FINISH the finished print sits far below
  7303. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  7304. This commands an absolute ``G1 Z`` back to just above the last printed
  7305. layer.
  7306. Absolute, not relative, is the whole safety argument. ``max_z_height +
  7307. clearance`` is a height the toolhead was physically at seconds earlier, so
  7308. it is inside the travel limits by construction and leaves the nozzle above
  7309. the part. It is also unambiguous across model families: Z is the
  7310. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  7311. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  7312. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  7313. (#2579).
  7314. Returns True if the move was sent and waited out, False if it was skipped.
  7315. """
  7316. client = printer_manager.get_client(printer_id)
  7317. if client is None:
  7318. return False
  7319. # Re-read state immediately before commanding motion. If the queue has
  7320. # already started the next print, the printer is no longer ours to move.
  7321. state = getattr(client, "state", None)
  7322. if state is None or state.state != "FINISH":
  7323. logger.info(
  7324. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  7325. printer_id,
  7326. getattr(state, "state", "unknown"),
  7327. )
  7328. return False
  7329. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  7330. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  7331. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  7332. return False
  7333. logger.info(
  7334. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  7335. printer_id,
  7336. target_z,
  7337. max_z_height,
  7338. _PLATE_RESTORE_CLEARANCE_MM,
  7339. _PLATE_RESTORE_SETTLE_SECONDS,
  7340. )
  7341. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  7342. return True
  7343. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  7344. """Drop the plate again after the finish photo (#2547).
  7345. Without this the user walks up to a finished print sitting just under the
  7346. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  7347. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  7348. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  7349. print homes anyway.
  7350. """
  7351. client = printer_manager.get_client(printer_id)
  7352. state = getattr(client, "state", None) if client else None
  7353. if client is None or state is None or state.state != "FINISH":
  7354. return
  7355. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  7356. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  7357. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  7358. """True if a queue item is about to take this printer (#2547).
  7359. The scheduler dispatches the next job the moment a print completes, and a
  7360. plate move interleaved with a print start is not a race worth having. The
  7361. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  7362. this window; this closes the head of it.
  7363. """
  7364. try:
  7365. from backend.app.models.print_queue import PrintQueueItem
  7366. async with async_session() as db:
  7367. result = await db.execute(
  7368. select(PrintQueueItem.id)
  7369. .where(
  7370. PrintQueueItem.printer_id == printer_id,
  7371. PrintQueueItem.status.in_(("pending", "printing")),
  7372. )
  7373. .limit(1)
  7374. )
  7375. return result.scalar_one_or_none() is not None
  7376. except Exception as e:
  7377. # Fail closed: if we can't tell, don't move the plate.
  7378. logging.getLogger(__name__).debug(
  7379. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  7380. )
  7381. return True
  7382. async def on_finish_photo_moment(printer_id: int, data: dict):
  7383. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  7384. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  7385. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  7386. fallback for prints that skip stage 22 (cancel, external-spool-only,
  7387. HMS halt, firmware variants). Grabs one frame via the same
  7388. external-camera / RTSP path the post-completion fallback uses, stores
  7389. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  7390. ``_background_finish_photo`` consume the cached bytes when it runs.
  7391. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  7392. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  7393. set to Smooth (#1721). No force-on now means the user's explicit
  7394. timelapse=off in the slicer send dialog is respected.
  7395. """
  7396. logger = logging.getLogger(__name__)
  7397. trigger = data.get("trigger", "unknown")
  7398. timelapse_was_active = bool(data.get("timelapse_was_active"))
  7399. logger.info(
  7400. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  7401. printer_id,
  7402. trigger,
  7403. timelapse_was_active,
  7404. )
  7405. # If a timelapse is actively recording, skip the pre-capture — the
  7406. # post-completion path will extract the last frame from the recorded
  7407. # video, which still provides the best framing (toolhead parked,
  7408. # before bed drop) without the per-layer parking side effects.
  7409. if timelapse_was_active:
  7410. logger.info(
  7411. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  7412. printer_id,
  7413. )
  7414. return
  7415. # #1790: register the producer-done event BEFORE the first await so the
  7416. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  7417. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  7418. # The `finally` below guarantees `set()` runs on every exit, including
  7419. # early returns and exceptions, so the consumer's bounded wait can't hang.
  7420. producer_done = asyncio.Event()
  7421. _stage22_finish_in_flight[printer_id] = producer_done
  7422. # #3240: also before the first await. On the FINISH-state path
  7423. # `on_print_complete` is dispatched right behind us and pops both the
  7424. # print's archive binding and its plate; read here, they are still there.
  7425. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  7426. # #2547: set once the plate has actually been raised, and read by the
  7427. # `finally` below. Declared out here so a failure anywhere after the move —
  7428. # a camera timeout, a DB error — still lowers the plate again.
  7429. restore_max_z: float | None = None
  7430. try:
  7431. async with async_session() as db:
  7432. from backend.app.api.routes.settings import get_setting
  7433. from backend.app.models.printer import Printer
  7434. capture_setting = await get_setting(db, "capture_finish_photo")
  7435. if capture_setting is not None and capture_setting.lower() != "true":
  7436. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  7437. return
  7438. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7439. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  7440. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7441. printer = result.scalar_one_or_none()
  7442. if printer is None:
  7443. logger.warning(
  7444. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  7445. printer_id,
  7446. )
  7447. return
  7448. frame_bytes: bytes | None = None
  7449. # #2708: the banked frame arrives already rotated — it comes from
  7450. # `_capture_snapshot_for_notification`, which rotates before returning.
  7451. # Every other source below is a raw grab. Tracking which lets us store
  7452. # exactly one rotation in `_stage22_finish_frames` either way.
  7453. frame_already_rotated = False
  7454. # On the FINISH-state path the End G-code has already run, and two very
  7455. # different situations arrive here needing opposite answers.
  7456. #
  7457. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  7458. # snippet may have ejected the plate — the scene in front of the camera
  7459. # is no longer the finished print, and no amount of moving the plate
  7460. # brings it back. Use the banked in-print frame instead.
  7461. #
  7462. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  7463. # than the camera frames well, and the toolhead is parked out of the
  7464. # way. That is the *best* moment available on firmware that never emits
  7465. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  7466. # back. Preferring the bank here unconditionally, as this code used to,
  7467. # is what shipped a mid-print photo with the toolhead over the part.
  7468. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  7469. banked = _inprint_frame_bank.get(printer_id)
  7470. if banked:
  7471. frame_bytes = banked
  7472. frame_already_rotated = True
  7473. logger.info(
  7474. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  7475. "frame (%d bytes) instead of a post-swap live grab",
  7476. len(banked),
  7477. )
  7478. else:
  7479. logger.warning(
  7480. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  7481. "in-print bank is empty — falling back to a live grab, which may show a "
  7482. "swapped or empty plate",
  7483. printer_id,
  7484. )
  7485. # `restore_max_z` is set only once the plate is actually up, because the
  7486. # `finally` reads it to decide whether it owes a move back down.
  7487. #
  7488. # Never on a print whose End G-code Bambuddy injected, even when the bank
  7489. # came up empty above: that machine may have just ejected its plate, and
  7490. # driving Z into whatever a swap mechanism is doing is not a risk worth
  7491. # taking for a photo of a bed we already know may be bare.
  7492. if (
  7493. frame_bytes is None
  7494. and trigger == "finish_state"
  7495. and restore_plate_enabled
  7496. and not print_dispatch_context.end_gcode_injected(printer_id)
  7497. ):
  7498. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  7499. if wants_restore is None:
  7500. logger.info(
  7501. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  7502. printer_id,
  7503. )
  7504. elif await _plate_restore_is_blocked_by_queue(printer_id):
  7505. logger.info(
  7506. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  7507. printer_id,
  7508. )
  7509. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  7510. restore_max_z = wants_restore
  7511. # Chamber light for the live capture below (#1655). The banked frame
  7512. # above was taken without it, like every in-print bank.
  7513. async with camera_light(printer if frame_bytes is None else None):
  7514. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  7515. from backend.app.api.routes.camera import live_frame_for_capture
  7516. from backend.app.services.external_camera import capture_frame
  7517. # #2707: this used to collide with the live view and fail, which is
  7518. # how finish-photo notifications went out with no image attached.
  7519. # Leaving frame_bytes None keeps the rest of the fallback chain.
  7520. defer, buffered = live_frame_for_capture(printer_id)
  7521. if defer:
  7522. frame_bytes = buffered
  7523. else:
  7524. frame_bytes = await capture_frame(
  7525. printer.external_camera_url,
  7526. printer.external_camera_type or "mjpeg",
  7527. snapshot_url=printer.external_camera_snapshot_url,
  7528. )
  7529. if frame_bytes:
  7530. logger.info(
  7531. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  7532. len(frame_bytes),
  7533. )
  7534. elif frame_bytes is None:
  7535. from backend.app.api.routes.camera import get_buffered_frame
  7536. buffered = get_buffered_frame(printer_id)
  7537. if buffered:
  7538. frame_bytes = buffered
  7539. logger.info(
  7540. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  7541. len(frame_bytes),
  7542. )
  7543. else:
  7544. from backend.app.services.camera import capture_camera_frame_bytes
  7545. frame_bytes = await capture_camera_frame_bytes(
  7546. ip_address=printer.ip_address,
  7547. access_code=printer.access_code,
  7548. model=printer.model,
  7549. timeout=15,
  7550. )
  7551. if frame_bytes:
  7552. logger.info(
  7553. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  7554. len(frame_bytes),
  7555. )
  7556. if frame_bytes:
  7557. if not frame_already_rotated:
  7558. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  7559. _stage22_finish_frames[printer_id] = frame_bytes
  7560. else:
  7561. logger.warning(
  7562. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  7563. printer_id,
  7564. )
  7565. except Exception as e:
  7566. logger.warning(
  7567. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  7568. printer_id,
  7569. e,
  7570. )
  7571. finally:
  7572. # #2547: we raised the plate, so we own lowering it — including when the
  7573. # capture above failed or threw partway through.
  7574. if restore_max_z is not None:
  7575. try:
  7576. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  7577. except Exception as e:
  7578. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7579. # #1790: always unblock the consumer's bounded wait — whether we stored
  7580. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  7581. # dict entry by the consumer doesn't affect signalling.
  7582. producer_done.set()
  7583. def _subtask_name_from_filename(filename: str) -> str:
  7584. """Recover the subtask name a print command would have carried for *filename*.
  7585. The dispatcher derives the printer-facing subtask name from the archive's
  7586. file name, so stripping the extensions back off gives the value MQTT echoes
  7587. on completion. Only the two extensions Bambuddy actually stores are removed,
  7588. and in the order they nest (``.gcode.3mf``), so a model whose own name
  7589. contains a dot -- ``My.Model.3mf`` -- keeps it.
  7590. """
  7591. name = PurePosixPath(filename).name
  7592. for suffix in (".3mf", ".gcode"):
  7593. if name.lower().endswith(suffix):
  7594. name = name[: -len(suffix)]
  7595. return name
  7596. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  7597. """Whether the subtask name is the printed 3MF's own file name.
  7598. A print started from the printer's screen reports the same full name, with
  7599. its extension, as both subtask and file (#3009). A dispatched print reports
  7600. a bare subtask name; one that merely ends in ".3mf" can be a model named
  7601. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  7602. """
  7603. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  7604. return False
  7605. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  7606. # How the printer marks a subtask name it had to cut short. Observed on real
  7607. # hardware at ~100 characters, but the cut-off is not a fixed character count
  7608. # (a name with multibyte characters came back at 98), so match the marker
  7609. # rather than a length.
  7610. _SUBTASK_TRUNCATION_MARKER = "..."
  7611. def _normalise_subtask_name(name: str) -> str:
  7612. """Canonical form for comparing a dispatched name against MQTT's echo.
  7613. The printer does not echo the name back verbatim: it substitutes
  7614. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  7615. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  7616. The 3MF lookup in this module has always known that -- it builds
  7617. space-to-underscore variants of every candidate filename, and its
  7618. directory search normalises both sides before comparing. This exists so
  7619. the completion check reads the same rule from the same place instead of
  7620. growing its own, which is exactly how it came to disagree (#2829).
  7621. A space at either end is substituted too: ``Part .gcode.3mf`` is
  7622. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  7623. are dropped after the substitution so both sides agree (#3241).
  7624. """
  7625. return name.strip().replace(" ", "_").strip("_").casefold()
  7626. def _3mf_files_for_print(paths: list[str], search_term: str) -> list[str]:
  7627. """The 3MF files of the printer's folder listings that are this print's.
  7628. A file of the print's own name wins, in whichever folder. Only without one
  7629. is a file that merely contains the name taken, and then only when it is
  7630. the one such file: "Cube_large.3mf" is not "Cube"'s file, and of several
  7631. candidates none can be told apart. Paths keep the listings' order.
  7632. """
  7633. threemf = [path for path in paths if path.lower().endswith(".3mf")]
  7634. exact = [path for path in threemf if _subtask_names_match(_subtask_name_from_filename(path), search_term)]
  7635. if exact:
  7636. return exact
  7637. term = _normalise_subtask_name(search_term)
  7638. partial = [path for path in threemf if term in _normalise_subtask_name(PurePosixPath(path).name)]
  7639. if len(partial) > 1:
  7640. logging.getLogger(__name__).info(
  7641. "Several 3MF files contain %r and none is named for it: %s", search_term, partial
  7642. )
  7643. return []
  7644. return partial
  7645. def _subtask_names_match(expected: str, observed: str) -> bool:
  7646. """Whether two subtask names describe the same print.
  7647. Beyond the space/underscore substitution, the printer truncates long names
  7648. and marks the cut with ``...``. A truncated echo has to count as a match or
  7649. every print with a long name strands its queue item the same way.
  7650. """
  7651. expected_n = _normalise_subtask_name(expected)
  7652. observed_n = _normalise_subtask_name(observed)
  7653. if expected_n == observed_n:
  7654. return True
  7655. # Either side can be the truncated one: the printer truncates what it
  7656. # echoes, and an archive whose own filename was recorded from a previous
  7657. # truncated echo carries the marker too.
  7658. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  7659. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  7660. continue
  7661. # The full side has lost its edge underscores; a cut that lands right
  7662. # after one keeps it, so drop it here too (#3241). Nothing left before
  7663. # the marker is no evidence of anything, and must not match every name.
  7664. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  7665. if kept and full.startswith(kept):
  7666. return True
  7667. return False
  7668. async def _queue_item_dispatched_name(db, item) -> str:
  7669. """The subtask name *item* was dispatched under, or "" when unknowable.
  7670. A row with no archive, or an archive with no file name, is unverifiable
  7671. rather than wrong; every caller answers that with its permissive branch.
  7672. """
  7673. if item.archive_id is None:
  7674. return ""
  7675. from backend.app.models.archive import PrintArchive
  7676. archive = await db.get(PrintArchive, item.archive_id)
  7677. if archive is None or not archive.filename:
  7678. return ""
  7679. return _subtask_name_from_filename(archive.filename)
  7680. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  7681. """Whether this completion event is plausibly about *item*'s print.
  7682. The caller finds its queue row by printer and ``status='printing'`` alone,
  7683. which is all a completion event gives it -- there is no run identifier in
  7684. the MQTT payload to match on. That makes the lookup indiscriminate: any
  7685. completion delivered for this printer closes whichever row happens to be
  7686. printing, however unrelated. Comparing the subtask name against the archive
  7687. the row was dispatched with costs one primary-key load and rules that out.
  7688. Deliberately permissive: it answers False only on a positive disagreement
  7689. between two names we actually have. A row with no archive, an archive with
  7690. no file name, or an event with no subtask name is unverifiable rather than
  7691. wrong, and refusing those would strand the item in ``printing`` and wedge
  7692. the printer's queue -- a worse failure than the one being prevented.
  7693. """
  7694. observed = (data.get("subtask_name") or "").strip()
  7695. if not observed or item.archive_id is None:
  7696. return True
  7697. from backend.app.models.archive import PrintArchive
  7698. archive = await db.get(PrintArchive, item.archive_id)
  7699. if archive is None or not archive.filename:
  7700. return True
  7701. expected = _subtask_name_from_filename(archive.filename)
  7702. if not expected or _subtask_names_match(expected, observed):
  7703. return True
  7704. logging.getLogger(__name__).warning(
  7705. "Ignoring print completion for queue item %s: it was dispatched as %r "
  7706. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  7707. "printing rather than closing a run this event is not about.",
  7708. item.id,
  7709. expected,
  7710. archive.id,
  7711. archive.filename,
  7712. observed,
  7713. )
  7714. return False
  7715. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  7716. """Spend the 3MF download cache on a still-empty fallback archive.
  7717. ``on_print_complete`` drops the cache as its first act, which deletes the
  7718. file. If the cover endpoint (or anything else) pulled the 3MF while the
  7719. print ran and the archive never got one, this is the last moment those bytes
  7720. exist (#2957).
  7721. """
  7722. logger = logging.getLogger(__name__)
  7723. names = [
  7724. n
  7725. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  7726. if n
  7727. ]
  7728. for name in names:
  7729. try:
  7730. cached = get_cached_3mf(printer_id, name)
  7731. # The print has ended: its completion prices the archive, so no
  7732. # print-start estimate is scheduled to race it.
  7733. if cached and await try_recover_fallback_archive(printer_id, name, cached, price=False):
  7734. return
  7735. except Exception as e:
  7736. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  7737. # Longest the print's end waits for its file to be deleted from the SD card
  7738. _SD_CLEANUP_BUDGET_SECONDS = 45.0
  7739. async def _cleanup_sd_card_after_print(
  7740. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  7741. ) -> None:
  7742. """Delete a finished print's file from the printer's SD card."""
  7743. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  7744. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  7745. # auto-start files found in root on power cycle, causing ghost prints.
  7746. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  7747. try:
  7748. if subtask_name:
  7749. archive_filename: str | None = None
  7750. async with async_session() as db:
  7751. from backend.app.models.archive import PrintArchive
  7752. from backend.app.models.printer import Printer
  7753. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7754. printer = result.scalar_one_or_none()
  7755. if archive_id:
  7756. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  7757. archive_filename = archive_row.scalar_one_or_none()
  7758. if printer:
  7759. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  7760. from backend.app.utils.filename import derive_remote_filename
  7761. # Primary candidate: the exact path the dispatcher uploaded to
  7762. # (derived from archive.filename via the same rule as upload).
  7763. # Without it, a library row that ended up with a doubled
  7764. # .gcode.3mf (#1542) leaves the real file behind because the
  7765. # subtask_name + ext fallbacks below don't match what's on the
  7766. # SD card. Fallbacks remain for archive-less prints (subtask
  7767. # never resolved to an archive) and for older naming variants.
  7768. candidate_paths: list[str] = []
  7769. if archive_filename:
  7770. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  7771. for ext in (".3mf", ".gcode"):
  7772. fallback = f"/{subtask_name}{ext}"
  7773. if fallback not in candidate_paths:
  7774. candidate_paths.append(fallback)
  7775. # Three outcomes track across all candidates so the final log
  7776. # line reflects what actually happened. The A1 in #1721 always
  7777. # ends here with ``any_not_found=True`` and the others False
  7778. # — its firmware auto-cleans the SD card before our cleanup
  7779. # runs, every candidate FTP-DELE returns 550, and the old
  7780. # code burned 3 retries × 2 s × 3 candidates per print
  7781. # logging a misleading "may linger" WARNING on a successful
  7782. # print.
  7783. any_deleted = False
  7784. any_real_failure = False
  7785. any_not_found = False
  7786. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  7787. for remote_path in candidate_paths:
  7788. if PurePosixPath(remote_path).name.lower() in files_in_use:
  7789. logger.info(
  7790. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  7791. remote_path,
  7792. printer.name,
  7793. )
  7794. continue
  7795. # Retry only the FAILED case — 550 NOT_FOUND will never
  7796. # recover by waiting, so a "file isn't here" answer
  7797. # advances immediately to the next candidate without
  7798. # consuming the retry budget.
  7799. for attempt in range(1, 4):
  7800. try:
  7801. delete_result = await delete_file_async(
  7802. printer.ip_address,
  7803. printer.access_code,
  7804. remote_path,
  7805. printer_model=printer.model,
  7806. )
  7807. except Exception as e:
  7808. delete_result = DeleteResult.FAILED
  7809. logger.warning(
  7810. "SD card cleanup attempt %d/3 raised for %s: %s",
  7811. attempt,
  7812. remote_path,
  7813. e,
  7814. )
  7815. if delete_result == DeleteResult.DELETED:
  7816. any_deleted = True
  7817. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  7818. break
  7819. if delete_result == DeleteResult.NOT_FOUND:
  7820. any_not_found = True
  7821. break # 550 will not recover; try next candidate
  7822. # FAILED: real error — retry with backoff, then give up
  7823. if attempt < 3:
  7824. await asyncio.sleep(2)
  7825. else:
  7826. any_real_failure = True
  7827. logger.warning(
  7828. "SD card cleanup failed after 3 attempts for %s "
  7829. "(network/auth/transient error — file may linger on SD card)",
  7830. remote_path,
  7831. )
  7832. if not any_deleted and not any_real_failure and any_not_found:
  7833. # Every candidate said "not here." Either the printer
  7834. # firmware swept the SD card itself (common on A1) or the
  7835. # dispatcher's upload path doesn't match our candidate
  7836. # rule. Either way: nothing to clean up, no warning.
  7837. logger.debug(
  7838. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  7839. "(printer likely self-cleaned)",
  7840. printer.name,
  7841. )
  7842. except Exception as e:
  7843. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  7844. async def on_print_complete(printer_id: int, data: dict):
  7845. """Handle print completion - update the archive status.
  7846. The printer counts as printing until the print's usage is booked (or this
  7847. ends), so the AMS remain% weight sync can't charge it a second time while
  7848. the usage tracker works (WU-3). Marked before the first await.
  7849. """
  7850. from backend.app.services.usage_tracker import done_completing, mark_completing
  7851. mark_completing(printer_id)
  7852. try:
  7853. await _close_out_print(printer_id, data)
  7854. finally:
  7855. done_completing(printer_id)
  7856. async def _close_out_print(printer_id: int, data: dict):
  7857. import time
  7858. logger = logging.getLogger(__name__)
  7859. start_time = time.time()
  7860. def log_timing(section: str):
  7861. elapsed = time.time() - start_time
  7862. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  7863. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  7864. # A kill-switch stop sends its provider notification immediately. Keep the
  7865. # task so the later notification path can await it and avoid a duplicate;
  7866. # if that immediate attempt failed, the regular completion path retries.
  7867. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  7868. # Last chance before the bytes go: if this print's archive is still an empty
  7869. # fallback and something downloaded the 3MF while it ran, fill the archive in
  7870. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  7871. # below deletes the file (#2957).
  7872. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  7873. # A pending cool-off retry has nothing left to recover for — the cache is
  7874. # about to be dropped and the print is over.
  7875. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  7876. if retry_task and not retry_task.done():
  7877. retry_task.cancel()
  7878. # Drop the 3MF download cache for this printer (#972). The print is over,
  7879. # nothing else legitimately needs the bytes; keeping them would only risk
  7880. # handing a stale file to the next print if it reuses the same name.
  7881. clear_3mf_cache(printer_id)
  7882. try:
  7883. ws_data = {
  7884. "status": data.get("status"),
  7885. "filename": data.get("filename"),
  7886. "subtask_name": data.get("subtask_name"),
  7887. "timelapse_was_active": data.get("timelapse_was_active"),
  7888. }
  7889. await ws_manager.send_print_complete(printer_id, ws_data)
  7890. log_timing("WebSocket send_print_complete")
  7891. except Exception as e:
  7892. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  7893. # Capture user info before clearing (needed for print log entry)
  7894. _print_user_info = printer_manager.get_current_print_user(printer_id)
  7895. # Clear current print user tracking (Issue #206)
  7896. printer_manager.clear_current_print_user(printer_id)
  7897. # If the user explicitly stopped this print from the queue UI the printer will
  7898. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  7899. # correct "print stopped" notification/email is sent instead of a failure alert.
  7900. _raw_status = data.get("status", "completed")
  7901. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  7902. logger.info(
  7903. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  7904. _raw_status,
  7905. printer_id,
  7906. )
  7907. data = {**data, "status": "cancelled"}
  7908. elif printer_id in _kill_switch_stopped and _raw_status in ("failed", "aborted"):
  7909. logger.info(
  7910. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (stopped by the printer kill switch)",
  7911. _raw_status,
  7912. printer_id,
  7913. )
  7914. data = {**data, "status": "cancelled", "_kill_switch": True}
  7915. _user_stopped_printers.discard(printer_id)
  7916. _kill_switch_stopped.discard(printer_id)
  7917. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  7918. # may have left material on the bed: a user can cancel ten hours into a
  7919. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  7920. # touchscreen-stop reports `aborted` rather than `cancelled` because
  7921. # `_user_stopped_printers` is only populated when the user stops via the
  7922. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  7923. # which auto-dispatched the next queued print onto a fouled bed two seconds
  7924. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  7925. # Auto Off power cycles and Bambuddy restarts.
  7926. try:
  7927. notify_live_activities.print_finished(printer_id, data)
  7928. except Exception:
  7929. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  7930. _final_status = data.get("status", "completed")
  7931. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  7932. printer_manager.set_awaiting_plate_clear(printer_id, True)
  7933. # MQTT relay - publish print complete
  7934. try:
  7935. printer_info = printer_manager.get_printer(printer_id)
  7936. if printer_info:
  7937. await mqtt_relay.on_print_complete(
  7938. printer_id,
  7939. printer_info.name,
  7940. printer_info.serial_number,
  7941. data.get("filename", ""),
  7942. data.get("subtask_name", ""),
  7943. data.get("status", "completed"),
  7944. )
  7945. except Exception:
  7946. pass # Don't fail print complete callback if MQTT fails
  7947. filename = data.get("filename", "")
  7948. subtask_name = data.get("subtask_name", "")
  7949. if not filename and not subtask_name:
  7950. # Which print ended can't be told: the printer reported no name since
  7951. # Bambuddy started (a print that failed while preparing, a calibration).
  7952. # Charge nothing, but close the print session, which otherwise kept the
  7953. # AMS weight sync off until the next print (AS-5). A print archived as
  7954. # running is closed and charged by the reconnect reconcile.
  7955. logger.warning("Print complete without filename or subtask_name")
  7956. try:
  7957. from backend.app.services.usage_tracker import discard_session
  7958. async with async_session() as db:
  7959. await discard_session(db, printer_id)
  7960. except Exception as e:
  7961. logger.warning("Failed to clear print session for printer %s: %s", printer_id, e)
  7962. return
  7963. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  7964. # Build list of possible keys to try (matching how they were registered in on_print_start)
  7965. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  7966. # Find the archive for this print
  7967. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  7968. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  7969. archive_id = None
  7970. for key in possible_keys:
  7971. archive_id = _active_prints.pop(key, None)
  7972. if archive_id:
  7973. _owned_print_archive_ids.discard(archive_id)
  7974. logger.info("Found archive %s with key %s", archive_id, key)
  7975. # Also clean up the printer's other keys pointing to this archive;
  7976. # another printer's are a plate of it still printing there.
  7977. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id and k[0] == printer_id]
  7978. for k in keys_to_remove:
  7979. _active_prints.pop(k, None)
  7980. break
  7981. # The archive bound when the print started, before the name search below.
  7982. # Only this one may give the finish-photo plate restore a height (#3240):
  7983. # the search matches names by substring.
  7984. bound_archive_id = archive_id
  7985. if not archive_id and data.get("_reconciled") and data.get("_reconciled_archive_id"):
  7986. # The reconcile names the archive whose run on this printer it
  7987. # closes. Only while that run is open: the print's real end may have
  7988. # closed it meanwhile, or closed the print without managing to write
  7989. # it, and either way there is nothing left to end twice.
  7990. if await _archive_of_open_run(printer_id) != data["_reconciled_archive_id"]:
  7991. logger.info(
  7992. "[RECONCILE] Archive %s has no run open on printer %s any more; nothing to close",
  7993. data["_reconciled_archive_id"],
  7994. printer_id,
  7995. )
  7996. return
  7997. archive_id = data["_reconciled_archive_id"]
  7998. ending_job = str(data.get("subtask_id") or "").strip()
  7999. if not archive_id and ending_job not in ("", "0"):
  8000. # Not bound (a restart since the start): this job's run, open on the
  8001. # printer. Only by its job id: a run open there can be of the print
  8002. # running now, while the end is of an earlier one closed late (the
  8003. # restart's reconcile of a missed end).
  8004. archive_id = await _archive_of_open_run(printer_id, subtask_id=ending_job)
  8005. if archive_id:
  8006. logger.info("Found archive %s by the run of job %s open on printer %s", archive_id, ending_job, printer_id)
  8007. if not archive_id:
  8008. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  8009. async with async_session() as db:
  8010. from backend.app.models.archive import PrintArchive
  8011. # Try matching by subtask_name (stored as print_name) first. The
  8012. # same name rule as the queue's completion check: a name inside
  8013. # another ("Clip" in "Cable Clip") is a different print, and the
  8014. # printer's underscores for spaces and truncation still match.
  8015. if subtask_name:
  8016. printing = await db.scalars(
  8017. select(PrintArchive)
  8018. .where(PrintArchive.printer_id == printer_id)
  8019. .where(PrintArchive.status == "printing")
  8020. .order_by(PrintArchive.created_at.desc())
  8021. )
  8022. # A print started from the printer's screen reports its file
  8023. # name, extensions included, as the subtask (#3009).
  8024. reported = {subtask_name, _subtask_name_from_filename(subtask_name)}
  8025. archive = next(
  8026. (
  8027. candidate
  8028. for candidate in printing
  8029. if any(
  8030. (candidate.print_name and _subtask_names_match(candidate.print_name, name))
  8031. or (
  8032. candidate.filename
  8033. and _subtask_names_match(_subtask_name_from_filename(candidate.filename), name)
  8034. )
  8035. for name in reported
  8036. )
  8037. ),
  8038. None,
  8039. )
  8040. if archive:
  8041. archive_id = archive.id
  8042. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  8043. # Also try by filename
  8044. if not archive_id and filename:
  8045. result = await db.execute(
  8046. select(PrintArchive)
  8047. .where(PrintArchive.printer_id == printer_id)
  8048. .where(PrintArchive.filename == filename)
  8049. .where(PrintArchive.status == "printing")
  8050. .order_by(PrintArchive.created_at.desc())
  8051. .limit(1)
  8052. )
  8053. archive = result.scalar_one_or_none()
  8054. if archive:
  8055. archive_id = archive.id
  8056. # Bounded: a printer whose FTP hangs on DELE took up to 3 candidates x 3
  8057. # attempts x a 60 s timeout, about nine minutes, before the queue item was
  8058. # closed below. The stranded-job closer gives up after five and closed it
  8059. # first, so the job's auto-off and its billing never ran. Inline rather
  8060. # than in the background, so the next job of the same file isn't released
  8061. # (and uploaded under the name being deleted) while the cleanup still
  8062. # works on it. A delete already sent may still finish in its FTP thread
  8063. # after the cutoff, as one past delete_file_async's own timeout always did.
  8064. try:
  8065. await asyncio.wait_for(
  8066. _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger),
  8067. timeout=_SD_CLEANUP_BUDGET_SECONDS,
  8068. )
  8069. except TimeoutError:
  8070. logger.warning(
  8071. "SD card cleanup on printer %s took over %ss; leaving the file there and closing the print",
  8072. printer_id,
  8073. _SD_CLEANUP_BUDGET_SECONDS,
  8074. )
  8075. log_timing("SD card cleanup")
  8076. # Update queue item status early — must run before the archive_id early-return
  8077. # so queue items don't get stuck in "printing" when archive lookup fails.
  8078. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  8079. queue_item_id = None
  8080. billing_run_id: str | None = None
  8081. billing_user_id: int | None = None
  8082. billing_cost_center_id: int | None = None
  8083. billing_plate_id: int | None = None
  8084. queue_status = None
  8085. queue_auto_off = False
  8086. try:
  8087. from backend.app.core.database import run_with_retry
  8088. from backend.app.models.print_queue import PrintQueueItem
  8089. async def _update_queue_status(db):
  8090. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  8091. nonlocal queue_item_id, queue_status, queue_auto_off
  8092. result = await db.execute(
  8093. select(PrintQueueItem)
  8094. .where(PrintQueueItem.printer_id == printer_id)
  8095. .where(PrintQueueItem.status == "printing")
  8096. )
  8097. printing_items = list(result.scalars().all())
  8098. if len(printing_items) > 1:
  8099. logger.warning(
  8100. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  8101. printer_id,
  8102. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  8103. )
  8104. item = printing_items[0] if printing_items else None
  8105. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  8106. return
  8107. if item:
  8108. queue_status = data.get("status", "completed")
  8109. # MQTT sends "aborted" for cancelled prints; normalise to
  8110. # "cancelled" so it matches the queue schema Literal.
  8111. if queue_status == "aborted":
  8112. queue_status = "cancelled"
  8113. item.status = queue_status
  8114. item.completed_at = datetime.now(timezone.utc)
  8115. if queue_status == "failed" and not item.error_message:
  8116. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  8117. # Bump usage counters on the source library file so admins can
  8118. # sort by "last printed" and (eventually) auto-purge stale
  8119. # files — #1008.
  8120. await _bump_library_file_usage_if_completed(db, item, queue_status)
  8121. await db.commit()
  8122. queue_item_id = item.id
  8123. billing_run_id = item.billing_run_id
  8124. billing_user_id = item.created_by_id
  8125. billing_cost_center_id = item.cost_center_id
  8126. billing_plate_id = item.plate_id
  8127. queue_auto_off = item.auto_off_after
  8128. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  8129. await run_with_retry(_update_queue_status, label="queue status update")
  8130. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  8131. # their own sessions and have their own error handling — no retry needed.
  8132. if queue_item_id is not None:
  8133. # Batch orders (#342): this run may have been the last one an order
  8134. # owed. Re-evaluate here rather than lazily on read, so a finished
  8135. # order reports itself complete without someone opening the page.
  8136. try:
  8137. from backend.app.services.print_batch import refresh_batch_status_for_item
  8138. async with async_session() as db:
  8139. await refresh_batch_status_for_item(db, queue_item_id)
  8140. await db.commit()
  8141. except Exception as e:
  8142. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  8143. # MQTT relay - publish queue job completed
  8144. try:
  8145. printer_info = printer_manager.get_printer(printer_id)
  8146. await mqtt_relay.on_queue_job_completed(
  8147. job_id=queue_item_id,
  8148. filename=filename or subtask_name,
  8149. printer_id=printer_id,
  8150. printer_name=printer_info.name if printer_info else "Unknown",
  8151. status=queue_status,
  8152. )
  8153. except Exception:
  8154. pass # Don't fail if MQTT fails
  8155. # Check if queue is now empty and send notification
  8156. try:
  8157. from sqlalchemy import func as sa_func
  8158. async with async_session() as db:
  8159. count_result = await db.execute(
  8160. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  8161. )
  8162. pending_count = count_result.scalar() or 0
  8163. if pending_count == 0:
  8164. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  8165. completed_result = await db.execute(
  8166. select(sa_func.count(PrintQueueItem.id)).where(
  8167. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  8168. PrintQueueItem.completed_at >= today_start,
  8169. )
  8170. )
  8171. completed_count = completed_result.scalar() or 1
  8172. await notification_service.on_queue_completed(
  8173. completed_count=completed_count,
  8174. db=db,
  8175. )
  8176. except Exception:
  8177. pass # Don't fail if notification fails
  8178. # Handle auto_off_after - power off printer if the queue item opted
  8179. # in. Delegates to the smart-plug manager so the off honours each
  8180. # plug's configured strategy (time delay or temperature threshold),
  8181. # is cancelled if the printer starts printing again, and never cuts
  8182. # power on a loaded print (#1890). Previously an inline block here
  8183. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  8184. # timeout regardless of print state — cutting a touchscreen reprint.
  8185. if queue_auto_off:
  8186. try:
  8187. async with async_session() as db:
  8188. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  8189. except Exception as e:
  8190. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  8191. except Exception as e:
  8192. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  8193. log_timing("Queue item update")
  8194. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  8195. # Must run before archive_id early-return so it fires for all prints (including
  8196. # prints started from BambuStudio/touchscreen that have no archive).
  8197. if data.get("status") == "completed":
  8198. try:
  8199. from backend.app.api.routes.settings import get_setting
  8200. async with async_session() as db:
  8201. threshold_str = await get_setting(db, "bed_cooled_threshold")
  8202. threshold = float(threshold_str) if threshold_str else 35.0
  8203. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  8204. async with async_session() as db:
  8205. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  8206. if providers:
  8207. _bed_cool_waiters[printer_id] = {
  8208. "threshold": threshold,
  8209. "filename": filename or subtask_name or "",
  8210. "registered_at": time.time(),
  8211. }
  8212. logger.info(
  8213. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  8214. printer_id,
  8215. threshold,
  8216. )
  8217. else:
  8218. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  8219. except Exception as e:
  8220. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  8221. # Capture the slicer estimate before usage tracking runs. The tracker may
  8222. # update archive.cost with this run's measured cost; billing partial runs
  8223. # against that already-partial value would discount the charge twice.
  8224. billing_planned_grams: float | None = None
  8225. billing_base_cost: float | None = None
  8226. if archive_id:
  8227. try:
  8228. async with async_session() as db:
  8229. from backend.app.models.archive import PrintArchive
  8230. billing_archive = await db.get(PrintArchive, archive_id)
  8231. if billing_archive:
  8232. billing_path = (
  8233. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  8234. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8235. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  8236. billing_archive,
  8237. billing_path,
  8238. billing_plate_id
  8239. if billing_plate_id is not None
  8240. else _get_start_plate_id(printer_id, archive_id),
  8241. )
  8242. except Exception as e:
  8243. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  8244. # --- Track filament consumption (must run before archive_id early-return so usage
  8245. # is recorded even when auto-archive is disabled) ---
  8246. usage_results: list[dict] = []
  8247. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  8248. stored_ams_mapping = data.get("ams_mapping")
  8249. # Fallback to _print_ams_mappings for queue/reprint (set before print starts).
  8250. # Drained either way, like the plate below: left over, it would be read by
  8251. # the archive's next run, dispatched without a mapping.
  8252. registered_ams_mapping = _print_ams_mappings.pop((printer_id, archive_id), None) if archive_id else None
  8253. if not stored_ams_mapping:
  8254. stored_ams_mapping = registered_ams_mapping
  8255. # Always drain the plate_id register on completion — the session already
  8256. # consumed it at print-start injection; leaving it would leak into the next
  8257. # print on the same archive_id (rare but possible with reprints) (#1697).
  8258. # Capture the popped value so the completion notification can scope the
  8259. # archive-level (summed-across-plates per #1593) filament + time totals
  8260. # down to the single plate that was actually printed (#1785).
  8261. notify_plate_id: int | None = None
  8262. if archive_id:
  8263. notify_plate_id = _print_plate_ids.pop((printer_id, archive_id), None)
  8264. # The start estimate must not outlive the real cost written below (COST-4).
  8265. if archive_id:
  8266. await _settle_archive_cost_estimate(archive_id)
  8267. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  8268. try:
  8269. async with async_session() as db:
  8270. from backend.app.api.routes.settings import get_setting
  8271. _spoolman_on = await get_setting(db, "spoolman_enabled")
  8272. if not _spoolman_on or _spoolman_on.lower() != "true":
  8273. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  8274. async with async_session() as db:
  8275. usage_results = await usage_on_print_complete(
  8276. printer_id,
  8277. data,
  8278. printer_manager,
  8279. db,
  8280. archive_id=archive_id,
  8281. ams_mapping=stored_ams_mapping,
  8282. )
  8283. if usage_results:
  8284. await ws_manager.broadcast(
  8285. {
  8286. "type": "spool_usage_logged",
  8287. "printer_id": printer_id,
  8288. "usage": usage_results,
  8289. }
  8290. )
  8291. log_timing("Usage tracker")
  8292. except Exception as e:
  8293. logger.warning("Usage tracker on_print_complete failed: %s", e)
  8294. # Drop the print-start context unconditionally — the Spoolman branch above
  8295. # skips the internal tracker entirely, so nothing else would clear what
  8296. # print start captured, and a row surviving its print would be restored
  8297. # onto the next one after a restart.
  8298. try:
  8299. from backend.app.services.usage_tracker import discard_session
  8300. async with async_session() as db:
  8301. await discard_session(db, printer_id)
  8302. except Exception as e:
  8303. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  8304. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  8305. # A partial run's cost from the Spoolman spools it was charged to; the
  8306. # built-in inventory's comes in usage_results.
  8307. spoolman_run_cost: float | None = None
  8308. if archive_id:
  8309. if data.get("status") == "completed":
  8310. try:
  8311. await _report_spoolman_usage(printer_id, archive_id)
  8312. log_timing("Spoolman usage report")
  8313. except Exception as e:
  8314. logger.warning("Spoolman usage reporting failed: %s", e)
  8315. else:
  8316. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  8317. try:
  8318. async with async_session() as db:
  8319. spoolman_run_cost = await _cleanup_spoolman_tracking(
  8320. printer_id,
  8321. archive_id,
  8322. db,
  8323. last_layer_num=data.get("last_layer_num"),
  8324. last_progress=data.get("last_progress"),
  8325. status=data.get("status") or "failed",
  8326. )
  8327. except Exception as e:
  8328. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  8329. await _release_archived_spoolman_slots(printer_id)
  8330. log_timing("Filament usage tracking")
  8331. if not archive_id:
  8332. # The printer's own calibration run has no archive by design, so this
  8333. # arrives here every time one finishes. Returning before the no-archive
  8334. # notification keeps a calibration from being announced as a finished
  8335. # print. Everything above this point has already run — the plate-clear
  8336. # gate, the queue reconciliation, the SD-card cleanup — so only the
  8337. # notification is skipped.
  8338. if is_internal_printer_job(filename, subtask_name):
  8339. logger.info(
  8340. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  8341. filename,
  8342. subtask_name,
  8343. )
  8344. return
  8345. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  8346. # Still send print-complete/failed/stopped notifications even without an archive.
  8347. # Try to enrich with queue/library-file data so user-specific emails work too.
  8348. async def _notify_no_archive():
  8349. try:
  8350. async with async_session() as db:
  8351. from backend.app.models.library import LibraryFile
  8352. from backend.app.models.print_queue import PrintQueueItem
  8353. from backend.app.models.printer import Printer
  8354. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8355. printer_obj = result.scalar_one_or_none()
  8356. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  8357. # Only the queue item this completion itself closed (the
  8358. # reconciliation above, which checks the run belongs to it).
  8359. # A print started outside Bambuddy closed none, and must not
  8360. # borrow an earlier job's owner, email or times.
  8361. no_archive_data: dict | None = None
  8362. try:
  8363. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  8364. if queue_item:
  8365. no_archive_data = {"created_by_id": queue_item.created_by_id}
  8366. # How long it really ran, as the archive path reports it (#1198).
  8367. started = to_naive_utc(queue_item.started_at)
  8368. ended = to_naive_utc(queue_item.completed_at)
  8369. # Not for a completion reconciled at reconnect: it
  8370. # ended at an unknown time while the printer was
  8371. # offline, and "now" is the reconnect (DB-C9).
  8372. if (
  8373. not data.get("_reconciled")
  8374. and started
  8375. and ended
  8376. and (ended - started).total_seconds() > 0
  8377. ):
  8378. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  8379. # Estimated time: the queue item caches it from its
  8380. # archive or library file; otherwise read the library
  8381. # file's metadata (LibraryFile has no column for it).
  8382. if queue_item.print_time_seconds:
  8383. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  8384. elif queue_item.library_file_id:
  8385. lib_result = await db.execute(
  8386. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  8387. )
  8388. lib_file = lib_result.scalar_one_or_none()
  8389. estimate = (
  8390. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  8391. )
  8392. if estimate:
  8393. no_archive_data["print_time_seconds"] = estimate
  8394. except Exception as lookup_err:
  8395. logger.debug(
  8396. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  8397. )
  8398. # Enrich with usage tracker results (captured in enclosing scope)
  8399. if usage_results:
  8400. if no_archive_data is None:
  8401. no_archive_data = {}
  8402. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8403. if total_from_usage > 0:
  8404. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8405. no_archive_data["usage_results"] = usage_results
  8406. # Try MQTT remaining_time for print duration when no queue/library data
  8407. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  8408. mqtt_remaining = data.get("remaining_time")
  8409. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  8410. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  8411. ps = data.get("status", "completed")
  8412. logger.info(
  8413. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  8414. )
  8415. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8416. await notification_service.on_print_complete(
  8417. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  8418. )
  8419. else:
  8420. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8421. # Send user-specific email if we have a created_by_id
  8422. if no_archive_data and no_archive_data.get("created_by_id"):
  8423. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8424. await _dispatch_user_print_email(
  8425. ps,
  8426. no_archive_data["created_by_id"],
  8427. p_name,
  8428. raw_filename,
  8429. db,
  8430. )
  8431. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  8432. except Exception as e:
  8433. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  8434. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  8435. return
  8436. log_timing("Archive lookup")
  8437. # Update archive status
  8438. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  8439. try:
  8440. async with async_session() as db:
  8441. service = ArchiveService(db)
  8442. status = data.get("status", "completed")
  8443. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  8444. if hms_errors:
  8445. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  8446. failure_reason = derive_failure_reason(status, hms_errors)
  8447. if data.get("_reconciled") and (status == "aborted" or (status == "failed" and not failure_reason)):
  8448. # A reconciled completion closes out a stale archive at
  8449. # reconnect — it is not a user action, so don't mislabel it
  8450. # "userCancelled". It shares the stale-cleanup path's key
  8451. # (issue #2974) and records that the real end time is unknown,
  8452. # which is also why its logged duration is 0 (#2592). A failed
  8453. # one the printer's errors explain keeps their reason (#3310).
  8454. failure_reason = "noStatusUpdate"
  8455. elif data.get("_kill_switch"):
  8456. # Not the user's cancel: the kill switch stopped a print that did
  8457. # not come from Bambuddy.
  8458. failure_reason = "killSwitch"
  8459. if failure_reason:
  8460. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  8461. elif status == "failed" and hms_errors:
  8462. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  8463. await service.update_archive_status(
  8464. archive_id,
  8465. status=status,
  8466. completed_at=(
  8467. # A reconciled completed print ended at an estimated time,
  8468. # not at the reconnect (#3310).
  8469. data.get("_reconciled_completed_at") or datetime.now(timezone.utc)
  8470. if status in ("completed", "failed", "aborted", "cancelled")
  8471. else None
  8472. ),
  8473. failure_reason=failure_reason,
  8474. )
  8475. logger.info(
  8476. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  8477. )
  8478. await ws_manager.send_archive_updated(
  8479. {
  8480. "id": archive_id,
  8481. "status": status,
  8482. }
  8483. )
  8484. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  8485. # MQTT relay - publish archive updated
  8486. try:
  8487. await mqtt_relay.on_archive_updated(
  8488. archive_id=archive_id,
  8489. print_name=filename or subtask_name,
  8490. status=status,
  8491. )
  8492. except Exception:
  8493. pass # Don't fail if MQTT fails
  8494. except Exception as e:
  8495. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  8496. # Continue with other operations even if archive update fails
  8497. log_timing("Archive status update")
  8498. # Apply finance wallet charge or release reservations once. For all partial
  8499. # terminal states (failed, aborted at the printer display, or cancelled via
  8500. # Bambuddy) use this run's measured spool delta, falling back to the last
  8501. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  8502. # estimate and therefore cannot represent an interrupted run.
  8503. try:
  8504. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  8505. async with async_session() as db:
  8506. from backend.app.models.archive import PrintArchive
  8507. from backend.app.services.finance_billing import apply_print_charge_for_archive
  8508. from backend.app.services.print_log import run_being_ended
  8509. archive = await db.get(PrintArchive, archive_id)
  8510. # The run this end fills in below: charged as its own, not as
  8511. # the archive's latest dispatch (another plate of it, maybe).
  8512. charged_run = await run_being_ended(db, archive_id, printer_id, archive.started_at) if archive else None
  8513. if archive and billing_run_id is None and charged_run is None:
  8514. billing_run_id = getattr(archive, "billing_run_id", None)
  8515. if archive and archive.created_by_id is None and _print_user_info:
  8516. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  8517. await db.flush()
  8518. run_status = data.get("status", "completed")
  8519. last_progress = data.get("last_progress")
  8520. if last_progress is None:
  8521. last_progress = data.get("progress")
  8522. actual_run_grams = _compute_run_filament_grams(
  8523. run_status,
  8524. billing_planned_grams,
  8525. last_progress,
  8526. usage_results,
  8527. )
  8528. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  8529. in_memory_cost_center_id = _print_cost_center_ids.pop((printer_id, archive_id), None)
  8530. charged = await apply_print_charge_for_archive(
  8531. db,
  8532. archive_id,
  8533. charged_user_id=billing_user_id,
  8534. cost_center_id=(
  8535. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  8536. ),
  8537. print_queue_id=queue_item_id,
  8538. print_run_id=billing_run_id,
  8539. base_cost_override=billing_base_cost,
  8540. filament_usage=filament_usage,
  8541. run_entry_id=charged_run.id if charged_run is not None else None,
  8542. run_status=run_status,
  8543. )
  8544. await db.commit()
  8545. if charged:
  8546. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  8547. except Exception as e:
  8548. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  8549. printer_info = printer_manager.get_printer(printer_id)
  8550. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8551. billing_filename = filename or subtask_name or "Unknown"
  8552. billing_error = str(e)
  8553. try:
  8554. await ws_manager.broadcast(
  8555. {
  8556. "type": "billing_charge_failed",
  8557. "printer_id": printer_id,
  8558. "printer_name": billing_printer_name,
  8559. "filename": billing_filename,
  8560. "archive_id": archive_id,
  8561. }
  8562. )
  8563. except Exception as notification_error:
  8564. logger.error(
  8565. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  8566. archive_id,
  8567. notification_error,
  8568. )
  8569. async def _notify_billing_charge_failed() -> None:
  8570. try:
  8571. async with async_session() as notification_db:
  8572. await notification_service.on_billing_charge_failed(
  8573. printer_id,
  8574. billing_printer_name,
  8575. billing_filename,
  8576. archive_id,
  8577. billing_error,
  8578. notification_db,
  8579. )
  8580. except Exception as provider_error:
  8581. logger.error(
  8582. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  8583. archive_id,
  8584. provider_error,
  8585. exc_info=True,
  8586. )
  8587. spawn_background_task(
  8588. _notify_billing_charge_failed(),
  8589. name=f"billing-charge-failed-{archive_id}",
  8590. )
  8591. log_timing("Finance charge update")
  8592. # Write independent print log entry (separate table, never touches archives)
  8593. # The run's id, for the energy work below: the archive's newest run is
  8594. # the one started last, which with plates of it on two printers need not
  8595. # be the one that just ended.
  8596. completed_run_id: int | None = None
  8597. async def _write_run(db):
  8598. # Retried on a locked SQLite database: a run left open here would be
  8599. # closed again by the next reconnect's reconcile.
  8600. nonlocal completed_run_id
  8601. from backend.app.models.archive import PrintArchive
  8602. from backend.app.services.print_log import discard_open_runs, record_archive_wear, write_log_entry
  8603. archive = await db.get(PrintArchive, archive_id)
  8604. if archive is None:
  8605. # Deleted while it printed: its run has nothing left to end on.
  8606. await discard_open_runs(db, printer_id)
  8607. await db.commit()
  8608. if archive:
  8609. # Back-fill created_by_id on reprint (#730): reprint reuses the
  8610. # source archive row rather than creating a new one, so an
  8611. # archive that was auto-created from a printer-initiated
  8612. # print (created_by_id=NULL) would otherwise stay unattributed
  8613. # forever. When we have a print-session user AND the archive
  8614. # has no attribution yet, credit the current user. Never
  8615. # overwrite an existing attribution — the original uploader
  8616. # keeps ownership.
  8617. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  8618. if archive.created_by_id is None and _print_user_id is not None:
  8619. archive.created_by_id = _print_user_id
  8620. p_info = printer_manager.get_printer(printer_id)
  8621. # Per-run actuals — written to PrintLogEntry so stats reflect
  8622. # what THIS print actually used, not the source archive's
  8623. # first-run values (#1378). Helper handles the partial-print
  8624. # math (failed / cancelled / stopped get scaled to progress
  8625. # or to tracked spool deltas).
  8626. _run_status = data.get("status", "completed")
  8627. # #2614: scope the per-run estimate to the printed plate. For a
  8628. # multi-plate 3MF dispatched one plate at a time, the archive's
  8629. # filament/cost are the whole-file totals; the PrintLogEntry must
  8630. # reflect only this plate. No effect on single-plate archives (the
  8631. # plate estimate equals the whole-file value) or on the tracker
  8632. # path (measured spool deltas win in _compute_run_filament_grams).
  8633. _est_full_path = (
  8634. app_settings.base_dir / archive.file_path if archive.file_path else None
  8635. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8636. # The plate that printed, as billing reads it: a reprint of
  8637. # another plate must not log the archive's first plate.
  8638. _run_plate_id = billing_plate_id if billing_plate_id is not None else notify_plate_id
  8639. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path, _run_plate_id)
  8640. if _run_plate_id is None:
  8641. _run_plate_id = archive.plate_id
  8642. _run_grams = _compute_run_filament_grams(
  8643. _run_status,
  8644. _est_grams,
  8645. data.get("last_progress", data.get("progress")),
  8646. usage_results,
  8647. )
  8648. # Per-run cost — prefer usage_results sum. For partial prints
  8649. # we deliberately skip the topup-to-estimate logic in
  8650. # usage_tracker (which assumes the print completed); the raw
  8651. # tracked-spool sum is closer to what THIS run actually cost.
  8652. _run_cost: float | None = None
  8653. if usage_results:
  8654. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  8655. if _run_cost is None and _run_status != "completed":
  8656. _run_cost = spoolman_run_cost
  8657. if _run_cost is None and _run_status == "completed":
  8658. _run_cost = _est_cost
  8659. from backend.app.models.printer import Printer as _Printer
  8660. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  8661. run_entry = await write_log_entry(
  8662. db,
  8663. archive_id=archive.id,
  8664. # Captured by _update_queue_status above; None for
  8665. # printer-initiated prints with no queue row. Batch
  8666. # cost/energy roll-up joins on it (#342).
  8667. queue_item_id=queue_item_id,
  8668. status=_run_status,
  8669. print_name=archive.print_name,
  8670. # The plate this run printed, as the estimate above takes
  8671. # it; the archive's own is the latest run's.
  8672. plate_id=_run_plate_id,
  8673. printer_name=p_info.name if p_info else None,
  8674. printer_id=printer_id,
  8675. started_at=archive.started_at,
  8676. completed_at=archive.completed_at,
  8677. filament_type=archive.filament_type,
  8678. filament_color=archive.filament_color,
  8679. filament_used_grams=_run_grams,
  8680. cost=_run_cost,
  8681. wear_cost_per_hour=_wear_rate,
  8682. failure_reason=archive.failure_reason,
  8683. thumbnail_path=archive.thumbnail_path,
  8684. created_by_id=archive.created_by_id,
  8685. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  8686. # Reconciled completions have an unknown real end time —
  8687. # log 0 duration instead of the whole disconnect gap (#2592),
  8688. # unless it was estimated (#3310).
  8689. reconciled=bool(data.get("_reconciled")) and not data.get("_reconciled_completed_at"),
  8690. # Its time is the estimate or nothing, never measured (#3310).
  8691. duration_unmeasured=bool(data.get("_reconciled")),
  8692. # The real end of a print stopped while its printer was offline.
  8693. replaces_offline_stop=True,
  8694. )
  8695. await record_archive_wear(db, archive, run_entry)
  8696. await db.commit()
  8697. completed_run_id = run_entry.id
  8698. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  8699. try:
  8700. from backend.app.core.database import run_with_retry
  8701. await run_with_retry(_write_run, label="print log entry")
  8702. except Exception as e:
  8703. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  8704. log_timing("Print log entry")
  8705. # Run slow operations as background tasks to avoid blocking the event loop
  8706. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  8707. async def _background_energy_calculation():
  8708. """Calculate and save energy usage in background.
  8709. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  8710. backend restart no longer loses per-print energy data).
  8711. """
  8712. try:
  8713. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  8714. async with async_session() as db:
  8715. from backend.app.models.archive import PrintArchive
  8716. from backend.app.models.print_log import PrintLogEntry
  8717. from backend.app.services.print_log import energy_start_of
  8718. archive = await db.get(PrintArchive, archive_id)
  8719. if archive is None:
  8720. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  8721. return
  8722. # The ended run's own start reading: the archive's is its
  8723. # latest start's, maybe another plate's on another printer.
  8724. run_row = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  8725. start = energy_start_of(run_row, archive)
  8726. if start is None:
  8727. logger.info("[ENERGY-BG] No start kWh recorded for archive %s's run", archive_id)
  8728. return
  8729. starting_kwh = start.kwh
  8730. candidates = await energy_plug_candidates(db, printer_id)
  8731. if not candidates:
  8732. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  8733. return
  8734. # Same ordering as the start reading, so the delta below is
  8735. # against the counter that produced `starting_kwh` (#2859).
  8736. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  8737. if selected is None:
  8738. logger.warning(
  8739. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  8740. printer_id,
  8741. ", ".join(plug.name for plug in candidates),
  8742. )
  8743. return
  8744. plug, energy = selected
  8745. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  8746. energy_used = round(energy["total"] - starting_kwh, 4)
  8747. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  8748. if energy_used < 0:
  8749. logger.warning(
  8750. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  8751. archive_id,
  8752. starting_kwh,
  8753. energy["total"],
  8754. )
  8755. return
  8756. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  8757. # Each hour of the print at the price of that hour (#1251). If
  8758. # that fails, the last price known, as before, rather than no
  8759. # energy at all. Read first: the session may be unusable after.
  8760. last_price = await stored_price(db)
  8761. try:
  8762. energy_cost_value = round(
  8763. await print_energy_cost(
  8764. db,
  8765. plug_id=start.plug_id,
  8766. start_at=start.at,
  8767. start_kwh=starting_kwh,
  8768. start_price=start.price,
  8769. end_kwh=energy["total"],
  8770. end_plug_id=plug.id,
  8771. price_now=await current_price(db),
  8772. ),
  8773. 3,
  8774. )
  8775. except Exception as e:
  8776. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  8777. energy_cost_value = round(energy_used * last_price, 3)
  8778. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  8779. # reprint doesn't visually clobber the source archive's energy data
  8780. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  8781. from sqlalchemy import func
  8782. existing_runs = await db.scalar(
  8783. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  8784. )
  8785. if (existing_runs or 0) <= 1:
  8786. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  8787. # we just wrote for THIS print. Either way it's the first run.
  8788. archive.energy_kwh = energy_used
  8789. archive.energy_cost = energy_cost_value
  8790. # The ended run's energy (write_log_entry above ran before this
  8791. # background task, so its energy fields are still NULL). With
  8792. # no run written, none: the archive's newest is another print's.
  8793. if run_row is not None:
  8794. run_row.energy_kwh = energy_used
  8795. run_row.energy_cost = energy_cost_value
  8796. await db.commit()
  8797. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  8798. except Exception as e:
  8799. logger.warning("[ENERGY-BG] Failed: %s", e)
  8800. async def _background_finish_photo() -> str | None:
  8801. """Capture finish photo in background. Returns photo filename if captured."""
  8802. # #2547: set once this function has raised the plate itself (the
  8803. # timelapse path, where the moment producer returned without doing it).
  8804. # Declared out here so the `finally` can lower it again no matter where
  8805. # the capture below fails.
  8806. plate_restored_z: float | None = None
  8807. try:
  8808. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  8809. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  8810. # Read phase: settings + printer + archive in a short session, released
  8811. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  8812. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  8813. # tens of seconds; holding this session across it pinned one pooled
  8814. # connection idle-in-transaction per finishing print (issue #2572).
  8815. async with async_session() as db:
  8816. from backend.app.api.routes.settings import get_setting
  8817. from backend.app.models.archive import PrintArchive
  8818. from backend.app.models.printer import Printer
  8819. capture_enabled = await get_setting(db, "capture_finish_photo")
  8820. if capture_enabled is not None and capture_enabled.lower() != "true":
  8821. return None
  8822. if not archive_id:
  8823. return None
  8824. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  8825. archive = (
  8826. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8827. ).scalar_one_or_none()
  8828. if not printer or not archive:
  8829. return None
  8830. import uuid
  8831. from datetime import datetime
  8832. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  8833. if not archive.file_path:
  8834. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  8835. archive_dir = resolve_archive_dir(archive)
  8836. photo_filename = None
  8837. # Prefer the timelapse last-frame source when a timelapse was
  8838. # recording — it captures the moment after the toolhead parks
  8839. # but before the bed drops, which the live-camera grab below
  8840. # would miss (#1397). Skipped for external cameras (those have
  8841. # their own framing and don't see a Bambu timelapse). Only
  8842. # runs when the USER explicitly enabled timelapse for this
  8843. # print — #1721 removed Bambuddy's force-on at dispatch
  8844. # because it caused per-layer nozzle parking on Smooth-mode
  8845. # slicer profiles.
  8846. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  8847. printer.external_camera_enabled and printer.external_camera_url
  8848. )
  8849. timelapse_still_pending = False
  8850. if prefer_timelapse_source:
  8851. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  8852. archive_id=archive_id,
  8853. archive_dir=archive_dir,
  8854. rotation=getattr(printer, "camera_rotation", 0),
  8855. )
  8856. # #1721: replacement framing path — on_finish_photo_moment
  8857. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  8858. # parked, bed not yet dropped) and cached the JPEG bytes in
  8859. # _stage22_finish_frames. Consume them now so the saved photo
  8860. # has the better framing instead of the post-bed-drop angle
  8861. # the live-camera fallback below would give.
  8862. if not photo_filename:
  8863. # #1790: on the FINISH-state fallback path the producer
  8864. # task is dispatched back-to-back with this consumer, so
  8865. # a bare pop would race past with an empty result and
  8866. # the RTSP fallback below would collide with the
  8867. # producer's still-in-flight grab (single-client RTSP
  8868. # on Bambu printers). Wait for the producer to finish
  8869. # or give up before touching the cache.
  8870. #
  8871. # #2547: 20s was enough when the producer only ever grabbed a
  8872. # frame. It now also raises the plate first, which costs the
  8873. # settle window before the grab even starts — so the budget has
  8874. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  8875. # under the notification's own photo wait below.
  8876. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  8877. if in_flight is not None:
  8878. try:
  8879. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  8880. except TimeoutError:
  8881. logger.warning(
  8882. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  8883. printer_id,
  8884. )
  8885. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  8886. if cached_frame:
  8887. # Already rotated by the producer (#2708) — rotating again
  8888. # here would undo the fix on the banked-frame path, whose
  8889. # bytes reach the cache having been rotated once already.
  8890. photos_dir = archive_dir / "photos"
  8891. photos_dir.mkdir(parents=True, exist_ok=True)
  8892. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8893. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8894. photo_path = photos_dir / photo_filename
  8895. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  8896. logger.info(
  8897. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  8898. photo_filename,
  8899. len(cached_frame),
  8900. )
  8901. # #2547: the timelapse path reaches the live grab below whenever the
  8902. # video hasn't landed in time — the documented usual outcome on
  8903. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  8904. # returned early for those prints without raising the plate, so
  8905. # without this the photo that actually ships in the notification is
  8906. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  8907. # asked us to fix. The archive still gets the better video frame
  8908. # later; this is about the image the user is sent.
  8909. #
  8910. # Gated on `timelapse_was_active` precisely because that is the
  8911. # condition under which the producer skipped. On every other path it
  8912. # has already raised and lowered the plate, and repeating that here
  8913. # would be a second pointless round trip.
  8914. if (
  8915. not photo_filename
  8916. and data.get("timelapse_was_active")
  8917. and not print_dispatch_context.end_gcode_injected(printer_id)
  8918. ):
  8919. try:
  8920. async with async_session() as db:
  8921. from backend.app.api.routes.settings import get_setting
  8922. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  8923. if restore_setting is None or restore_setting.lower() == "true":
  8924. max_z = await _max_z_for_current_print(
  8925. printer_id, data, logger, bound_archive_id, notify_plate_id
  8926. )
  8927. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  8928. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  8929. plate_restored_z = max_z
  8930. except Exception as e:
  8931. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  8932. # Fallback chain: external camera → buffered live frame →
  8933. # fresh RTSP capture. Only runs if the timelapse path above
  8934. # didn't already produce a photo.
  8935. # Chamber light for the live capture below (#1655).
  8936. async with camera_light(printer if not photo_filename else None):
  8937. if not photo_filename:
  8938. if printer.external_camera_enabled and printer.external_camera_url:
  8939. logger.info("[PHOTO-BG] Using external camera")
  8940. from backend.app.api.routes.camera import live_frame_for_capture
  8941. from backend.app.services.external_camera import capture_frame
  8942. # #2707: the second half of the finish-photo failure — the
  8943. # pre-capture and this fallback both collided with the live
  8944. # view. None here continues down the fallback chain.
  8945. defer, buffered = live_frame_for_capture(printer_id)
  8946. if defer:
  8947. frame_data = buffered
  8948. else:
  8949. frame_data = await capture_frame(
  8950. printer.external_camera_url,
  8951. printer.external_camera_type or "mjpeg",
  8952. snapshot_url=printer.external_camera_snapshot_url,
  8953. )
  8954. if frame_data:
  8955. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  8956. photos_dir = archive_dir / "photos"
  8957. photos_dir.mkdir(parents=True, exist_ok=True)
  8958. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8959. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8960. photo_path = photos_dir / photo_filename
  8961. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  8962. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  8963. else:
  8964. # Check if camera stream is active - use buffered frame to avoid freeze
  8965. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  8966. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  8967. active_chamber_for_printer = [
  8968. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  8969. ]
  8970. buffered_frame = get_buffered_frame(printer_id)
  8971. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  8972. # Use frame from active stream
  8973. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  8974. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  8975. photos_dir = archive_dir / "photos"
  8976. photos_dir.mkdir(parents=True, exist_ok=True)
  8977. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8978. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8979. photo_path = photos_dir / photo_filename
  8980. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  8981. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  8982. else:
  8983. # No active stream - capture new frame
  8984. from backend.app.services.camera import capture_finish_photo
  8985. photo_filename = await capture_finish_photo(
  8986. printer_id=printer_id,
  8987. ip_address=printer.ip_address,
  8988. access_code=printer.access_code,
  8989. model=printer.model,
  8990. archive_dir=archive_dir,
  8991. rotation=getattr(printer, "camera_rotation", 0),
  8992. )
  8993. # Write phase: attach the photo in a fresh short-lived session.
  8994. if photo_filename:
  8995. async with async_session() as db:
  8996. from backend.app.models.archive import PrintArchive
  8997. arch = await db.get(PrintArchive, archive_id)
  8998. if arch is not None:
  8999. photos = arch.photos or []
  9000. photos.append(photo_filename)
  9001. arch.photos = photos
  9002. await db.commit()
  9003. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  9004. # The short wait above is bounded so a slow printer can't hold up
  9005. # the print-complete notification, which is what the caller is
  9006. # blocking on. When it ran out with the video still on its way,
  9007. # keep waiting off to the side and add the better frame to the
  9008. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  9009. # users, whose videos routinely take minutes to transfer, never get
  9010. # the pre-bed-drop framing this path exists to provide.
  9011. #
  9012. # Spawned here rather than at the point the wait gave up: both this
  9013. # function and the upgrade do a read-modify-write on `photos`, and
  9014. # the live-camera fallback above can take tens of seconds. Starting
  9015. # the upgrade before that write means the two can interleave and one
  9016. # silently drops the other's entry, leaving a JPEG on disk that the
  9017. # gallery never lists.
  9018. if timelapse_still_pending:
  9019. spawn_background_task(
  9020. _upgrade_finish_photo_from_timelapse(
  9021. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  9022. ),
  9023. name=f"finish-photo-upgrade-{archive_id}",
  9024. )
  9025. return photo_filename
  9026. except Exception as e:
  9027. logger.warning("[PHOTO-BG] Failed: %s", e)
  9028. return None
  9029. finally:
  9030. # #2547: we raised the plate, so we owe the move back down — even if
  9031. # the capture in between threw. Otherwise the user finds the print
  9032. # pinned under the nozzle.
  9033. if plate_restored_z is not None:
  9034. try:
  9035. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  9036. except Exception as e:
  9037. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  9038. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  9039. # Photo capture task - result will be used by notifications
  9040. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  9041. log_timing("Background tasks scheduled (energy, photo)")
  9042. # Also run smart plug, notifications, and maintenance as background tasks
  9043. print_status = data.get("status", "completed")
  9044. async def _background_smart_plug():
  9045. """Handle smart plug automation in background."""
  9046. try:
  9047. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  9048. async with async_session() as db:
  9049. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  9050. logger.info("[AUTO-OFF-BG] Completed")
  9051. except Exception as e:
  9052. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  9053. async def _background_notifications(finish_photo_filename: str | None = None):
  9054. """Send print complete notifications in background."""
  9055. try:
  9056. logger.info(
  9057. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  9058. )
  9059. async with async_session() as db:
  9060. from backend.app.models.archive import PrintArchive
  9061. from backend.app.models.printer import Printer
  9062. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9063. printer = result.scalar_one_or_none()
  9064. printer_name = printer.name if printer else f"Printer {printer_id}"
  9065. archive_data = None
  9066. if archive_id:
  9067. from backend.app.models.print_log import PrintLogEntry
  9068. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  9069. archive = archive_result.scalar_one_or_none()
  9070. # The run that ended: the archive shows its latest, which
  9071. # with another plate of it printing elsewhere is not this.
  9072. run = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  9073. run_started = run.started_at if run is not None else archive.started_at if archive else None
  9074. run_completed = run.completed_at if run is not None else archive.completed_at if archive else None
  9075. if archive:
  9076. # Actual elapsed time from started_at/completed_at when both are
  9077. # populated (every terminal status sets completed_at after #1198).
  9078. # Falls back to None so the notification path can decide whether to
  9079. # render the slicer estimate as a last resort.
  9080. actual_time_seconds = None
  9081. # Unknown for a completion reconciled at reconnect: the
  9082. # print ended while the printer was offline and
  9083. # completed_at is the reconnect, so the gap would read
  9084. # as the duration -- 14 h for a night offline (DB-C9).
  9085. # An estimated end (#3310) gives the estimate.
  9086. if (
  9087. run_started
  9088. and run_completed
  9089. and (not data.get("_reconciled") or data.get("_reconciled_completed_at"))
  9090. ):
  9091. elapsed = (run_completed - run_started).total_seconds()
  9092. if elapsed > 0:
  9093. actual_time_seconds = int(elapsed)
  9094. archive_data = {
  9095. "print_time_seconds": archive.print_time_seconds,
  9096. "actual_time_seconds": actual_time_seconds,
  9097. "actual_filament_grams": archive.filament_used_grams,
  9098. "failure_reason": run.failure_reason if run is not None else archive.failure_reason,
  9099. "created_by_id": archive.created_by_id,
  9100. }
  9101. # Scale filament usage for partial prints
  9102. if print_status != "completed" and archive.filament_used_grams:
  9103. progress = data.get("progress") or 0
  9104. scale = _partial_progress_scale(progress)
  9105. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  9106. archive_data["progress"] = progress
  9107. # Pass per-slot data from archive.extra_data
  9108. if archive.extra_data and archive.extra_data.get("filament_slots"):
  9109. slots = archive.extra_data["filament_slots"]
  9110. if print_status != "completed":
  9111. scale = _partial_progress_scale(data.get("progress"))
  9112. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  9113. archive_data["filament_slots"] = slots
  9114. # Scope project-summed totals down to the plate that was
  9115. # actually printed — see _scope_notification_archive_data_to_plate
  9116. # for the why (#1785).
  9117. archive_data = _scope_notification_archive_data_to_plate(
  9118. archive_data,
  9119. archive.file_path,
  9120. notify_plate_id,
  9121. print_status,
  9122. data.get("progress"),
  9123. app_settings.base_dir,
  9124. )
  9125. # Enrich filament_grams from usage_results when archive has no 3MF data
  9126. if not archive_data.get("actual_filament_grams") and usage_results:
  9127. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  9128. if total_from_usage > 0:
  9129. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  9130. # Pass usage tracker results for AMS slot info in notifications
  9131. if usage_results:
  9132. archive_data["usage_results"] = usage_results
  9133. # Add finish photo URL and image bytes if available
  9134. if finish_photo_filename:
  9135. photo_url, photo_bytes = await _finish_photo_for_notification(
  9136. db, archive, archive_id, finish_photo_filename
  9137. )
  9138. if photo_url:
  9139. archive_data["finish_photo_url"] = photo_url
  9140. if photo_bytes:
  9141. archive_data["image_data"] = photo_bytes
  9142. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  9143. await notification_service.on_print_complete(
  9144. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  9145. )
  9146. else:
  9147. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  9148. # Post-print outcome confirmation (#1898). Runs in this
  9149. # background task so the finish photo fetched above rides
  9150. # along with the prompt.
  9151. if print_status == "completed" and archive_id:
  9152. await _dispatch_outcome_confirmation_safely(
  9153. db, printer_id, printer_name, data, archive_id, archive_data, run_id=completed_run_id
  9154. )
  9155. # Send user-specific email notification
  9156. if archive_data:
  9157. created_by_id = archive_data.get("created_by_id")
  9158. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  9159. await _dispatch_user_print_email(
  9160. print_status,
  9161. created_by_id,
  9162. printer_name,
  9163. raw_filename,
  9164. db,
  9165. image_data=archive_data.get("image_data"),
  9166. finish_photo_url=archive_data.get("finish_photo_url"),
  9167. )
  9168. logger.info("[NOTIFY-BG] Completed")
  9169. except Exception as e:
  9170. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  9171. async def _background_maintenance_check():
  9172. """Check for maintenance due in background."""
  9173. if print_status != "completed":
  9174. return
  9175. try:
  9176. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  9177. async with async_session() as db:
  9178. from backend.app.models.printer import Printer
  9179. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9180. printer = result.scalar_one_or_none()
  9181. printer_name = printer.name if printer else f"Printer {printer_id}"
  9182. await ensure_default_types(db)
  9183. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  9184. attention = [
  9185. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  9186. ]
  9187. items_needing_attention = [
  9188. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  9189. for item in attention
  9190. ]
  9191. if items_needing_attention:
  9192. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  9193. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  9194. # MQTT relay - publish maintenance alerts
  9195. for item in attention:
  9196. current_value, threshold, unit = maintenance_alert_values(item)
  9197. try:
  9198. await mqtt_relay.on_maintenance_alert(
  9199. printer_id=printer_id,
  9200. printer_name=printer_name,
  9201. maintenance_type=item.maintenance_type_name,
  9202. current_value=current_value,
  9203. threshold=threshold,
  9204. unit=unit,
  9205. )
  9206. except Exception:
  9207. pass # Don't fail if MQTT fails
  9208. else:
  9209. logger.info("[MAINT-BG] Completed (no items need attention)")
  9210. except Exception as e:
  9211. logger.warning("[MAINT-BG] Failed: %s", e)
  9212. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  9213. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  9214. # Notification task waits for photo capture to complete first (with timeout).
  9215. # When a timelapse was recording, photo sourcing polls the per-print
  9216. # timelapse for up to 60s (#1397) — extend the budget so the notification
  9217. # carries the correct bed-up photo instead of falling through to the
  9218. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  9219. #
  9220. # #2547: both budgets now have to cover a plate restore as well.
  9221. #
  9222. # Without timelapse, the wait is on the moment producer, which raises the
  9223. # plate before its grab — so this has to outlast that producer's own budget.
  9224. #
  9225. # With timelapse, the capture polls up to
  9226. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  9227. # falls back to a live grab, which is the case that raises the plate. At the
  9228. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  9229. # restore would have moved the plate for a photo nobody waited for.
  9230. photo_wait_timeout = (
  9231. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  9232. if data.get("timelapse_was_active")
  9233. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  9234. )
  9235. async def _photo_then_notify():
  9236. """Wait for photo capture, then send notification with photo URL."""
  9237. finish_photo = None
  9238. try:
  9239. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  9240. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  9241. except TimeoutError:
  9242. logger.warning(
  9243. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  9244. photo_wait_timeout,
  9245. )
  9246. except Exception as e:
  9247. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  9248. try:
  9249. await _background_notifications(finish_photo)
  9250. except Exception as e:
  9251. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  9252. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  9253. # Stitch external camera layer timelapse if session was active
  9254. print_status = data.get("status", "completed")
  9255. async def _background_layer_timelapse():
  9256. """Stitch layer timelapse and attach to archive."""
  9257. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  9258. try:
  9259. if print_status == "completed":
  9260. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  9261. # The run the frames belong to, read before the stitch: it can
  9262. # take long enough for the archive to start printing again.
  9263. run_started_at = None
  9264. if archive_id:
  9265. async with async_session() as db:
  9266. run_archive = await ArchiveService(db).get_archive(archive_id)
  9267. run_started_at = run_archive.started_at if run_archive else None
  9268. timelapse_path = await tl_complete(printer_id)
  9269. if timelapse_path and archive_id:
  9270. await _attach_layer_timelapse(archive_id, timelapse_path, notify_plate_id, run_started_at)
  9271. elif timelapse_path:
  9272. # Timelapse created but no archive - just clean up
  9273. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  9274. else:
  9275. # Print failed or cancelled - cancel timelapse session
  9276. cancel_session(printer_id)
  9277. logger.info(
  9278. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  9279. )
  9280. except Exception as e:
  9281. logger.warning("[LAYER-TL] Failed: %s", e)
  9282. # A completed print's session left _active_sessions when its stitch
  9283. # began: the one there now belongs to the next print, which may have
  9284. # started during the stitch, and must not lose its frames.
  9285. if print_status != "completed":
  9286. try:
  9287. cancel_session(printer_id)
  9288. except Exception:
  9289. pass # Best-effort timelapse session cancellation on error
  9290. layer_timelapse = _background_layer_timelapse()
  9291. if archive_id and print_status == "completed":
  9292. layer_timelapse = _mark_run_finishing(archive_id, layer_timelapse)
  9293. spawn_background_task(layer_timelapse, name="background-layer-timelapse")
  9294. log_timing("All background tasks scheduled")
  9295. # Auto-scan for timelapse if recording was active during the print
  9296. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  9297. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  9298. # Schedule timelapse scan as background task with retries
  9299. # The printer needs time to encode the video after print completion
  9300. _schedule_timelapse_scan(archive_id, printer_id, plate_id=notify_plate_id)
  9301. log_timing("Timelapse scan scheduled")
  9302. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  9303. # AMS sensor history recording
  9304. _ams_history_task: asyncio.Task | None = None
  9305. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  9306. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  9307. def _retention_days(stored: str | None, default: int) -> int:
  9308. """A history retention setting as days to keep: at least 1, the default
  9309. when unset or unreadable. A stored 0 or less (the API took one before it
  9310. had a minimum) would put the cutoff at now and delete all history."""
  9311. try:
  9312. return max(1, int(stored)) if stored is not None else default
  9313. except (TypeError, ValueError):
  9314. return default
  9315. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  9316. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  9317. _ams_alarm_cooldown: dict[str, datetime] = {}
  9318. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  9319. # (printer_id, ams_id) already reported as sending the drop index and no
  9320. # percentage. Logged once each so a supported printer that turns out to do this
  9321. # shows up in a support bundle rather than as a user wondering where the
  9322. # humidity reading went -- see the note at the read site below (#3140).
  9323. _ams_index_only_logged: set[tuple[int, int]] = set()
  9324. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  9325. """Temperature at which the AMS alarm fires, falling back to the display band.
  9326. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  9327. when a notification was sent as well, which is why a room above it made the
  9328. alarm fire once an hour for as long as the weather lasted -- and the only way
  9329. to stop that was to raise the display band and lose the colour that says the
  9330. unit is warm (#2905).
  9331. Unset resolves to the fair threshold, so an install that never sets one is
  9332. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  9333. so that arrives here as a string and is handled by the same branch as any
  9334. other unparseable value -- there is no separate sentinel to keep in sync.
  9335. A non-positive value is refused rather than honoured: zero would alarm
  9336. permanently, and it is far more likely to be a cleared field than a
  9337. deliberate choice.
  9338. """
  9339. if raw_alarm_value is None:
  9340. return fair_threshold
  9341. try:
  9342. value = float(raw_alarm_value)
  9343. except (TypeError, ValueError):
  9344. return fair_threshold
  9345. if not math.isfinite(value) or value <= 0:
  9346. return fair_threshold
  9347. return value
  9348. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  9349. # through a cycle and the cool-down after it (#1802). Stored in the settings
  9350. # table rather than alongside _ams_alarm_cooldown above, because a restart
  9351. # partway through a cool-down would otherwise resume alarming about heat the
  9352. # user asked for — the same internal-timestamp-row pattern as
  9353. # support.py's debug_logging_enabled_at.
  9354. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  9355. # Upper bound on that suppression. The latch normally clears as soon as the unit
  9356. # reads at or below the threshold; see utils.ams_drying for why this cap only
  9357. # matters when it never does.
  9358. AMS_DRYING_GRACE_MINUTES = 120
  9359. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  9360. """Read the persisted per-AMS drying latch, dropping entries out of window.
  9361. Anything older than the grace cap would expire on its next visit anyway, so
  9362. discarding it here costs nothing and stops rows for deleted printers from
  9363. accumulating.
  9364. Stamps ahead of now get two defences, because a box whose clock jumps
  9365. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  9366. ones are discarded outright, and the rest are clamped to now. Without the
  9367. clamp the cap would measure from a moment that has not happened yet and hold
  9368. the alarm quiet for the skew on top of the cap. One unnecessary notification
  9369. after a clock jump is a far better failure than an alarm silently disabled
  9370. for hours.
  9371. """
  9372. from backend.app.models.settings import Settings
  9373. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9374. setting = result.scalar_one_or_none()
  9375. if not setting or not setting.value:
  9376. return {}
  9377. try:
  9378. raw = json.loads(setting.value)
  9379. except (ValueError, TypeError):
  9380. return {} # Corrupted row → no latch, alarms behave as they did before
  9381. if not isinstance(raw, dict):
  9382. return {}
  9383. now = datetime.now(timezone.utc)
  9384. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  9385. latch: dict[str, datetime] = {}
  9386. for key, value in raw.items():
  9387. try:
  9388. stamp = datetime.fromisoformat(str(value))
  9389. except (ValueError, TypeError):
  9390. continue
  9391. if stamp.tzinfo is None:
  9392. stamp = stamp.replace(tzinfo=timezone.utc)
  9393. if not (now - window <= stamp <= now + window):
  9394. continue
  9395. # Nothing may sit in the future: suppression is measured as now minus
  9396. # the stamp, so a stamp ahead of now would extend it by the skew on top
  9397. # of the cap. Clamping the survivors keeps the cap an actual cap.
  9398. latch[str(key)] = min(stamp, now)
  9399. return latch
  9400. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  9401. """Persist the latch, writing only when it actually changed.
  9402. Adds the session change but does not commit — the caller's own commit
  9403. carries it, so the latch lands in the same transaction as the sensor rows
  9404. that produced it.
  9405. """
  9406. from backend.app.models.settings import Settings
  9407. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  9408. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9409. setting = result.scalar_one_or_none()
  9410. if setting is None:
  9411. # Don't create the row on installs that never dry anything.
  9412. if payload != "{}":
  9413. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  9414. elif setting.value != payload:
  9415. setting.value = payload
  9416. def _ams_has_filament(ams_data: dict) -> bool:
  9417. """True if this AMS unit has at least one tray slot holding filament.
  9418. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  9419. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  9420. still report sensor readings, but those readings are ambient and not
  9421. actionable: no filament to dry, no humidity to push down. #1619 — gate
  9422. humidity/temperature alarms on this check so empty units don't generate
  9423. hourly noise. Sensor history still records regardless so the UI charts
  9424. stay continuous.
  9425. Fallback path inspects the `tray` array's `tray_type` fields for setups
  9426. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  9427. """
  9428. bits = ams_data.get("tray_exist_bits")
  9429. if isinstance(bits, str) and bits.strip():
  9430. try:
  9431. return int(bits, 16) > 0
  9432. except ValueError:
  9433. pass
  9434. trays = ams_data.get("tray")
  9435. if isinstance(trays, list):
  9436. return any(
  9437. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  9438. )
  9439. return False
  9440. async def record_ams_history():
  9441. """Background task to record AMS humidity and temperature data."""
  9442. logger = logging.getLogger(__name__)
  9443. # Wait a short time for MQTT connections to establish on startup
  9444. await asyncio.sleep(10)
  9445. while True:
  9446. try:
  9447. from backend.app.models.ams_history import AMSSensorHistory
  9448. from backend.app.models.printer import Printer
  9449. from backend.app.models.settings import Settings
  9450. async with async_session() as db:
  9451. # Get all active printers
  9452. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9453. printers = result.scalars().all()
  9454. # Get alarm thresholds from settings
  9455. humidity_threshold = 60.0 # Default: fair threshold
  9456. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  9457. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  9458. setting = result.scalar_one_or_none()
  9459. if setting:
  9460. try:
  9461. humidity_threshold = float(setting.value)
  9462. except (ValueError, TypeError):
  9463. pass # Keep default threshold if stored value is invalid
  9464. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  9465. setting = result.scalar_one_or_none()
  9466. if setting:
  9467. try:
  9468. temp_fair_threshold = float(setting.value)
  9469. except (ValueError, TypeError):
  9470. pass # Keep default threshold if stored value is invalid
  9471. # The alarm gets its own threshold, seeded from the resolved fair
  9472. # value so an install that has never set one behaves exactly as
  9473. # it did before (#2905). ams_temp_fair decides when the card turns
  9474. # amber; 35 C is a reasonable place to change a colour and not a
  9475. # reasonable place to page someone. A room above it makes the
  9476. # alarm fire once an hour for as long as the weather lasts, and
  9477. # the only way to stop it was to raise the display band and lose
  9478. # the colour that says the unit is warm.
  9479. #
  9480. # An unset value is stored as the literal "None", which the except
  9481. # below swallows the same way it swallows garbage -- so the
  9482. # fallback costs nothing and needs no sentinel of its own.
  9483. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  9484. setting = result.scalar_one_or_none()
  9485. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  9486. temp_fair_threshold, setting.value if setting else None
  9487. )
  9488. # Per-filament humidity threshold overrides (#1605) — resolved
  9489. # per-AMS below from the loaded tray types. Reuses the same
  9490. # resolver as the auto-drying scheduler so behavior stays in
  9491. # lockstep across both consumers.
  9492. from backend.app.services.print_scheduler import PrintScheduler
  9493. per_type_humidity_thresholds: dict[str, int] = {}
  9494. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  9495. setting = result.scalar_one_or_none()
  9496. if setting and setting.value:
  9497. try:
  9498. raw = json.loads(setting.value)
  9499. if isinstance(raw, dict):
  9500. for k, v in raw.items():
  9501. try:
  9502. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  9503. v
  9504. )
  9505. except (TypeError, ValueError):
  9506. continue
  9507. except (ValueError, TypeError):
  9508. pass # Invalid JSON → no overrides, fall through to global threshold
  9509. # Per-AMS drying latch (#1802), loaded once per pass and written
  9510. # back below only if a unit changed it.
  9511. drying_latch = await _load_ams_drying_latch(db)
  9512. drying_latch_before = dict(drying_latch)
  9513. recorded_count = 0
  9514. for printer in printers:
  9515. # Get current state from printer manager
  9516. state = printer_manager.get_status(printer.id)
  9517. if not state or not state.connected or not state.raw_data:
  9518. continue # Skip disconnected printers - don't use stale data
  9519. raw_data = state.raw_data
  9520. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  9521. continue
  9522. # Record data for each AMS unit
  9523. for ams_data in raw_data["ams"]:
  9524. ams_id = int(ams_data.get("id", 0))
  9525. # Percentage only. The 1-5 index is inverted, so
  9526. # charting it as a percentage drew the wettest units as
  9527. # the driest (#3140); a unit that reports no percentage
  9528. # leaves a gap in the chart instead. See
  9529. # utils/ams_humidity.
  9530. humidity = ams_humidity_percent(ams_data)
  9531. # No supported printer is known to send the index
  9532. # alone -- the report came from unsupported firmware,
  9533. # and no install has been seen using the old fallback.
  9534. # "Known" is doing work there, so say so once per unit:
  9535. # the alternative is a silent blank card.
  9536. if humidity is None and ams_data.get("humidity") is not None:
  9537. unit_key = (printer.id, ams_id)
  9538. if unit_key not in _ams_index_only_logged:
  9539. _ams_index_only_logged.add(unit_key)
  9540. logger.info(
  9541. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  9542. "percentage. The index is inverted and is not shown as a percentage "
  9543. "(#3140), so this unit has no humidity reading, chart or alarm. "
  9544. "Please report this with the printer and AMS firmware versions.",
  9545. printer.name,
  9546. ams_id,
  9547. )
  9548. # Get temperature
  9549. temperature = None
  9550. temp_str = ams_data.get("temp")
  9551. if temp_str is not None:
  9552. try:
  9553. temperature = float(temp_str)
  9554. except (ValueError, TypeError):
  9555. pass # Skip unparseable temperature value
  9556. # Skip if no data
  9557. if humidity is None and temperature is None:
  9558. continue
  9559. # Record the data point
  9560. history = AMSSensorHistory(
  9561. printer_id=printer.id,
  9562. ams_id=ams_id,
  9563. humidity=humidity,
  9564. # Both columns hold the same reading now that the
  9565. # index can no longer reach ``humidity``. Writing it
  9566. # through the same value also stops a genuine 0%
  9567. # from being stored as NULL, which the old truthiness
  9568. # test did.
  9569. humidity_raw=humidity,
  9570. temperature=temperature,
  9571. )
  9572. db.add(history)
  9573. recorded_count += 1
  9574. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  9575. is_ams_ht = ams_id >= 128
  9576. if is_ams_ht:
  9577. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  9578. else:
  9579. ams_label = f"AMS-{chr(65 + ams_id)}"
  9580. # Skip alarm dispatch for empty AMS units — humidity /
  9581. # temperature readings are ambient with no filament to
  9582. # protect, and the hourly notification just becomes
  9583. # noise. Sensor history was already recorded above so
  9584. # the UI charts stay continuous (#1619). Per-AMS check
  9585. # so a multi-AMS setup with one loaded + one empty
  9586. # still alarms on the loaded unit.
  9587. if not _ams_has_filament(ams_data):
  9588. continue
  9589. # Resolve per-filament humidity threshold for this AMS
  9590. # unit (#1605). Falls back to the global ams_humidity_fair
  9591. # when no per-type overrides are configured.
  9592. trays = ams_data.get("tray", []) or []
  9593. effective_humidity_threshold = float(
  9594. PrintScheduler.resolve_humidity_threshold(
  9595. trays, per_type_humidity_thresholds, int(humidity_threshold)
  9596. )
  9597. )
  9598. # Check humidity alarm (only if above threshold)
  9599. if humidity is not None and humidity > effective_humidity_threshold:
  9600. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  9601. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9602. now = datetime.now(timezone.utc)
  9603. if (
  9604. last_alarm is None
  9605. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9606. ):
  9607. _ams_alarm_cooldown[cooldown_key] = now
  9608. logger.info(
  9609. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  9610. )
  9611. try:
  9612. # Call different notification method based on AMS type
  9613. if is_ams_ht:
  9614. await notification_service.on_ams_ht_humidity_high(
  9615. printer.id,
  9616. printer.name,
  9617. ams_label,
  9618. humidity,
  9619. effective_humidity_threshold,
  9620. db,
  9621. )
  9622. else:
  9623. await notification_service.on_ams_humidity_high(
  9624. printer.id,
  9625. printer.name,
  9626. ams_label,
  9627. humidity,
  9628. effective_humidity_threshold,
  9629. db,
  9630. )
  9631. except Exception as e:
  9632. logger.warning("Failed to send humidity alarm: %s", e)
  9633. # A drying cycle heats the unit far past ams_temp_fair on
  9634. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  9635. # AMS-HT, against a 35 C default — so the alarm fired
  9636. # once an hour for the whole cycle and kept firing while
  9637. # the unit cooled back down (#1802). Latch on the
  9638. # firmware's own drying state and hold until the reading
  9639. # returns to normal. Humidity is deliberately left alone:
  9640. # it falls during drying, which is the whole point.
  9641. latch_key = f"{printer.id}:{ams_id}"
  9642. # The latch releases at `threshold`, so it takes the alarm
  9643. # number too. Handing it the display band would strand the
  9644. # latch on any unit that settles back above it -- a room
  9645. # where the AMS rests at 37.7 C never returns under a 35 C
  9646. # band, so the latch could only expire on the grace cap
  9647. # rather than releasing when the unit had actually cooled.
  9648. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  9649. drying_active=is_drying_active(ams_data),
  9650. temperature=temperature,
  9651. threshold=temp_alarm_threshold,
  9652. latched_at=drying_latch.get(latch_key),
  9653. now=datetime.now(timezone.utc),
  9654. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  9655. )
  9656. if new_latch is None:
  9657. drying_latch.pop(latch_key, None)
  9658. else:
  9659. drying_latch[latch_key] = new_latch
  9660. # Check temperature alarm (only if above threshold)
  9661. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  9662. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  9663. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9664. now = datetime.now(timezone.utc)
  9665. if (
  9666. last_alarm is None
  9667. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9668. ):
  9669. _ams_alarm_cooldown[cooldown_key] = now
  9670. logger.info(
  9671. f"Sending temperature alarm for {printer.name} {ams_label}: "
  9672. f"{temperature}°C > {temp_alarm_threshold}°C"
  9673. )
  9674. try:
  9675. # Call different notification method based on AMS type
  9676. if is_ams_ht:
  9677. # The reported threshold has to be the one
  9678. # that fired, or the message says "> 35 °C"
  9679. # while firing at 45.
  9680. await notification_service.on_ams_ht_temperature_high(
  9681. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9682. )
  9683. else:
  9684. await notification_service.on_ams_temperature_high(
  9685. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9686. )
  9687. except Exception as e:
  9688. logger.warning("Failed to send temperature alarm: %s", e)
  9689. if drying_latch != drying_latch_before:
  9690. await _save_ams_drying_latch(db, drying_latch)
  9691. await db.commit()
  9692. if recorded_count > 0:
  9693. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  9694. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  9695. global _ams_cleanup_counter
  9696. _ams_cleanup_counter += 1
  9697. if _ams_cleanup_counter >= 288:
  9698. _ams_cleanup_counter = 0
  9699. # Get retention days from settings
  9700. from backend.app.models.settings import Settings
  9701. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  9702. setting = result.scalar_one_or_none()
  9703. retention_days = _retention_days(setting.value if setting else None, AMS_HISTORY_RETENTION_DAYS)
  9704. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9705. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  9706. await db.commit()
  9707. if result.rowcount > 0:
  9708. logger.info(
  9709. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  9710. )
  9711. # Wait until next recording interval
  9712. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  9713. except asyncio.CancelledError:
  9714. break
  9715. except Exception as e:
  9716. logger.warning("AMS history recording failed: %s", e)
  9717. await asyncio.sleep(60) # Wait a bit before retrying
  9718. def start_ams_history_recording():
  9719. """Start the AMS history recording background task."""
  9720. global _ams_history_task
  9721. if _ams_history_task is None:
  9722. _ams_history_task = asyncio.create_task(record_ams_history())
  9723. logging.getLogger(__name__).info("AMS history recording started")
  9724. def stop_ams_history_recording():
  9725. """Stop the AMS history recording background task."""
  9726. global _ams_history_task
  9727. if _ams_history_task:
  9728. _ams_history_task.cancel()
  9729. _ams_history_task = None
  9730. logging.getLogger(__name__).info("AMS history recording stopped")
  9731. # Printer sensor history recording (nozzle / bed / chamber)
  9732. _printer_sensor_history_task: asyncio.Task | None = None
  9733. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  9734. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  9735. _printer_sensor_cleanup_counter = 0
  9736. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  9737. # MQTT parser writes, so we don't need to handle per-model field aliases here
  9738. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  9739. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  9740. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  9741. _SENSOR_TARGET_KEYS = {
  9742. "nozzle": "nozzle_target",
  9743. "nozzle_2": "nozzle_2_target",
  9744. "bed": "bed_target",
  9745. "chamber": "chamber_target",
  9746. }
  9747. async def record_printer_sensor_history():
  9748. """Background task to record nozzle / bed / chamber readings.
  9749. Pulls from `state.temperatures` (already normalised across all printer
  9750. models by the MQTT parser) rather than re-parsing raw_data, so we get
  9751. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  9752. """
  9753. logger = logging.getLogger(__name__)
  9754. await asyncio.sleep(10)
  9755. while True:
  9756. try:
  9757. from backend.app.models.printer import Printer
  9758. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  9759. from backend.app.models.settings import Settings
  9760. async with async_session() as db:
  9761. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9762. printers = result.scalars().all()
  9763. recorded_count = 0
  9764. for printer in printers:
  9765. state = printer_manager.get_status(printer.id)
  9766. if not state or not state.connected:
  9767. continue
  9768. temps = getattr(state, "temperatures", None) or {}
  9769. if not isinstance(temps, dict):
  9770. continue
  9771. for kind in _SENSOR_KINDS:
  9772. if kind not in temps:
  9773. continue
  9774. try:
  9775. value = float(temps[kind])
  9776. except (ValueError, TypeError):
  9777. continue
  9778. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  9779. target_val: float | None = None
  9780. if target_raw is not None:
  9781. try:
  9782. target_val = float(target_raw)
  9783. except (ValueError, TypeError):
  9784. target_val = None
  9785. db.add(
  9786. PrinterSensorHistory(
  9787. printer_id=printer.id,
  9788. sensor_kind=kind,
  9789. value=value,
  9790. target=target_val,
  9791. )
  9792. )
  9793. recorded_count += 1
  9794. await db.commit()
  9795. if recorded_count > 0:
  9796. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  9797. # Periodic cleanup — once every ~24h at this interval.
  9798. global _printer_sensor_cleanup_counter
  9799. _printer_sensor_cleanup_counter += 1
  9800. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  9801. if _printer_sensor_cleanup_counter >= cleanup_every:
  9802. _printer_sensor_cleanup_counter = 0
  9803. result = await db.execute(
  9804. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  9805. )
  9806. setting = result.scalar_one_or_none()
  9807. retention_days = _retention_days(
  9808. setting.value if setting else None, PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  9809. )
  9810. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9811. cleanup = await db.execute(
  9812. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  9813. )
  9814. await db.commit()
  9815. if cleanup.rowcount > 0:
  9816. logger.info(
  9817. "Cleaned up %s old printer sensor history entries (older than %s days)",
  9818. cleanup.rowcount,
  9819. retention_days,
  9820. )
  9821. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  9822. except asyncio.CancelledError:
  9823. break
  9824. except Exception as e:
  9825. logger.warning("Printer sensor history recording failed: %s", e)
  9826. await asyncio.sleep(60)
  9827. def start_printer_sensor_history_recording():
  9828. global _printer_sensor_history_task
  9829. if _printer_sensor_history_task is None:
  9830. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  9831. logging.getLogger(__name__).info("Printer sensor history recording started")
  9832. def stop_printer_sensor_history_recording():
  9833. global _printer_sensor_history_task
  9834. if _printer_sensor_history_task:
  9835. _printer_sensor_history_task.cancel()
  9836. _printer_sensor_history_task = None
  9837. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  9838. # Printer runtime tracking
  9839. _runtime_tracking_task: asyncio.Task | None = None
  9840. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  9841. # Printers the runtime tracker has seen connected since startup. One of them
  9842. # going offline clears its timestamp, so the time it was away is not counted
  9843. # when it comes back printing (DB-C5). A printer not yet seen -- still
  9844. # connecting after a restart -- keeps it for a grace period: a print that ran
  9845. # on through a Bambuddy restart is counted from the stored timestamp, as before.
  9846. _runtime_seen_connected: set[int] = set()
  9847. # A printer never seen connected this long after the tracker started is
  9848. # offline, not still connecting: its stored timestamp predates a gap too.
  9849. RUNTIME_STARTUP_GRACE_SECONDS = 120
  9850. async def track_printer_runtime():
  9851. """Background task to track printer active runtime (RUNNING state only).
  9852. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  9853. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  9854. which track mechanical wear. Pause time has no motion and no wear, so
  9855. counting it inflates maintenance warnings (#1521).
  9856. """
  9857. logger = logging.getLogger(__name__)
  9858. # Wait for MQTT connections to establish on startup
  9859. await asyncio.sleep(15)
  9860. started = time.monotonic()
  9861. while True:
  9862. try:
  9863. from backend.app.models.printer import Printer
  9864. # Fetch printer IDs in a short-lived read-only session
  9865. async with async_session() as db:
  9866. result = await db.execute(
  9867. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  9868. Printer.is_active.is_(True)
  9869. )
  9870. )
  9871. printer_rows = result.all()
  9872. now = datetime.now(timezone.utc)
  9873. updated_count = 0
  9874. # Update each printer in its own short session to minimise write-lock
  9875. # hold time and avoid blocking critical commits like queue status
  9876. # updates (#897).
  9877. for pid, pname, runtime_secs, last_update in printer_rows:
  9878. state = printer_manager.get_status(pid)
  9879. if not state:
  9880. logger.debug("[%s] Runtime tracking: no state available", pname)
  9881. continue
  9882. if not state.connected:
  9883. logger.debug("[%s] Runtime tracking: not connected", pname)
  9884. offline = pid in _runtime_seen_connected or (
  9885. time.monotonic() - started > RUNTIME_STARTUP_GRACE_SECONDS
  9886. )
  9887. if offline and last_update is not None:
  9888. try:
  9889. async with async_session() as db:
  9890. printer = await db.get(Printer, pid)
  9891. if printer:
  9892. printer.last_runtime_update = None
  9893. await db.commit()
  9894. except Exception as e:
  9895. # Still marked: the next offline tick tries again.
  9896. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  9897. continue
  9898. _runtime_seen_connected.discard(pid)
  9899. continue
  9900. _runtime_seen_connected.add(pid)
  9901. needs_commit = False
  9902. new_runtime = runtime_secs
  9903. new_last_update = last_update
  9904. if state.state == "RUNNING":
  9905. if last_update:
  9906. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  9907. elapsed = (now - lu).total_seconds()
  9908. if elapsed > 0:
  9909. new_runtime = runtime_secs + int(elapsed)
  9910. updated_count += 1
  9911. needs_commit = True
  9912. logger.debug(
  9913. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  9914. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  9915. )
  9916. else:
  9917. needs_commit = True
  9918. logger.debug("[%s] Runtime tracking: first active detection", pname)
  9919. new_last_update = now
  9920. else:
  9921. if last_update is not None:
  9922. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  9923. new_last_update = None
  9924. needs_commit = True
  9925. if needs_commit:
  9926. try:
  9927. async with async_session() as db:
  9928. result = await db.execute(select(Printer).where(Printer.id == pid))
  9929. printer = result.scalar_one_or_none()
  9930. if printer:
  9931. printer.runtime_seconds = new_runtime
  9932. printer.last_runtime_update = new_last_update
  9933. await db.commit()
  9934. except Exception as e:
  9935. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  9936. if updated_count > 0:
  9937. logger.debug("Updated runtime for %s printer(s)", updated_count)
  9938. except asyncio.CancelledError:
  9939. logger.info("Runtime tracking cancelled")
  9940. break
  9941. except Exception as e:
  9942. logger.warning("Runtime tracking failed: %s", e)
  9943. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  9944. def start_runtime_tracking():
  9945. """Start the printer runtime tracking background task."""
  9946. global _runtime_tracking_task
  9947. if _runtime_tracking_task is None:
  9948. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  9949. logging.getLogger(__name__).info("Printer runtime tracking started")
  9950. def stop_runtime_tracking():
  9951. """Stop the printer runtime tracking background task."""
  9952. global _runtime_tracking_task
  9953. if _runtime_tracking_task:
  9954. _runtime_tracking_task.cancel()
  9955. _runtime_tracking_task = None
  9956. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  9957. # SpoolBuddy device watchdog
  9958. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  9959. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  9960. async def _spoolbuddy_watchdog_loop():
  9961. """Periodic check for SpoolBuddy devices that have gone offline."""
  9962. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  9963. while True:
  9964. try:
  9965. await spoolbuddy_watchdog()
  9966. except asyncio.CancelledError:
  9967. break
  9968. except Exception as e:
  9969. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  9970. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  9971. def start_spoolbuddy_watchdog():
  9972. global _spoolbuddy_watchdog_task
  9973. if _spoolbuddy_watchdog_task is None:
  9974. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  9975. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  9976. def stop_spoolbuddy_watchdog():
  9977. global _spoolbuddy_watchdog_task
  9978. if _spoolbuddy_watchdog_task:
  9979. _spoolbuddy_watchdog_task.cancel()
  9980. _spoolbuddy_watchdog_task = None
  9981. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  9982. # Dead-MQTT-session recovery
  9983. #
  9984. # check_staleness() covers the "connected but silent" half-broken session. It
  9985. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  9986. # is the only thing left watching at that point. When paho stops making
  9987. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  9988. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  9989. # offline with the UI open the whole time, recovered only when something
  9990. # happened to nudge it.
  9991. #
  9992. # This loop is that backstop. It only touches printers that had a working
  9993. # session and lost it, and only when the MQTT port still answers — a printer
  9994. # that is simply switched off is left to paho, since rebuilding a client
  9995. # against an unreachable host achieves nothing and would fill the log every
  9996. # night.
  9997. _connection_watchdog_task: asyncio.Task | None = None
  9998. CONNECTION_WATCHDOG_INTERVAL = 60
  9999. # How long a printer must have been silent before we stop trusting paho.
  10000. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  10001. # so a session that is recovering on its own is never interrupted.
  10002. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  10003. # Per-printer floor between rebuild attempts.
  10004. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  10005. _connection_watchdog_last_attempt: dict[int, float] = {}
  10006. async def _recover_dead_printer_sessions() -> int:
  10007. """Rebuild MQTT clients that have been offline too long to still be trying.
  10008. Returns the number of printers a rebuild was attempted for (for tests and
  10009. for the caller's logging). Never raises: one unreachable printer must not
  10010. stop the sweep for the rest of the farm.
  10011. """
  10012. logger = logging.getLogger(__name__)
  10013. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  10014. now = time.monotonic()
  10015. recovered = 0
  10016. for printer_id, client in list(printer_manager._clients.items()):
  10017. try:
  10018. if client.state.connected:
  10019. _connection_watchdog_last_attempt.pop(printer_id, None)
  10020. continue
  10021. # Time since the last inbound message is the age of the last known
  10022. # good session — no extra bookkeeping needed, and it is the same
  10023. # clock is_stale() reads. 0 means this client has never had one:
  10024. # that is the initial-connect path, where paho retrying is the
  10025. # correct and only behaviour, so leave it be.
  10026. last_msg = client._last_message_time
  10027. if not last_msg:
  10028. continue
  10029. offline_for = time.time() - last_msg
  10030. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  10031. continue
  10032. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  10033. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  10034. continue
  10035. if not await check_port(client.ip_address, PORT_MQTT):
  10036. # Switched off, unplugged, or off the network. Paho's retry is
  10037. # the right handler; say so at debug level and move on.
  10038. logger.debug(
  10039. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  10040. "— leaving the reconnect to paho",
  10041. printer_id,
  10042. offline_for,
  10043. )
  10044. _connection_watchdog_last_attempt[printer_id] = now
  10045. continue
  10046. _connection_watchdog_last_attempt[printer_id] = now
  10047. recovered += 1
  10048. logger.warning(
  10049. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  10050. "rebuilding the client with a fresh session (last connect error: %s)",
  10051. printer_id,
  10052. offline_for,
  10053. PORT_MQTT,
  10054. client.last_connect_error or "none recorded",
  10055. )
  10056. # Async context, so this takes the hard-reset path: fresh client_id,
  10057. # paho's QoS 1 queue dropped. That matters — a project_file left
  10058. # unacked on the dead session would otherwise replay into the new
  10059. # one and trip 0500_4003 on the printer (#1136).
  10060. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  10061. except Exception as e:
  10062. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  10063. return recovered
  10064. async def _connection_watchdog_loop():
  10065. logger = logging.getLogger(__name__)
  10066. # Let the initial connects settle before judging anyone offline.
  10067. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  10068. while True:
  10069. try:
  10070. await _recover_dead_printer_sessions()
  10071. except asyncio.CancelledError:
  10072. break
  10073. except Exception as e:
  10074. logger.warning("Connection watchdog sweep failed: %s", e)
  10075. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  10076. def start_connection_watchdog():
  10077. global _connection_watchdog_task
  10078. if _connection_watchdog_task is None:
  10079. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  10080. logging.getLogger(__name__).info("Printer connection watchdog started")
  10081. def stop_connection_watchdog():
  10082. global _connection_watchdog_task
  10083. if _connection_watchdog_task:
  10084. _connection_watchdog_task.cancel()
  10085. _connection_watchdog_task = None
  10086. _connection_watchdog_last_attempt.clear()
  10087. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  10088. # Camera stream orphan cleanup
  10089. _camera_cleanup_task: asyncio.Task | None = None
  10090. CAMERA_CLEANUP_INTERVAL = 60
  10091. # Every this many camera cleanups (about an hour), the timelapse janitor too:
  10092. # kept frames of a failed stitch go after a day, not at the next restart.
  10093. TIMELAPSE_CLEANUP_EVERY = 60
  10094. async def _camera_cleanup_loop():
  10095. """Periodically clean up orphaned ffmpeg processes and timelapse leftovers."""
  10096. from backend.app.api.routes.camera import cleanup_orphaned_streams
  10097. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10098. rounds = 0
  10099. while True:
  10100. try:
  10101. rounds += 1
  10102. await cleanup_orphaned_streams()
  10103. except asyncio.CancelledError:
  10104. break
  10105. except Exception as e:
  10106. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  10107. try:
  10108. if rounds % TIMELAPSE_CLEANUP_EVERY == 0:
  10109. await asyncio.to_thread(cleanup_orphaned_timelapse_sessions)
  10110. except asyncio.CancelledError:
  10111. break
  10112. except Exception as e:
  10113. logging.getLogger(__name__).warning("Timelapse frames cleanup failed: %s", e)
  10114. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  10115. def start_camera_cleanup():
  10116. global _camera_cleanup_task
  10117. if _camera_cleanup_task is None:
  10118. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  10119. logging.getLogger(__name__).info("Camera stream cleanup started")
  10120. def stop_camera_cleanup():
  10121. global _camera_cleanup_task
  10122. if _camera_cleanup_task:
  10123. _camera_cleanup_task.cancel()
  10124. _camera_cleanup_task = None
  10125. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  10126. # ---------------------------------------------------------------------------
  10127. # Expected-print TTL eviction
  10128. # ---------------------------------------------------------------------------
  10129. def _evict_stale_expected_prints() -> None:
  10130. """Remove entries from _expected_prints / _expected_print_creators that are
  10131. older than _EXPECTED_PRINT_TTL_SECONDS.
  10132. This prevents unbounded growth when a print is registered (via
  10133. register_expected_print) but on_print_start never fires — e.g. because the
  10134. printer disconnects, the app restarts, or the print is started directly from
  10135. the printer panel without going through the queue.
  10136. """
  10137. # Use monotonic time so the TTL is unaffected by system clock adjustments
  10138. # (e.g. NTP sync, DST changes).
  10139. # A print that ended without its archive being found at completion leaves
  10140. # its id here; only running prints are owned.
  10141. _owned_print_archive_ids.intersection_update(_active_prints.values())
  10142. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  10143. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  10144. if not stale_keys:
  10145. return
  10146. evicted: set[tuple[int, int]] = set()
  10147. for key in stale_keys:
  10148. archive_id = _expected_prints.pop(key, None)
  10149. if archive_id is not None:
  10150. evicted.add((key[0], archive_id))
  10151. _expected_print_creators.pop(key, None)
  10152. _expected_print_registered_at.pop(key, None)
  10153. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  10154. # that have no remaining live keys in _expected_prints (all variants
  10155. # were just evicted) and are not printing right now. Print start pops
  10156. # only the names the printer reported, so the "<base>.gcode" variant
  10157. # outlives it; without the printing check its eviction two hours after
  10158. # dispatch threw away a running print's plate, AMS mapping and cost
  10159. # centre, which completion still reads (#3275).
  10160. for printer_id, archive_id in evicted:
  10161. if not _expected_or_printing_here(printer_id, archive_id):
  10162. _drop_dispatch(printer_id, archive_id)
  10163. logging.getLogger(__name__).info(
  10164. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  10165. )
  10166. async def _expected_prints_cleanup_loop() -> None:
  10167. """Background task: periodically evict stale expected-print entries."""
  10168. while True:
  10169. try:
  10170. _evict_stale_expected_prints()
  10171. except asyncio.CancelledError:
  10172. raise
  10173. except Exception as e:
  10174. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  10175. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  10176. def start_expected_prints_cleanup() -> None:
  10177. global _expected_prints_cleanup_task
  10178. if _expected_prints_cleanup_task is None:
  10179. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  10180. logging.getLogger(__name__).info("Expected prints cleanup started")
  10181. def stop_expected_prints_cleanup() -> None:
  10182. global _expected_prints_cleanup_task
  10183. if _expected_prints_cleanup_task:
  10184. _expected_prints_cleanup_task.cancel()
  10185. _expected_prints_cleanup_task = None
  10186. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  10187. # ---------------------------------------------------------------------------
  10188. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  10189. # ---------------------------------------------------------------------------
  10190. _auth_cleanup_task: asyncio.Task | None = None
  10191. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  10192. async def _run_auth_cleanup() -> None:
  10193. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  10194. from backend.app.core.database import async_session
  10195. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  10196. from backend.app.models.user_totp import UserTOTP
  10197. now = datetime.now(timezone.utc)
  10198. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  10199. try:
  10200. async with async_session() as db:
  10201. stale_cutoff = now - timedelta(hours=1)
  10202. result = await db.execute(
  10203. select(UserTOTP).where(
  10204. UserTOTP.is_enabled.is_(False),
  10205. UserTOTP.created_at < stale_cutoff,
  10206. )
  10207. )
  10208. stale_records = result.scalars().all()
  10209. if stale_records:
  10210. for rec in stale_records:
  10211. await db.delete(rec)
  10212. await db.commit()
  10213. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  10214. except Exception as e:
  10215. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  10216. # Remove expired revoked-JTI entries (they are no longer needed once the
  10217. # original token's exp has passed — the token would be rejected by JWT
  10218. # signature verification regardless).
  10219. try:
  10220. async with async_session() as db:
  10221. await db.execute(
  10222. delete(AuthEphemeralToken).where(
  10223. AuthEphemeralToken.token_type == "revoked_jti",
  10224. AuthEphemeralToken.expires_at < now,
  10225. )
  10226. )
  10227. await db.commit()
  10228. except Exception as e:
  10229. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  10230. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  10231. # Events outside this window can never affect rate-limit decisions — they only
  10232. # consume DB space. Use the same window constant as the rate limiter so the
  10233. # two are always in sync.
  10234. try:
  10235. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  10236. async with async_session() as db:
  10237. await db.execute(
  10238. delete(AuthRateLimitEvent).where(
  10239. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  10240. )
  10241. )
  10242. await db.commit()
  10243. except Exception as e:
  10244. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  10245. async def _auth_cleanup_loop() -> None:
  10246. """Periodic background task: run auth cleanup every hour."""
  10247. while True:
  10248. try:
  10249. await _run_auth_cleanup()
  10250. except asyncio.CancelledError:
  10251. break
  10252. except Exception as e:
  10253. logging.warning("Auth cleanup loop error: %s", e)
  10254. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  10255. def start_auth_cleanup() -> None:
  10256. global _auth_cleanup_task
  10257. if _auth_cleanup_task is None:
  10258. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  10259. logging.getLogger(__name__).info("Auth periodic cleanup started")
  10260. def stop_auth_cleanup() -> None:
  10261. global _auth_cleanup_task
  10262. if _auth_cleanup_task:
  10263. _auth_cleanup_task.cancel()
  10264. _auth_cleanup_task = None
  10265. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  10266. @asynccontextmanager
  10267. async def lifespan(app: FastAPI):
  10268. # Startup
  10269. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  10270. # anything else can spawn tasks that might trip it.
  10271. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  10272. install_proactor_reset_filter()
  10273. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  10274. # what turned descriptor exhaustion into a corrupted database (#2883).
  10275. from backend.app.core.fd_limit import raise_open_file_limit
  10276. raise_open_file_limit()
  10277. # Before init_db, so the warning is near the top of the log rather than
  10278. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  10279. warn_if_running_on_uvloop()
  10280. await init_db()
  10281. # Browser download tokens expire after five minutes. Remove abandoned
  10282. # prepared ZIPs at startup as well as before each new preparation so a
  10283. # quiet appliance cannot retain an unusable bundle indefinitely.
  10284. try:
  10285. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  10286. await prune_stale_printer_file_bundles()
  10287. except Exception as exc:
  10288. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  10289. # After migrations, so the is_env_managed column exists. Never raises --
  10290. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  10291. # startup (see apply_env_oidc_provider).
  10292. from backend.app.core.oidc_env import apply_env_oidc_provider
  10293. async with async_session() as oidc_db:
  10294. await apply_env_oidc_provider(oidc_db)
  10295. # Close out batches that finished before `completed` was a reachable status
  10296. # (#342). Without this the Batches tab opens on every batch created since
  10297. # the feature shipped, all still marked active. Never blocks startup.
  10298. try:
  10299. from backend.app.services.print_batch import backfill_batch_statuses
  10300. async with async_session() as batch_db:
  10301. await backfill_batch_statuses(batch_db)
  10302. except Exception as exc:
  10303. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  10304. # Register an app-scoped httpx client for Bambu Cloud services so
  10305. # per-request BambuCloudService instances reuse the same connection pool
  10306. # (important for routes like /cloud/filament-info that chain many
  10307. # get_setting_detail calls). The shared client stores no region/token
  10308. # state, so the per-request ownership pattern that fixed the region-bleed
  10309. # bug is preserved.
  10310. import httpx as _httpx
  10311. from backend.app.services.bambu_cloud import set_shared_http_client
  10312. from backend.app.services.model_providers.makerworld.service import (
  10313. set_shared_http_client as set_shared_makerworld_http_client,
  10314. )
  10315. from backend.app.services.orca_cloud import (
  10316. set_shared_http_client as set_shared_orca_http_client,
  10317. )
  10318. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  10319. set_shared_http_client(_shared_cloud_http_client)
  10320. # Reuse the same connection pool for MakerWorld — different host, same
  10321. # keep-alive pool saves a TLS handshake per request.
  10322. set_shared_makerworld_http_client(_shared_cloud_http_client)
  10323. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  10324. # each spun up (and never closed) its own client, leaking sockets.
  10325. set_shared_orca_http_client(_shared_cloud_http_client)
  10326. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  10327. # This can happen when a print was cancelled mid-print on versions before this fix.
  10328. try:
  10329. async with async_session() as db:
  10330. from backend.app.models.print_queue import PrintQueueItem
  10331. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  10332. aborted_items = result.scalars().all()
  10333. if aborted_items:
  10334. for item in aborted_items:
  10335. item.status = "cancelled"
  10336. await db.commit()
  10337. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  10338. except Exception as e:
  10339. logging.warning("Failed to fix aborted queue items: %s", e)
  10340. # Restore debug logging state from previous session
  10341. await init_debug_logging()
  10342. # Set up printer manager callbacks
  10343. loop = asyncio.get_event_loop()
  10344. printer_manager.set_event_loop(loop)
  10345. printer_manager.set_status_change_callback(on_printer_status_change)
  10346. printer_manager.set_print_start_callback(on_print_start)
  10347. printer_manager.set_print_complete_callback(on_print_complete)
  10348. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  10349. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  10350. printer_manager.set_ams_change_callback(on_ams_change)
  10351. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  10352. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  10353. await printer_manager.load_awaiting_plate_clear_from_db()
  10354. # Layer change callback for external camera timelapse
  10355. async def on_layer_change(printer_id: int, layer_num: int):
  10356. """Capture timelapse frame on layer change + first layer notification."""
  10357. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  10358. await tl_layer_change(printer_id, layer_num)
  10359. # #1867: bank a recent in-print frame so the finish-photo path has a
  10360. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  10361. # #2547 added `on_print_progress` as a second driver — this one alone
  10362. # stops firing once the final layer begins.
  10363. await _maybe_bank_inprint_frame(printer_id, layer_num)
  10364. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  10365. # Gate on actual printing state — Bambu firmware ticks layer_num during
  10366. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  10367. # nozzle clean), so a bare layer_num check can fire minutes before the
  10368. # first real extrusion. We require gcode_state == RUNNING and
  10369. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  10370. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  10371. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  10372. # edge fires later; _first_layer_notified stays clear until we actually send
  10373. # so a deferred re-evaluation can win. See issue #1837.
  10374. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  10375. client = printer_manager.get_client(printer_id)
  10376. state = client.state if client else None
  10377. if not state or state.state != "RUNNING":
  10378. return
  10379. if state.mc_print_sub_stage not in (None, 0):
  10380. return
  10381. _first_layer_notified[printer_id] = True
  10382. try:
  10383. async with async_session() as db:
  10384. from backend.app.models.printer import Printer
  10385. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  10386. printer = result.scalar_one_or_none()
  10387. if not printer:
  10388. return
  10389. printer_name = printer.name
  10390. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  10391. total_layers = state.total_layers if state else 0
  10392. image_data = await _capture_snapshot_for_notification(
  10393. printer_id, printer, logging.getLogger(__name__)
  10394. )
  10395. await notification_service.on_first_layer_complete(
  10396. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  10397. )
  10398. except Exception as e:
  10399. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  10400. printer_manager.set_layer_change_callback(on_layer_change)
  10401. async def on_print_progress(printer_id: int, percent: int):
  10402. """#2547: keep the in-print frame bank fresh through the final layer.
  10403. `on_layer_change` stops the moment the last layer starts, which on the
  10404. H2C capture that closed #2547 left the bank stale for the three minutes
  10405. that layer took. Progress is the only field that keeps advancing there,
  10406. and it freezes before the End G-code runs — so banking on it stays
  10407. inside the print and never sees a swapped plate.
  10408. """
  10409. client = printer_manager.get_client(printer_id)
  10410. state = client.state if client else None
  10411. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  10412. printer_manager.set_print_progress_callback(on_print_progress)
  10413. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  10414. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  10415. waiter = _bed_cool_waiters.get(printer_id)
  10416. if not waiter:
  10417. return
  10418. threshold = waiter["threshold"]
  10419. if bed_temp > threshold:
  10420. return
  10421. # Bed is at or below threshold — fire notification and remove waiter
  10422. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  10423. if not waiter_info:
  10424. return # Another callback already handled it
  10425. bed_cool_logger = logging.getLogger(__name__)
  10426. bed_cool_logger.info(
  10427. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  10428. bed_temp,
  10429. printer_id,
  10430. threshold,
  10431. )
  10432. try:
  10433. printer_info = printer_manager.get_printer(printer_id)
  10434. p_name = printer_info.name if printer_info else "Unknown"
  10435. async with async_session() as db:
  10436. await notification_service.on_bed_cooled(
  10437. printer_id=printer_id,
  10438. printer_name=p_name,
  10439. bed_temp=bed_temp,
  10440. threshold=threshold,
  10441. filename=waiter_info["filename"],
  10442. db=db,
  10443. )
  10444. except Exception as e:
  10445. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  10446. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  10447. async def on_drying_complete(printer_id: int, ams_id: int):
  10448. """Smart-plug auto-off-after-drying trigger (#1349).
  10449. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  10450. manager walks all plugs linked to this printer and turns off only
  10451. the ones with ``auto_off_after_drying`` enabled, after their
  10452. per-plug delay. Multiple AMS units finishing close together (e.g. a
  10453. dual-AMS dry that ends within the same MQTT push) call this once
  10454. per unit — the manager's ``_cancel_pending_off`` collapses
  10455. repeated scheduling on the same plug to one timer, so duplicate
  10456. fires are safe.
  10457. """
  10458. try:
  10459. async with async_session() as db:
  10460. await smart_plug_manager.on_drying_complete(printer_id, db)
  10461. except Exception as e:
  10462. logging.getLogger(__name__).warning(
  10463. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  10464. printer_id,
  10465. ams_id,
  10466. e,
  10467. )
  10468. printer_manager.set_drying_complete_callback(on_drying_complete)
  10469. async def on_drying_cycle_end(printer_id: int, cycle):
  10470. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  10471. from backend.app.services.spool_drying import record_drying_cycle
  10472. try:
  10473. async with async_session() as db:
  10474. await record_drying_cycle(db, printer_id, cycle)
  10475. except Exception as e:
  10476. logging.getLogger(__name__).warning(
  10477. "Failed to record drying for printer %d (AMS %d): %s",
  10478. printer_id,
  10479. cycle.ams_id,
  10480. e,
  10481. )
  10482. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  10483. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  10484. """Surface the read-back result of a spool assignment to the UI (#2582).
  10485. The MQTT client confirms (or fails to confirm) that the tray telemetry
  10486. echoed back the filament id we pushed. We relay that as a websocket
  10487. event so the frontend can toast "loaded" / "assignment didn't take"
  10488. instead of the historic silent fire-and-forget, which made the
  10489. AMS→Studio hand-off feel random to users.
  10490. """
  10491. try:
  10492. from backend.app.services.spool_assignment_notifications import (
  10493. _slot_label_from_global_tray,
  10494. )
  10495. if ams_id == 255:
  10496. global_id = 254 + tray_id
  10497. elif ams_id >= 128:
  10498. global_id = ams_id
  10499. else:
  10500. global_id = ams_id * 4 + tray_id
  10501. slot_label = _slot_label_from_global_tray(global_id)
  10502. printer_info = printer_manager.get_printer(printer_id)
  10503. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  10504. await ws_manager.broadcast(
  10505. {
  10506. "type": "spool_assignment_verified",
  10507. "printer_id": printer_id,
  10508. "printer_name": printer_name,
  10509. "ams_id": ams_id,
  10510. "tray_id": tray_id,
  10511. "slot": slot_label,
  10512. "verified": verified,
  10513. # Present on success: False means the filament setting landed
  10514. # but the K-profile (cali_idx) did not — the reporter's exact
  10515. # "loaded but no flow profile" symptom.
  10516. "kprofile_applied": detail.get("kprofile_applied", True),
  10517. }
  10518. )
  10519. except Exception as e:
  10520. logging.getLogger(__name__).warning(
  10521. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  10522. printer_id,
  10523. ams_id,
  10524. tray_id,
  10525. e,
  10526. )
  10527. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  10528. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  10529. """Persist a mid-print tray change for completion-time attribution.
  10530. AMS filament backup switches trays without telling the slicer, so the
  10531. tray-change log is the only record of which spool fed which layers.
  10532. Keeping it only in memory meant a restart mid-print charged everything
  10533. to the tray that finished the job.
  10534. """
  10535. try:
  10536. from backend.app.services.usage_tracker import record_tray_change
  10537. async with async_session() as db:
  10538. await record_tray_change(db, printer_id, tray_global, layer_num)
  10539. except Exception as e:
  10540. logging.getLogger(__name__).warning(
  10541. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  10542. printer_id,
  10543. tray_global,
  10544. layer_num,
  10545. e,
  10546. )
  10547. printer_manager.set_tray_change_callback(on_tray_change)
  10548. # Initialize MQTT relay from settings
  10549. async with async_session() as db:
  10550. from backend.app.api.routes.settings import get_setting
  10551. mqtt_settings = {
  10552. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  10553. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  10554. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  10555. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  10556. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  10557. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  10558. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  10559. }
  10560. await mqtt_relay.configure(mqtt_settings)
  10561. # Restore MQTT smart plug subscriptions
  10562. if mqtt_settings.get("mqtt_enabled"):
  10563. from backend.app.models.smart_plug import SmartPlug
  10564. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  10565. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  10566. mqtt_plugs = result.scalars().all()
  10567. restored = 0
  10568. for plug in mqtt_plugs:
  10569. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  10570. restored += 1
  10571. if restored:
  10572. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  10573. # Connect to all active printers
  10574. async with async_session() as db:
  10575. await init_printer_connections(db)
  10576. # Auto-connect to Spoolman if enabled
  10577. async with async_session() as db:
  10578. from backend.app.api.routes.settings import get_setting
  10579. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  10580. spoolman_url = await get_setting(db, "spoolman_url")
  10581. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  10582. try:
  10583. client = await init_spoolman_client(spoolman_url)
  10584. if await client.health_check():
  10585. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  10586. # Ensure the 'tag' extra field exists for RFID/UUID storage
  10587. field_ok = await client.ensure_tag_extra_field()
  10588. if not field_ok:
  10589. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  10590. # Register the BambuStudio slicer-preset fields used by the
  10591. # spool-edit / assign flow. Spoolman rejects PATCHes with
  10592. # unknown extra keys, so these must exist before any update
  10593. # that touches them.
  10594. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  10595. if not await client.ensure_extra_field(field_name):
  10596. logging.warning(
  10597. "Spoolman extra field %r registration failed — "
  10598. "spool slicer-preset edits will return 502",
  10599. field_name,
  10600. )
  10601. else:
  10602. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  10603. except Exception as e:
  10604. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  10605. # Start the print scheduler
  10606. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  10607. # Start the smart plug scheduler for time-based on/off
  10608. smart_plug_manager.start_scheduler()
  10609. # Start the Home Assistant sensor poller (#1148)
  10610. ha_sensor_manager.start()
  10611. location_ha_sensor_manager.start()
  10612. # Resume any pending auto-offs that were interrupted by restart
  10613. await smart_plug_manager.resume_pending_auto_offs()
  10614. # Start the notification digest scheduler
  10615. notification_service.start_digest_scheduler()
  10616. notify_live_activities.start()
  10617. notify_widgets.start()
  10618. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  10619. # provider in reactions/both mode; the notification routes resync them.
  10620. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  10621. # until the next provider save, not the whole startup.
  10622. try:
  10623. await telegram_reaction_poller.start()
  10624. except Exception as e:
  10625. logging.warning("Telegram reaction poller did not start: %s", e)
  10626. # Start the GitHub backup scheduler
  10627. await github_backup_service.start_scheduler()
  10628. # Start the local backup scheduler
  10629. await local_backup_service.start_scheduler()
  10630. await obico_detection_service.start()
  10631. # Start the library trash sweeper (#1008)
  10632. await library_trash_service.start_scheduler()
  10633. # Start the archive auto-purge sweeper (#1008 follow-up)
  10634. await archive_purge_service.start_scheduler()
  10635. # Start AMS history recording
  10636. start_ams_history_recording()
  10637. # Start printer sensor (nozzle / bed / chamber) history recording
  10638. start_printer_sensor_history_recording()
  10639. # Start printer runtime tracking
  10640. start_runtime_tracking()
  10641. # Start SpoolBuddy device watchdog
  10642. start_spoolbuddy_watchdog()
  10643. # Start camera stream orphan cleanup
  10644. start_camera_cleanup()
  10645. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  10646. start_connection_watchdog()
  10647. # One-shot sweep for timelapse session directories orphaned by a crash
  10648. # or restart that happened mid-print (in-memory session tracking can't
  10649. # survive that, and nothing else reaps the leftover frames/output file)
  10650. try:
  10651. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10652. removed = cleanup_orphaned_timelapse_sessions()
  10653. if removed:
  10654. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  10655. except Exception as e:
  10656. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  10657. # Start expected-print TTL eviction (prevents memory leak when prints are
  10658. # registered but on_print_start never fires)
  10659. start_expected_prints_cleanup()
  10660. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  10661. start_auth_cleanup()
  10662. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  10663. from backend.app.services import announcements as announcements_service
  10664. announcements_service.start()
  10665. from backend.app.services.printer_media import start_printer_download_cleanup
  10666. start_printer_download_cleanup()
  10667. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  10668. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  10669. from backend.app.services.loop_watchdog import start_loop_watchdog
  10670. start_loop_watchdog()
  10671. # Initialize virtual printer manager and sync from DB
  10672. from backend.app.services.virtual_printer import virtual_printer_manager
  10673. virtual_printer_manager.set_session_factory(async_session)
  10674. virtual_printer_manager.set_printer_manager(printer_manager)
  10675. try:
  10676. await virtual_printer_manager.sync_from_db()
  10677. logging.info("Virtual printer manager synced from database")
  10678. except Exception as e:
  10679. logging.warning("Failed to sync virtual printers: %s", e)
  10680. yield
  10681. # Shutdown
  10682. print_scheduler.stop()
  10683. smart_plug_manager.stop_scheduler()
  10684. ha_sensor_manager.stop()
  10685. location_ha_sensor_manager.stop()
  10686. notification_service.stop_digest_scheduler()
  10687. await notify_live_activities.close()
  10688. await notify_widgets.close()
  10689. await telegram_reaction_poller.aclose()
  10690. github_backup_service.stop_scheduler()
  10691. local_backup_service.stop_scheduler()
  10692. library_trash_service.stop_scheduler()
  10693. archive_purge_service.stop_scheduler()
  10694. obico_detection_service.stop()
  10695. stop_ams_history_recording()
  10696. stop_printer_sensor_history_recording()
  10697. stop_runtime_tracking()
  10698. stop_spoolbuddy_watchdog()
  10699. stop_camera_cleanup()
  10700. stop_connection_watchdog()
  10701. from backend.app.services.loop_watchdog import stop_loop_watchdog
  10702. stop_loop_watchdog()
  10703. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  10704. # cleanly rather than waiting on a queue that nothing will ever fill.
  10705. try:
  10706. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  10707. await shutdown_all_broadcasters()
  10708. except Exception as e:
  10709. logging.warning("Failed to shut down camera broadcasters: %s", e)
  10710. stop_expected_prints_cleanup()
  10711. stop_auth_cleanup()
  10712. from backend.app.services import announcements as announcements_service
  10713. announcements_service.stop()
  10714. from backend.app.services.printer_media import stop_printer_download_cleanup
  10715. await stop_printer_download_cleanup()
  10716. # Stops a timelapse editor's ffmpeg rather than leaving it to the OS.
  10717. from backend.app.services import timelapse_jobs
  10718. await timelapse_jobs.cancel_all()
  10719. printer_manager.disconnect_all()
  10720. slot_unlink_grace.reset()
  10721. await close_spoolman_client()
  10722. # Stop all virtual printer services
  10723. await virtual_printer_manager.stop_all()
  10724. await mqtt_smart_plug_service.disconnect(timeout=2)
  10725. await mqtt_relay.disconnect(timeout=2)
  10726. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  10727. set_shared_http_client(None)
  10728. set_shared_makerworld_http_client(None)
  10729. set_shared_orca_http_client(None)
  10730. await _shared_cloud_http_client.aclose()
  10731. # Checkpoint WAL (SQLite only) and close all database connections
  10732. from backend.app.core.db_dialect import is_sqlite
  10733. if is_sqlite():
  10734. try:
  10735. async with engine.begin() as conn:
  10736. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  10737. logging.info("WAL checkpoint completed")
  10738. except Exception as e:
  10739. logging.warning("WAL checkpoint failed: %s", e)
  10740. await engine.dispose()
  10741. app = FastAPI(
  10742. title=app_settings.app_name,
  10743. description="Archive and manage Bambu Lab 3MF files",
  10744. version=APP_VERSION,
  10745. lifespan=lifespan,
  10746. )
  10747. # Added first so it sits innermost, next to the routes: a refused header's value
  10748. # (often a stored token) masked in every JSON body. See core.response_redaction.
  10749. app.add_middleware(RefusedHeaderResponseMask)
  10750. def _json_safe(value):
  10751. """The validation errors with every non-finite number written as text."""
  10752. if isinstance(value, float) and not math.isfinite(value):
  10753. return str(value)
  10754. if isinstance(value, dict):
  10755. return {key: _json_safe(item) for key, item in value.items()}
  10756. if isinstance(value, list | tuple):
  10757. return [_json_safe(item) for item in value]
  10758. return value
  10759. @app.exception_handler(RequestValidationError)
  10760. async def _validation_error(_request, exc: RequestValidationError) -> JSONResponse:
  10761. """FastAPI's own 422, except that it survives a non-finite number.
  10762. A body may carry ``Infinity`` or ``NaN`` (Python's JSON reader accepts
  10763. them), and the default handler echoes the input back in its errors,
  10764. which JSON cannot hold: the request ended in an error instead of a 422.
  10765. """
  10766. return JSONResponse(status_code=422, content={"detail": _json_safe(jsonable_encoder(exc.errors()))})
  10767. # =============================================================================
  10768. # Authentication Middleware - Secures ALL API routes by default
  10769. # =============================================================================
  10770. # Public routes that don't require authentication even when auth is enabled
  10771. PUBLIC_API_ROUTES = {
  10772. # Auth routes needed before/during login
  10773. "/api/v1/auth/status",
  10774. "/api/v1/auth/login",
  10775. "/api/v1/auth/setup", # Needed for initial setup and recovery
  10776. # Advanced auth status needed for login page
  10777. "/api/v1/auth/advanced-auth/status",
  10778. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  10779. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  10780. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  10781. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  10782. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  10783. # OIDC routes that must be reachable without a JWT
  10784. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  10785. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  10786. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  10787. # Connected apps: the app's server swaps a code for the user's identity,
  10788. # authenticated by its client secret rather than a login token.
  10789. "/api/v1/connect/token",
  10790. # Version check for updates (no sensitive data)
  10791. "/api/v1/updates/version",
  10792. # Metrics endpoint handles its own prometheus_token authentication
  10793. "/api/v1/metrics",
  10794. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  10795. # this BEFORE a JWT is available to pick up the firstboot wizard's
  10796. # hostname / timezone / locale and the chrony NTP-gate state. The
  10797. # response contains user-set defaults and a public sync flag — no
  10798. # secrets. Without this entry the global auth middleware returns 401
  10799. # before the route handler runs, regardless of the route's own
  10800. # "no auth required" intent.
  10801. "/api/v1/system/appliance",
  10802. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  10803. # authenticates with a long-lived ``camwall``-scoped token in the query
  10804. # string — exactly like the camera streams two lists below, and for the same
  10805. # reason (no header to put a JWT in). "Public" here only means the middleware
  10806. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  10807. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  10808. # plain ``camera_stream`` token does NOT open this door.
  10809. "/api/v1/camwall/printers",
  10810. # Overlay branding: the route enforces overlay-scoped token authentication.
  10811. "/api/v1/overlay-branding/logo",
  10812. }
  10813. # Route prefixes that are public (for routes with dynamic segments)
  10814. PUBLIC_API_PREFIXES = [
  10815. # WebSocket connections handle their own auth
  10816. "/api/v1/ws",
  10817. # OIDC authorize redirects — include provider_id in path
  10818. "/api/v1/auth/oidc/authorize/",
  10819. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  10820. # a phone with no session, so no header can carry a JWT — the single-use
  10821. # capability token in the path IS the credential (same reasoning as the
  10822. # /dl/ slicer downloads below). The route grants nothing beyond writing
  10823. # good/reject on the one archive the token was minted for.
  10824. "/api/v1/archives/confirm/",
  10825. ]
  10826. # Route patterns that are public (read-only display data)
  10827. # These are checked with "in path" - needed because browsers load images/videos
  10828. # via <img src> and <video src> which don't include Authorization headers
  10829. PUBLIC_API_PATTERNS = [
  10830. # Thumbnails
  10831. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  10832. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  10833. # Images and media
  10834. "/photos/", # /archives/{id}/photos/{filename}
  10835. "/project-image/", # /archives/{id}/project-image/{path}
  10836. "/qrcode", # /archives/{id}/qrcode
  10837. "/timelapse", # /archives/{id}/timelapse (video)
  10838. "/cover", # /printers/{id}/cover
  10839. "/icon", # /external-links/{id}/icon
  10840. # Camera (streams loaded via <img> tag)
  10841. "/camera/stream", # /printers/{id}/camera/stream
  10842. "/camera/snapshot", # /printers/{id}/camera/snapshot
  10843. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  10844. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  10845. # string (same reasoning as the camera streams above — no header to carry a
  10846. # JWT). "Public" only means the middleware steps aside; the route still runs
  10847. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  10848. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  10849. "/overlay-status", # /printers/{id}/overlay-status
  10850. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  10851. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  10852. # download token in the URL path instead.
  10853. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  10854. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  10855. # and these patterns match by substring. Without its own entry the middleware
  10856. # 401s the slicer's header-less request before the route's token check runs,
  10857. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  10858. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  10859. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  10860. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  10861. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  10862. ]
  10863. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  10864. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  10865. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  10866. Format: comma-separated list of ``scheme://host[:port]`` origins.
  10867. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  10868. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  10869. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  10870. Invalid entries are dropped with a warning rather than failing startup, so
  10871. a typo in one origin doesn't take the whole deployment down.
  10872. """
  10873. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  10874. if not raw:
  10875. return ()
  10876. valid: list[str] = []
  10877. for item in raw.split(","):
  10878. candidate = item.strip()
  10879. if not candidate:
  10880. continue
  10881. try:
  10882. parsed = urlparse(candidate)
  10883. except ValueError as e:
  10884. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  10885. continue
  10886. if parsed.scheme not in ("http", "https"):
  10887. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  10888. continue
  10889. if not parsed.netloc:
  10890. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  10891. continue
  10892. if parsed.path and parsed.path != "/":
  10893. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  10894. continue
  10895. if parsed.query or parsed.fragment:
  10896. _security_headers_logger.warning(
  10897. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  10898. )
  10899. continue
  10900. if "*" in parsed.netloc:
  10901. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  10902. continue
  10903. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  10904. if valid:
  10905. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  10906. return tuple(valid)
  10907. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  10908. def _frame_ancestors(default_value: str) -> str:
  10909. """Compose the ``frame-ancestors`` CSP directive (#1191).
  10910. ``default_value`` is the strict directive used when the operator has not
  10911. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  10912. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  10913. Settings URL builder's preview). When trusted origins
  10914. are configured, ``'self'`` is always included so same-origin embedding never
  10915. breaks even if an operator forgets to add their own origin to the list.
  10916. """
  10917. if _TRUSTED_FRAME_ORIGINS:
  10918. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  10919. return f"frame-ancestors {default_value};"
  10920. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  10921. # patterns are anchored on the exact emitted name so the relaxed policies
  10922. # below can never apply to any other asset.
  10923. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  10924. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  10925. # -> /assets/pdf.worker.min-<hash>.js
  10926. # Vite also emits a one-line chunk under the second name that only exports the
  10927. # worker's URL. The page imports it as a module, and a module script is run
  10928. # under the importing document's policy, never its own response's, so it
  10929. # matching as well changes nothing.
  10930. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  10931. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  10932. @app.middleware("http")
  10933. async def security_headers_middleware(request, call_next):
  10934. """Add standard HTTP security headers to every response."""
  10935. # Per-request nonce stamped into `script-src` (#1460). On its own this
  10936. # changes nothing for Bambuddy's own pages — index.html has no inline
  10937. # scripts since the SW registration moved to /sw-register.js. The reason
  10938. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  10939. # script injected into the HTML on the edge, with a fresh hash on every
  10940. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  10941. # it clones the same nonce onto its injected <script>, and the inline
  10942. # script passes the policy without us needing 'unsafe-inline'. See
  10943. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  10944. csp_nonce = secrets.token_urlsafe(16)
  10945. # Routes that render their own HTML need it too, or their inline script is
  10946. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  10947. # one that does: it submits its own form so a verdict still costs one tap.
  10948. request.state.csp_nonce = csp_nonce
  10949. response = await call_next(request)
  10950. response.headers["X-Content-Type-Options"] = "nosniff"
  10951. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  10952. # browsers honour CSP frame-ancestors instead, and the legacy
  10953. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  10954. # When operators have explicitly allowlisted trusted frame origins (#1191
  10955. # — typically Home Assistant on a different port), drop X-Frame-Options
  10956. # and let the CSP-side frame-ancestors directive govern embedding.
  10957. if not _TRUSTED_FRAME_ORIGINS:
  10958. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  10959. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  10960. # Content-Security-Policy for the React SPA.
  10961. # Notes:
  10962. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  10963. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  10964. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  10965. # - media-src blob:: timelapse video player uses Blob URLs.
  10966. # - font-src data:: some icon fonts are embedded as data URIs.
  10967. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  10968. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  10969. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  10970. # default CSP would render a blank page.
  10971. response.headers["Content-Security-Policy"] = (
  10972. "default-src 'self'; "
  10973. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  10974. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  10975. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  10976. "connect-src 'self'; "
  10977. "font-src 'self' data: https://fonts.gstatic.com; "
  10978. "worker-src 'self' blob:; "
  10979. "object-src 'none'; "
  10980. "base-uri 'self'; " + _frame_ancestors("'none'")
  10981. )
  10982. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  10983. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  10984. # its emscripten/embind glue generates invoker functions with `new
  10985. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  10986. # worker is governed by the policy delivered with the WORKER SCRIPT's
  10987. # own response — not the document's — so relaxing it here confines
  10988. # eval to that DOM-less worker context. The document policy below
  10989. # stays nonce-strict, and this response header has no effect when the
  10990. # file is merely fetched (a fetch's CSP is enforced against the
  10991. # requesting document, not the resource's own headers).
  10992. response.headers["Content-Security-Policy"] = (
  10993. "default-src 'self'; "
  10994. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  10995. "connect-src 'self'; "
  10996. "object-src 'none'; "
  10997. "base-uri 'self'; " + _frame_ancestors("'none'")
  10998. )
  10999. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  11000. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  11001. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  11002. # rule as the STEP worker above: the policy that governs a dedicated
  11003. # worker is the one delivered with its own script, so the wasm compile
  11004. # has to be permitted here rather than on the document. Unlike the STEP
  11005. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  11006. response.headers["Content-Security-Policy"] = (
  11007. "default-src 'self'; "
  11008. "script-src 'self' 'wasm-unsafe-eval'; "
  11009. "connect-src 'self'; "
  11010. "object-src 'none'; "
  11011. "base-uri 'self'; " + _frame_ancestors("'none'")
  11012. )
  11013. else:
  11014. # The streaming overlay is embedded same-origin by the URL builder's
  11015. # preview in Settings (#1422), so this branch allows 'self'.
  11016. # Embedding from anywhere else is still refused: 'self'
  11017. # only permits a framer on this origin, which is Bambuddy's own UI, so
  11018. # a clickjacking page on another host is blocked exactly as before.
  11019. # (The overlay draws status over a camera feed and its only interactive
  11020. # element is the logo link, so there is nothing to bait a click into
  11021. # even from a same-origin framer.) Cross-origin embedding of the
  11022. # overlay — Home Assistant on another port — remains what
  11023. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  11024. # allowlist in.
  11025. #
  11026. # The connected-app consent page (/connect/authorize) gets the same
  11027. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  11028. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  11029. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  11030. # requires every ancestor to be this origin, so a foreign page -- a
  11031. # sidebar link's site included -- still cannot frame the consent
  11032. # screen to bait a click.
  11033. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  11034. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  11035. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  11036. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  11037. # the policy served with their own script, so each gets it in its own
  11038. # branch above and the document policy stays as strict as it was.
  11039. response.headers["Content-Security-Policy"] = (
  11040. "default-src 'self'; "
  11041. f"script-src 'self' 'nonce-{csp_nonce}'; "
  11042. "style-src 'self' 'unsafe-inline'; "
  11043. "img-src 'self' data: blob:; "
  11044. "media-src 'self' blob:; "
  11045. "connect-src 'self' ws: wss:; "
  11046. "font-src 'self' data:; "
  11047. "object-src 'none'; "
  11048. "base-uri 'self'; "
  11049. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  11050. )
  11051. if request.url.scheme == "https":
  11052. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  11053. return response
  11054. @app.middleware("http")
  11055. async def auth_middleware(request, call_next):
  11056. """Enforce authentication on all API routes when auth is enabled.
  11057. This middleware provides defense-in-depth by checking auth at the API gateway level,
  11058. regardless of whether individual routes have auth dependencies.
  11059. """
  11060. from starlette.responses import JSONResponse
  11061. path = request.url.path
  11062. # Only apply to API routes
  11063. if not path.startswith("/api/"):
  11064. return await call_next(request)
  11065. # Allow public routes
  11066. if path in PUBLIC_API_ROUTES:
  11067. return await call_next(request)
  11068. # Allow public prefixes
  11069. for prefix in PUBLIC_API_PREFIXES:
  11070. if path.startswith(prefix):
  11071. return await call_next(request)
  11072. # Allow public patterns (read-only display data like thumbnails)
  11073. for pattern in PUBLIC_API_PATTERNS:
  11074. if pattern in path:
  11075. return await call_next(request)
  11076. # Check if auth is enabled. Fail CLOSED on any exception during the
  11077. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  11078. # an attacker who could force a DB exception (e.g. file-descriptor
  11079. # exhaustion via login flood) bypass auth on every protected endpoint.
  11080. # Only the probe is guarded: the request itself runs outside the try, so an
  11081. # error in a route surfaces as the 500 it is rather than as an auth outage.
  11082. try:
  11083. async with async_session() as db:
  11084. from backend.app.core.auth import is_auth_enabled
  11085. auth_enabled = await is_auth_enabled(db)
  11086. except Exception:
  11087. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  11088. return JSONResponse(
  11089. status_code=503,
  11090. content={"detail": "Authentication service temporarily unavailable"},
  11091. )
  11092. if not auth_enabled:
  11093. # Auth disabled, allow all requests
  11094. return await call_next(request)
  11095. # Auth is enabled - require valid token
  11096. auth_header = request.headers.get("Authorization")
  11097. x_api_key = request.headers.get("X-API-Key")
  11098. # Check for API key auth first
  11099. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  11100. # API key authentication - let the request through to be validated by route handler
  11101. # API keys are validated per-route since they have different permission levels
  11102. return await call_next(request)
  11103. # Check for JWT auth
  11104. if not auth_header or not auth_header.startswith("Bearer "):
  11105. return JSONResponse(
  11106. status_code=401,
  11107. content={"detail": "Authentication required"},
  11108. headers={"WWW-Authenticate": "Bearer"},
  11109. )
  11110. # Validate JWT token
  11111. import jwt
  11112. try:
  11113. from backend.app.core.auth import (
  11114. ALGORITHM,
  11115. SECRET_KEY,
  11116. _is_token_fresh,
  11117. get_user_by_username,
  11118. is_jti_revoked,
  11119. )
  11120. token = auth_header.replace("Bearer ", "")
  11121. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  11122. username = payload.get("sub")
  11123. if not username:
  11124. raise ValueError("No username in token")
  11125. jti = payload.get("jti")
  11126. if not jti:
  11127. raise ValueError("No jti in token")
  11128. iat = payload.get("iat")
  11129. # Verify user exists, is active, and token is still fresh (L-R8-A).
  11130. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  11131. # this session so the gateway adds a single pooled checkout, not two (#2572).
  11132. async with async_session() as db:
  11133. if await is_jti_revoked(jti, db):
  11134. return JSONResponse(
  11135. status_code=401,
  11136. content={"detail": "Token has been revoked"},
  11137. headers={"WWW-Authenticate": "Bearer"},
  11138. )
  11139. user = await get_user_by_username(db, username)
  11140. if not user or not user.is_active:
  11141. return JSONResponse(
  11142. status_code=401,
  11143. content={"detail": "User not found or inactive"},
  11144. headers={"WWW-Authenticate": "Bearer"},
  11145. )
  11146. if not _is_token_fresh(iat, user):
  11147. return JSONResponse(
  11148. status_code=401,
  11149. content={"detail": "Token no longer valid"},
  11150. headers={"WWW-Authenticate": "Bearer"},
  11151. )
  11152. except jwt.ExpiredSignatureError:
  11153. return JSONResponse(
  11154. status_code=401,
  11155. content={"detail": "Token has expired"},
  11156. headers={"WWW-Authenticate": "Bearer"},
  11157. )
  11158. except (jwt.InvalidTokenError, ValueError):
  11159. return JSONResponse(
  11160. status_code=401,
  11161. content={"detail": "Invalid token"},
  11162. headers={"WWW-Authenticate": "Bearer"},
  11163. )
  11164. except Exception:
  11165. # Not a bad token but a failure checking it (database, pool): refuse,
  11166. # as for the probe above, rather than answer 401 -- the frontend reads
  11167. # a 401 from /auth/me as final and signs the user out.
  11168. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  11169. return JSONResponse(
  11170. status_code=503,
  11171. content={"detail": "Authentication service temporarily unavailable"},
  11172. )
  11173. return await call_next(request)
  11174. @app.middleware("http")
  11175. async def trace_id_middleware(request, call_next):
  11176. """Stamp every HTTP request with a trace ID and echo it back.
  11177. Decorated AFTER auth_middleware on purpose: Starlette stacks
  11178. @app.middleware decorators LIFO, so the last-decorated runs first
  11179. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  11180. which means auth-middleware log lines (and every line emitted on the
  11181. way down to and back from the route handler) all carry the same
  11182. trace ID. If we put it before auth, auth's logs would be stamped
  11183. with the *previous* request's ID — useless for correlation.
  11184. Honours an inbound ``X-Trace-Id`` header so callers running their
  11185. own tracing can correlate their span IDs with our log lines, but
  11186. only if the value passes the whitelist gate in
  11187. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  11188. rejected (too long, contains control chars, etc.) silently triggers
  11189. a freshly minted server-side ID rather than failing the request.
  11190. The minted (or echoed) ID is set on a ContextVar so that every log
  11191. record emitted during the request — application logs *and* uvicorn's
  11192. access log — carries it via TraceIDFilter, and is also written to
  11193. the ``X-Trace-Id`` response header so clients can pin a server-side
  11194. log search to the exact request they made.
  11195. """
  11196. from backend.app.core.trace import (
  11197. generate_trace_id,
  11198. normalise_inbound_trace_id,
  11199. trace_id_var,
  11200. )
  11201. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  11202. trace_id = inbound if inbound is not None else generate_trace_id()
  11203. token = trace_id_var.set(trace_id)
  11204. try:
  11205. response = await call_next(request)
  11206. finally:
  11207. # Reset the ContextVar so a record emitted in a totally
  11208. # unrelated background task that just happens to inherit this
  11209. # context doesn't keep referencing this request's ID forever.
  11210. # In practice ContextVar.reset is best-effort under asyncio
  11211. # task-spawn semantics, but the cost is one attribute write so
  11212. # we may as well do it.
  11213. trace_id_var.reset(token)
  11214. response.headers["X-Trace-Id"] = trace_id
  11215. return response
  11216. # API routes
  11217. app.include_router(auth.router, prefix=app_settings.api_prefix)
  11218. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  11219. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  11220. app.include_router(users.router, prefix=app_settings.api_prefix)
  11221. app.include_router(groups.router, prefix=app_settings.api_prefix)
  11222. app.include_router(printers.router, prefix=app_settings.api_prefix)
  11223. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  11224. app.include_router(archives.router, prefix=app_settings.api_prefix)
  11225. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  11226. app.include_router(finance.router, prefix=app_settings.api_prefix)
  11227. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  11228. app.include_router(labels.router, prefix=app_settings.api_prefix)
  11229. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  11230. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  11231. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  11232. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  11233. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  11234. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  11235. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  11236. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  11237. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  11238. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  11239. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  11240. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  11241. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  11242. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  11243. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  11244. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  11245. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  11246. app.include_router(updates.router, prefix=app_settings.api_prefix)
  11247. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  11248. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  11249. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  11250. app.include_router(camera.router, prefix=app_settings.api_prefix)
  11251. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  11252. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  11253. app.include_router(projects.router, prefix=app_settings.api_prefix)
  11254. app.include_router(library.router, prefix=app_settings.api_prefix)
  11255. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  11256. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  11257. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  11258. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  11259. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  11260. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  11261. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  11262. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  11263. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  11264. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  11265. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  11266. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  11267. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  11268. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  11269. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  11270. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  11271. app.include_router(system.router, prefix=app_settings.api_prefix)
  11272. app.include_router(support.router, prefix=app_settings.api_prefix)
  11273. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  11274. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  11275. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  11276. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  11277. app.include_router(bulk.router, prefix=app_settings.api_prefix)
  11278. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  11279. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  11280. app.include_router(obico.router, prefix=app_settings.api_prefix)
  11281. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  11282. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  11283. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  11284. # Serve static files (React build)
  11285. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  11286. # Compressed, and cached for good where Vite hashed the name (#3175).
  11287. app.mount(
  11288. "/assets",
  11289. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  11290. name="assets",
  11291. )
  11292. if (app_settings.static_dir / "img").exists():
  11293. app.mount(
  11294. "/img",
  11295. StaticFiles(directory=app_settings.static_dir / "img"),
  11296. name="img",
  11297. )
  11298. if (app_settings.static_dir / "icons").exists():
  11299. app.mount(
  11300. "/icons",
  11301. StaticFiles(directory=app_settings.static_dir / "icons"),
  11302. name="icons",
  11303. )
  11304. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  11305. # falls through to the SPA catch-all and returns index.html, which the
  11306. # browser's font sanitizer rejects ("downloadable font: rejected by
  11307. # sanitizer").
  11308. if (app_settings.static_dir / "fonts").exists():
  11309. app.mount(
  11310. "/fonts",
  11311. StaticFiles(directory=app_settings.static_dir / "fonts"),
  11312. name="fonts",
  11313. )
  11314. @app.get("/")
  11315. async def serve_frontend():
  11316. """Serve the React frontend."""
  11317. index_file = app_settings.static_dir / "index.html"
  11318. if index_file.exists():
  11319. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11320. return {
  11321. "message": "Bambuddy API",
  11322. "docs": "/docs",
  11323. "frontend": "Build and place React app in /static directory",
  11324. }
  11325. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  11326. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  11327. # forever, but the HTML wrapping it is the only file that knows which hash
  11328. # is current. Without explicit cache-control headers Chromium decides
  11329. # heuristically (typically 10% of the time since Last-Modified) and on
  11330. # long-running kiosks happily serves stale HTML across browser restarts.
  11331. # That stale HTML references an old bundle hash, the old bundle is also
  11332. # in the disk cache, and the user ends up running pre-update JS forever
  11333. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  11334. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  11335. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  11336. @app.get("/health")
  11337. async def health_check():
  11338. """Health check endpoint."""
  11339. return {"status": "healthy"}
  11340. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  11341. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  11342. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  11343. # in deployment debugging.
  11344. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  11345. async def serve_manifest():
  11346. """Serve PWA manifest."""
  11347. manifest_file = app_settings.static_dir / "manifest.json"
  11348. if manifest_file.exists():
  11349. return FileResponse(manifest_file, media_type="application/manifest+json")
  11350. return {"error": "Manifest not found"}
  11351. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  11352. async def serve_service_worker():
  11353. """Serve service worker."""
  11354. sw_file = app_settings.static_dir / "sw.js"
  11355. if sw_file.exists():
  11356. return FileResponse(
  11357. sw_file,
  11358. media_type="application/javascript",
  11359. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  11360. )
  11361. return {"error": "Service worker not found"}
  11362. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  11363. async def serve_sw_register():
  11364. """Serve the service-worker registration bootstrap script.
  11365. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  11366. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  11367. """
  11368. reg_file = app_settings.static_dir / "sw-register.js"
  11369. if reg_file.exists():
  11370. return FileResponse(reg_file, media_type="application/javascript")
  11371. return {"error": "sw-register.js not found"}
  11372. # ── GCode viewer static files ────────────────────────────────────────────────
  11373. # Catch-all route for React Router (must be last)
  11374. @app.get("/{full_path:path}")
  11375. async def serve_spa(full_path: str):
  11376. """Serve React app for client-side routing."""
  11377. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  11378. if full_path.startswith("api/"):
  11379. from fastapi import HTTPException
  11380. raise HTTPException(status_code=404, detail="Not found")
  11381. index_file = app_settings.static_dir / "index.html"
  11382. if index_file.exists():
  11383. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11384. return {"error": "Frontend not built"}