main.py 579 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import re
  8. import secrets
  9. import time
  10. from contextlib import asynccontextmanager
  11. from datetime import datetime, timedelta, timezone
  12. from logging.handlers import RotatingFileHandler
  13. from pathlib import Path, PurePosixPath
  14. from typing import cast
  15. from urllib.parse import urlparse
  16. from fastapi import FastAPI
  17. from fastapi.encoders import jsonable_encoder
  18. from fastapi.exceptions import RequestValidationError
  19. from fastapi.responses import FileResponse, JSONResponse
  20. from fastapi.staticfiles import StaticFiles
  21. from sqlalchemy import delete, func, inspect as sa_inspect, or_, select, text, update
  22. from sqlalchemy.engine import CursorResult
  23. from sqlalchemy.exc import IntegrityError
  24. from sqlalchemy.orm.exc import StaleDataError
  25. from backend.app.api.routes import (
  26. ams_history,
  27. announcements,
  28. api_keys,
  29. archive_purge,
  30. archives,
  31. auth,
  32. bug_report,
  33. camera,
  34. camwall,
  35. cloud,
  36. connected_apps,
  37. discovery,
  38. external_links,
  39. filaments,
  40. finance,
  41. firmware,
  42. github_backup,
  43. groups,
  44. ha_sensors,
  45. inventory,
  46. kprofiles,
  47. labels,
  48. library,
  49. library_tags,
  50. library_trash,
  51. library_variants,
  52. local_backup,
  53. local_presets,
  54. location_ha_sensors,
  55. maintenance,
  56. makerworld,
  57. manyfold,
  58. metrics,
  59. mfa,
  60. notification_templates,
  61. notifications,
  62. obico,
  63. orca_cloud,
  64. overlay_branding,
  65. pending_uploads,
  66. pipeline_runs,
  67. print_log,
  68. print_queue,
  69. printer_locations,
  70. printer_sensor_history,
  71. printers,
  72. projects,
  73. scheduled_dryings,
  74. settings as settings_routes,
  75. slice_jobs,
  76. slicer_pipelines,
  77. slicer_presets,
  78. smart_plugs,
  79. sponsor_prompt,
  80. spoolbuddy,
  81. spoolman,
  82. spoolman_inventory,
  83. support,
  84. system,
  85. updates,
  86. user_notifications,
  87. users,
  88. virtual_printers,
  89. webhook,
  90. websocket,
  91. )
  92. from backend.app.api.routes.maintenance import (
  93. _get_printer_maintenance_internal,
  94. ensure_default_types,
  95. maintenance_alert_values,
  96. )
  97. from backend.app.api.routes.support import init_debug_logging
  98. from backend.app.core.config import APP_VERSION, settings as app_settings
  99. from backend.app.core.database import async_session, engine, init_db
  100. from backend.app.core.static_assets import AssetStaticFiles
  101. from backend.app.core.tasks import spawn_background_task
  102. from backend.app.core.websocket import ws_manager
  103. from backend.app.services import kprofile_drift, print_dispatch_context, slot_unlink_grace
  104. from backend.app.services.ams_assignment_lock import get_ams_assignment_lock
  105. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  106. from backend.app.services.archive_cost_estimate import (
  107. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  108. settle_archive_cost_estimate as _settle_archive_cost_estimate,
  109. )
  110. from backend.app.services.archive_purge import archive_purge_service
  111. from backend.app.services.bambu_ftp import (
  112. RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  113. FileNotOnPrinterError,
  114. cache_3mf_download,
  115. clear_3mf_cache,
  116. download_file_async,
  117. download_file_try_paths_async,
  118. ftps_handshake_blocked,
  119. get_cached_3mf,
  120. get_ftp_retry_settings,
  121. normalize_3mf_name,
  122. with_ftp_retry,
  123. )
  124. from backend.app.services.bambu_mqtt import PrinterState
  125. from backend.app.services.camera_light import camera_light
  126. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  127. from backend.app.services.github_backup import github_backup_service
  128. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  129. from backend.app.services.library_trash import library_trash_service
  130. from backend.app.services.local_backup import local_backup_service
  131. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  132. from backend.app.services.mqtt_relay import mqtt_relay
  133. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  134. from backend.app.services.notification_service import notification_service
  135. from backend.app.services.notify_live_activities import notify_live_activities
  136. from backend.app.services.notify_widgets import notify_widgets
  137. from backend.app.services.obico_detection import obico_detection_service
  138. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  139. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  140. from backend.app.services.print_scheduler import scheduler as print_scheduler
  141. from backend.app.services.print_storage import (
  142. REASON_FTP_TRANSFER_FAILED,
  143. REASON_FTPS_COOLOFF,
  144. external_storage_present,
  145. ftp_probe_paths,
  146. print_file_reachable_over_ftp,
  147. )
  148. from backend.app.services.printer_manager import (
  149. init_printer_connections,
  150. parse_plate_id,
  151. printer_manager,
  152. printer_state_to_dict,
  153. resolve_plate_id,
  154. )
  155. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  156. from backend.app.services.slot_nozzle import (
  157. nozzle_diameter_for_extruder,
  158. nozzle_flow_for_extruder,
  159. )
  160. from backend.app.services.smart_plug_manager import smart_plug_manager
  161. from backend.app.services.spool_assignment_notifications import (
  162. notify_missing_spool_assignments_on_print_start,
  163. )
  164. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  165. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  166. from backend.app.services.spoolman_tracking import (
  167. cleanup_tracking as _cleanup_spoolman_tracking,
  168. release_archived_slot_rows as _release_archived_spoolman_slots,
  169. report_usage as _report_spoolman_usage,
  170. store_print_data as _store_spoolman_print_data,
  171. )
  172. from backend.app.services.telegram_reactions import telegram_reaction_poller
  173. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  174. from backend.app.utils.ams_humidity import ams_humidity_percent
  175. from backend.app.utils.filament_types import printer_filament_type
  176. from backend.app.utils.fts_routing import extruder_for_inlet
  177. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  178. from backend.app.utils.print_jobs import is_internal_printer_job
  179. # =============================================================================
  180. # Dependency Check - runs before other imports to give helpful error messages
  181. # =============================================================================
  182. def _start_error_server(missing_packages: list):
  183. """Start a minimal HTTP server to display dependency errors in browser."""
  184. import os
  185. import signal
  186. from http.server import BaseHTTPRequestHandler, HTTPServer
  187. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  188. html = f"""<!DOCTYPE html>
  189. <html>
  190. <head>
  191. <title>Bambuddy - Setup Required</title>
  192. <style>
  193. body {{
  194. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  195. background: #0f172a; color: #e2e8f0;
  196. display: flex; justify-content: center; align-items: center;
  197. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  198. }}
  199. .container {{
  200. background: #1e293b; border-radius: 12px; padding: 40px;
  201. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  202. }}
  203. h1 {{ color: #f87171; margin-bottom: 10px; }}
  204. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  205. .packages {{
  206. background: #0f172a; border-radius: 8px; padding: 20px;
  207. margin: 20px 0; text-align: left;
  208. }}
  209. .packages ul {{ margin: 0; padding-left: 20px; }}
  210. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  211. .command {{
  212. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  213. margin: 15px 0; font-family: monospace; color: #4ade80;
  214. text-align: left; overflow-x: auto;
  215. }}
  216. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  217. </style>
  218. </head>
  219. <body>
  220. <div class="container">
  221. <h1>Setup Required</h1>
  222. <h2>Missing Python packages</h2>
  223. <div class="packages"><ul>{packages_html}</ul></div>
  224. <p>To fix, run this command on your server:</p>
  225. <div class="command">pip install -r requirements.lock</div>
  226. <p>Or if using a virtual environment:</p>
  227. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  228. <p class="note">After installing, restart Bambuddy:<br>
  229. <code>sudo systemctl restart bambuddy</code></p>
  230. </div>
  231. </body>
  232. </html>"""
  233. class ErrorHandler(BaseHTTPRequestHandler):
  234. def do_GET(self):
  235. self.send_response(503)
  236. self.send_header("Content-type", "text/html")
  237. self.end_headers()
  238. self.wfile.write(html.encode())
  239. def log_message(self, format, *args):
  240. print(f"[Error Server] {args[0]}")
  241. port = int(os.environ.get("PORT", 8000))
  242. print(f"\nStarting error server on http://0.0.0.0:{port}")
  243. print("Visit this URL in your browser to see the error details.\n")
  244. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  245. def shutdown(signum, frame):
  246. print("\nShutting down error server...")
  247. raise SystemExit(0)
  248. signal.signal(signal.SIGTERM, shutdown)
  249. signal.signal(signal.SIGINT, shutdown)
  250. server.serve_forever()
  251. def check_dependencies():
  252. """Check that all required packages are installed."""
  253. missing = []
  254. # Map of import name -> package name (for pip install)
  255. required = {
  256. "jwt": "PyJWT",
  257. "fastapi": "fastapi",
  258. "uvicorn": "uvicorn",
  259. "sqlalchemy": "sqlalchemy",
  260. "aiosqlite": "aiosqlite",
  261. "pydantic": "pydantic",
  262. "paho.mqtt": "paho-mqtt",
  263. }
  264. for module, package in required.items():
  265. try:
  266. __import__(module)
  267. except ImportError:
  268. missing.append(package)
  269. if missing:
  270. print("\n" + "=" * 60)
  271. print("ERROR: Missing required Python packages!")
  272. print("=" * 60)
  273. print(f"\nMissing packages: {', '.join(missing)}")
  274. print("\nTo fix, run:")
  275. print(" pip install -r requirements.lock")
  276. print("\nOr if using a virtual environment:")
  277. print(" ./venv/bin/pip install -r requirements.lock")
  278. print("=" * 60 + "\n")
  279. _start_error_server(missing)
  280. check_dependencies()
  281. # =============================================================================
  282. # Import settings first for logging configuration
  283. # Configure logging based on settings
  284. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  285. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  286. log_level = getattr(logging, log_level_str, logging.INFO)
  287. # Trace ID column ([-] when no request scope is active — startup, MQTT
  288. # callbacks, scheduled tasks not chained from a request — so the column
  289. # stays visually aligned and missing values are obvious in grep). See
  290. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  291. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  292. # Create root logger
  293. root_logger = logging.getLogger()
  294. root_logger.setLevel(log_level)
  295. # Trace-ID injection: this filter populates record.trace_id from the
  296. # per-request ContextVar so the format string above can reference it.
  297. # Attached to each HANDLER (not the root logger) because Python's
  298. # logging semantics only invoke a logger's filters on records that
  299. # *originated* at that logger — records propagated up from child
  300. # loggers (every named logger in the app) never trigger root's filter.
  301. # Putting it on the handlers means every record any handler emits gets
  302. # trace_id injected just before the formatter runs, regardless of which
  303. # logger created the record. Without this, the formatter raises
  304. # KeyError on every child-logger record and the record is silently
  305. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  306. # partially" bug we hit. See backend/app/core/trace.py for the
  307. # ContextVar the filter reads.
  308. from backend.app.core.logging_filters import RefusedHeaderRedactFilter
  309. from backend.app.core.response_redaction import RefusedHeaderResponseMask
  310. from backend.app.core.trace import TraceIDFilter
  311. _trace_id_filter = TraceIDFilter()
  312. # Console handler - always enabled
  313. console_handler = logging.StreamHandler()
  314. console_handler.setLevel(log_level)
  315. console_handler.setFormatter(logging.Formatter(log_format))
  316. console_handler.addFilter(_trace_id_filter)
  317. # A refused header's value (often a token) masked before the line is written.
  318. _refused_header_filter = RefusedHeaderRedactFilter()
  319. console_handler.addFilter(_refused_header_filter)
  320. root_logger.addHandler(console_handler)
  321. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  322. """Send uvicorn's own loggers to bambuddy.log as well.
  323. Neither reaches the root handler: uvicorn.access has propagate=False, and
  324. uvicorn.error propagates only to "uvicorn", which has propagate=False.
  325. uvicorn.access is the record of which endpoint changed server state;
  326. uvicorn.error is where an unhandled route error is logged with its
  327. traceback ("Exception in ASGI application").
  328. """
  329. for name in ("uvicorn.access", "uvicorn.error"):
  330. logging.getLogger(name).addHandler(handler)
  331. # File handler - only in production or if explicitly enabled
  332. if app_settings.log_to_file:
  333. log_file = app_settings.log_dir / "bambuddy.log"
  334. file_handler = RotatingFileHandler(
  335. log_file,
  336. maxBytes=app_settings.log_max_bytes,
  337. backupCount=app_settings.log_backup_count,
  338. encoding="utf-8",
  339. )
  340. file_handler.setLevel(log_level)
  341. file_handler.setFormatter(logging.Formatter(log_format))
  342. file_handler.addFilter(_trace_id_filter)
  343. file_handler.addFilter(_refused_header_filter)
  344. root_logger.addHandler(file_handler)
  345. logging.info("Logging to file: %s", log_file)
  346. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  347. # access logger with propagate=False by default, so without this attach
  348. # there is no on-disk record of which endpoint triggered a server-state
  349. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  350. # for exactly this reason. Filtered to write methods only
  351. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  352. # frontend don't churn the rotation window faster than it's useful.
  353. from backend.app.core.logging_filters import (
  354. CancelledPoolNoiseFilter,
  355. WriteRequestsOnlyFilter,
  356. )
  357. _attach_file_handler_to_uvicorn(file_handler)
  358. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  359. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  360. # Uvicorn's access logger has propagate=False (its own default), so the
  361. # root-attached TraceIDFilter never sees these records. Attach a
  362. # second instance directly so HTTP access lines carry the same trace
  363. # ID column as the application logs they correlate with.
  364. uvicorn_access_logger.addFilter(TraceIDFilter())
  365. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  366. # BaseHTTPMiddleware cancelling the inner task scope on client
  367. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  368. # underlying transaction leak; this filter only suppresses the residual
  369. # log records that pre-existing pools still emit during their cleanup.
  370. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  371. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  372. # handler (console included), whether or not file logging is on.
  373. from backend.app.core.logging_filters import ( # noqa: E402
  374. QueryTokenRedactFilter,
  375. ShutdownCancelledRequestFilter,
  376. )
  377. # First, so the traceback of a stream cancelled at shutdown is dropped before
  378. # the filters below render it.
  379. logging.getLogger("uvicorn.error").addFilter(ShutdownCancelledRequestFilter())
  380. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  381. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  382. logging.getLogger(_uvicorn_logger).addFilter(_refused_header_filter)
  383. # These stay at WARNING even in debug mode: at INFO/DEBUG httpx/httpcore log
  384. # full request URLs, and some carry credentials (bot tokens, webhook URLs, API
  385. # keys in the query). Same as the runtime log-level toggle in support.py.
  386. logging.getLogger("httpcore").setLevel(logging.WARNING)
  387. logging.getLogger("httpx").setLevel(logging.WARNING)
  388. # aiosqlite logs every statement with its parameters at DEBUG.
  389. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  390. # Reduce noise from third-party libraries in production
  391. if not app_settings.debug:
  392. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  393. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  394. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  395. # Track active prints: {(printer_id, filename): archive_id}
  396. _active_prints: dict[tuple[int, str], int] = {}
  397. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  398. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  399. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  400. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  401. # instead of running its own grab-now chain when present, so the finish photo
  402. # captures the better-framed pre-bed-drop moment without us having to force
  403. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  404. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  405. #
  406. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  407. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  408. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  409. # bank and the others are not — so the consumer can't tell them apart and
  410. # must not rotate again.
  411. _stage22_finish_frames: dict[int, bytes] = {}
  412. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  413. # `finally` block (whether it captured a frame or not). The consumer in
  414. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  415. # so the FINISH-state fallback path — where moment and completion are dispatched
  416. # back-to-back — doesn't race past the producer with an empty pop, and the
  417. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  418. # grab (Bambu printers allow only one RTSP client at a time).
  419. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  420. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  421. # layer-change and on print-progress advances (#2547) while the model is still
  422. # printing, then consumed by the FINISH-state finish-photo path when the
  423. # dispatcher recorded that it injected End G-code into this print. Bambu
  424. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  425. # plate-swap) has run, so a live grab there would capture the swapped/empty
  426. # plate.
  427. #
  428. # The load-bearing property: both drivers are print telemetry that stops before
  429. # the End G-code executes — no further layer_num increases, and mc_percent
  430. # freezes — so the last banked frame is always the finished print before the
  431. # swap. Anything added as a third driver must hold that same property.
  432. _inprint_frame_bank: dict[int, bytes] = {}
  433. # Monotonic timestamp of the last banked frame per printer — throttles banking
  434. # so tall prints don't add a camera grab on every layer.
  435. _inprint_frame_bank_ts: dict[int, float] = {}
  436. # Minimum seconds between banked frames, except the final object layer which
  437. # always refreshes for the best framing.
  438. _INPRINT_BANK_MIN_INTERVAL = 25.0
  439. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  440. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  441. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  442. # the first connected status update for that connection; transitions back
  443. # to False whenever we observe `state.connected = False` so the next
  444. # reconnect re-arms reconciliation. Keyed by printer_id.
  445. _printer_reconciled_since_connect: dict[int, bool] = {}
  446. # Same edge, same keying, for priming the printer's calibration table exactly
  447. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  448. # is otherwise filled only when someone opens the Profiles page or Configure
  449. # Slot, when a GitHub backup runs, or when the printer happens to answer
  450. # somebody else's query on the report topic. Until then the AMS slot card has
  451. # no K value to show on the printers whose trays carry none of their own
  452. # (#2854 — H2-series report cali_idx and nothing more).
  453. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  454. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  455. # {(printer_id, filename): archive_id}
  456. _expected_prints: dict[tuple[int, str], int] = {}
  457. # Archives of the running prints Bambuddy dispatched itself: adopted from an
  458. # expected print, or found with Bambuddy's dispatch marker. _active_prints holds
  459. # every print on_print_start archived, those started from Bambu Studio, Handy or
  460. # the printer's screen included, so it is no proof of ownership on its own.
  461. _owned_print_archive_ids: set[int] = set()
  462. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  463. # Used by usage tracker to map 3MF slots to physical AMS trays
  464. _print_ams_mappings: dict[int, list[int]] = {}
  465. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  466. _print_cost_center_ids: dict[int, int] = {}
  467. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  468. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  469. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  470. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  471. # for the queue path. Cleared on print completion or TTL eviction.
  472. _print_plate_ids: dict[int, int] = {}
  473. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  474. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  475. _last_progress_milestone: dict[int, int] = {}
  476. # Track whether first layer complete notification has been sent for current print
  477. _first_layer_notified: dict[int, bool] = {}
  478. # Track whether we already sent a kill-switch stop for the current unauthorized print
  479. _unauthorized_print_kill_sent: set[int] = set()
  480. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  481. # lookup briefly so an unknown active print does not query the database on
  482. # every status frame. A short TTL keeps settings changes responsive.
  483. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  484. _kill_switch_setting_cache: tuple[bool, float] | None = None
  485. # Provider notification started when the kill switch stops a print. The later
  486. # MQTT print-complete callback awaits this task and only sends its regular
  487. # provider notification when the immediate attempt failed.
  488. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  489. # HMS faults already notified, with when each was last seen:
  490. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  491. # fault that flickers beside a held notice was forgotten on every gap and
  492. # notified on every return (#3226). The window is long because the measured
  493. # gaps reach 64 s.
  494. _notified_hms_errors: dict[int, dict[str, float]] = {}
  495. _HMS_CLEAR_GRACE_SECONDS = 600.0
  496. # The print state each printer was last seen in, and the faults recorded before
  497. # it last changed, which are forgotten as soon as they are gone (see
  498. # _take_new_hms_faults).
  499. _hms_print_state: dict[int, str] = {}
  500. _hms_forget_when_gone: dict[int, set[str]] = {}
  501. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  502. # Used for snapshot-diff detection at print completion
  503. _timelapse_baselines: dict[int, set[str]] = {}
  504. # Track printers waiting for bed to cool after print completion.
  505. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  506. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  507. _bed_cool_waiters: dict[int, dict] = {}
  508. # Track printers where the user explicitly stopped the print from the queue UI.
  509. # When on_print_complete fires with status "failed" for these printers we treat it
  510. # as "cancelled" (stopped by user) so the correct notification email is sent.
  511. _user_stopped_printers: set[int] = set()
  512. # Printers whose running print the kill switch stopped. Their completion is a
  513. # cancel with the reason "killSwitch", not the "failed" the printer reports.
  514. _kill_switch_stopped: set[int] = set()
  515. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  516. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  517. # holds the previous observation so we only fire on the True → False edge (a
  518. # False → False repeat doesn't notify; an initial False at startup doesn't
  519. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  520. # holds the per-printer pending asyncio task that fires the notification
  521. # after a debounce window — cancelled if the printer reconnects before the
  522. # window elapses, so transient MQTT blips don't flood the user.
  523. _printer_last_connected: dict[int, bool] = {}
  524. # Printers whose relay offline event went out, so the reconnect publishes the
  525. # matching online event and a blip shorter than the debounce publishes neither.
  526. _printer_offline_published: set[int] = set()
  527. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  528. # Debounce: a printer must stay offline this long before we notify. Sized
  529. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  530. # so a single stale-trigger cooldown isn't enough to fire — only a real
  531. # offline that survives one reconnect attempt notifies.
  532. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  533. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  534. # when status="failed" to label the print's failure_reason in archives.
  535. #
  536. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  537. # which is wrong on two counts:
  538. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  539. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  540. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  541. # the public wiki) as part of its user-cancel sequence. Matching on the module
  542. # alone caused user-cancellations to be archived as "Layer shift" failures.
  543. # We now match by full short code only — anything not in this map leaves
  544. # failure_reason=None rather than guessing.
  545. # Values are the canonical camelCase failure-reason keys, NOT display labels
  546. # (issue #2974). The vocabulary is enforced on writes by
  547. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  548. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  549. # Statistics breakdown. Storing a label here instead put a second spelling of
  550. # the same cause into one column: the Failure Analysis widget groups on the raw
  551. # value, so a print the backend classified and an identical one a user
  552. # classified counted as two different reasons, and the label form could never
  553. # be translated because there was no key for ``t()`` to resolve.
  554. _HMS_FAILURE_REASONS: dict[str, str] = {
  555. # Layer shift / step loss
  556. "0300_4057": "layerShift",
  557. "0300_4068": "layerShift",
  558. "0300_800C": "layerShift",
  559. # Filament runout (printer-side & per-AMS-slot)
  560. "0300_8004": "filamentRunout",
  561. "0700_8011": "filamentRunout",
  562. "0701_8011": "filamentRunout",
  563. "0702_8011": "filamentRunout",
  564. "0703_8011": "filamentRunout",
  565. "0704_8011": "filamentRunout",
  566. "0705_8011": "filamentRunout",
  567. "0706_8011": "filamentRunout",
  568. "0707_8011": "filamentRunout",
  569. "07FF_8011": "filamentRunout",
  570. # Clogged nozzle / extruder
  571. "0300_4006": "cloggedNozzle",
  572. "0300_8016": "cloggedNozzle",
  573. "0300_801C": "cloggedNozzle",
  574. "0700_8003": "cloggedNozzle",
  575. "0700_8007": "cloggedNozzle",
  576. "0700_8013": "cloggedNozzle",
  577. "0701_8003": "cloggedNozzle",
  578. "0701_8007": "cloggedNozzle",
  579. "0701_8013": "cloggedNozzle",
  580. "0702_8003": "cloggedNozzle",
  581. # AI print monitoring — spaghetti / the model coming off the plate.
  582. # `spaghettiDetached` is a key the archive editor already offers for this
  583. # failure mode, not a new one, so a derived reason opens the dropdown on
  584. # that option rather than blank — and survives the next save, which clears
  585. # any value the editor does not recognise.
  586. #
  587. # A module-0x0C row is safe here despite the warning above: that warning is
  588. # about matching on the module alone, and 0C00_8042 is a full short code
  589. # with a documented meaning ("The AI print monitor has detected a spaghetti
  590. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  591. # cannot collide.
  592. #
  593. # 0300_8003's own text ends "before continuing your print", but on an X2D
  594. # it arrives with the print already paused, offering only
  595. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  596. #
  597. # Two neighbours are left out on purpose, so this does not get re-derived:
  598. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  599. # reads as a warning about a print that is still running, not a halt.
  600. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  601. # the waste chute. That is not the print failing.
  602. #
  603. # That line is drawn from the text, not from `severity`, because severity
  604. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  605. # module/error word with no level in it, and bambu_mqtt.py gives every
  606. # print_error entry a flat severity=3. Matching on the short code alone is
  607. # the right shape for derive_failure_reason, not an omission.
  608. "0300_8003": "spaghettiDetached",
  609. "0C00_8042": "spaghettiDetached",
  610. }
  611. def _hms_short_code(attr: int, code: int | str) -> str:
  612. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  613. if isinstance(code, str):
  614. code_int = int(code.replace("0x", ""), 16) if code else 0
  615. else:
  616. code_int = int(code or 0)
  617. attr_int = int(attr or 0)
  618. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  619. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  620. """Derive the failure_reason key for an archived print.
  621. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  622. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  623. no HMS code matches (don't guess — null is honest). The keys are the
  624. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  625. translated at render time.
  626. """
  627. if status in ("aborted", "cancelled"):
  628. return "userCancelled"
  629. if status != "failed":
  630. return None
  631. for err in hms_errors or []:
  632. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  633. if short_code in _HMS_FAILURE_REASONS:
  634. return _HMS_FAILURE_REASONS[short_code]
  635. return None
  636. # Track created_by_id for expected prints so the user email can be sent even when
  637. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  638. # {(printer_id, filename): created_by_id}
  639. _expected_print_creators: dict[tuple[int, str], int] = {}
  640. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  641. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  642. # tag tuple changes for the slot. Cleared when the slot is reported empty
  643. # so remove + reinsert reliably re-prompts the UI.
  644. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  645. async def _broadcast_unknown_tag(
  646. *,
  647. printer_id: int,
  648. ams_id: int,
  649. tray_id: int,
  650. tag_uid: str,
  651. tray_uuid: str,
  652. tray_type: str | None = None,
  653. tray_color: str | None = None,
  654. tray_sub_brands: str | None = None,
  655. tray_count: int | None = None,
  656. ) -> None:
  657. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  658. _logger = logging.getLogger(__name__)
  659. slot_key = (ams_id, tray_id)
  660. tag_key = (tag_uid or "", tray_uuid or "")
  661. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  662. if per_printer.get(slot_key) == tag_key:
  663. _logger.debug(
  664. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  665. printer_id,
  666. ams_id,
  667. tray_id,
  668. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  669. )
  670. return
  671. _logger.info(
  672. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  673. printer_id,
  674. ams_id,
  675. tray_id,
  676. tray_type,
  677. tray_color,
  678. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  679. )
  680. # Broadcast first; only commit the dedup if the WS write succeeds.
  681. # If broadcast raises, the next MQTT push retries instead of being
  682. # permanently silenced by a poisoned dedup entry.
  683. await ws_manager.broadcast(
  684. {
  685. "type": "unknown_tag",
  686. "printer_id": printer_id,
  687. "ams_id": ams_id,
  688. "tray_id": tray_id,
  689. "tag_uid": tag_uid,
  690. "tray_uuid": tray_uuid,
  691. "tray_type": tray_type,
  692. "tray_color": tray_color,
  693. "tray_sub_brands": tray_sub_brands,
  694. "tray_count": tray_count,
  695. }
  696. )
  697. per_printer[slot_key] = tag_key
  698. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  699. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  700. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  701. if per_printer is None:
  702. return
  703. per_printer.pop((ams_id, tray_id), None)
  704. # TTL for expected-print entries: evict registrations older than this to prevent
  705. # unbounded growth when a print is registered but never starts (e.g. printer
  706. # disconnect, app restart, print started from the printer panel).
  707. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  708. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  709. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  710. # Cleanup loop interval
  711. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  712. _expected_prints_cleanup_task: asyncio.Task | None = None
  713. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  714. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  715. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  716. possible_keys: list[tuple[int, str]] = []
  717. filename = (state.gcode_file or state.current_print or "").strip()
  718. subtask_name = (state.subtask_name or "").strip()
  719. if subtask_name:
  720. possible_keys.append((printer_id, subtask_name))
  721. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  722. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  723. if filename:
  724. base_name = filename.rsplit("/", 1)[-1]
  725. if base_name.endswith(".gcode.3mf"):
  726. root_name = base_name[: -len(".gcode.3mf")]
  727. possible_keys.append((printer_id, root_name))
  728. possible_keys.append((printer_id, base_name))
  729. possible_keys.append((printer_id, f"{root_name}.gcode"))
  730. possible_keys.append((printer_id, f"{root_name}.3mf"))
  731. elif base_name.endswith(".3mf"):
  732. root_name = base_name[: -len(".3mf")]
  733. possible_keys.append((printer_id, root_name))
  734. possible_keys.append((printer_id, base_name))
  735. elif base_name.endswith(".gcode"):
  736. root_name = base_name[: -len(".gcode")]
  737. possible_keys.append((printer_id, root_name))
  738. possible_keys.append((printer_id, f"{root_name}.3mf"))
  739. possible_keys.append((printer_id, base_name))
  740. else:
  741. possible_keys.append((printer_id, base_name))
  742. possible_keys.append((printer_id, f"{base_name}.3mf"))
  743. return possible_keys
  744. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  745. """The id of who started the print, unless that user has been deleted since.
  746. Deleting a user forgets them in printer_manager, but a print that ended a
  747. moment before still holds them.
  748. """
  749. if not print_user or print_user.get("user_id") is None:
  750. return None
  751. from backend.app.models.user import User
  752. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  753. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  754. """Check the cheap, process-local print ownership signals."""
  755. if printer_manager.get_current_print_user(printer_id):
  756. return True
  757. return any(
  758. key in _expected_prints or _active_prints.get(key) in _owned_print_archive_ids
  759. for key in _build_status_print_keys(printer_id, state)
  760. )
  761. def _bind_active_print(
  762. printer_id: int,
  763. archive_id: int,
  764. archive_filename: str | None,
  765. filename: str | None = None,
  766. subtask_name: str | None = None,
  767. ) -> None:
  768. """Track a running print under every name its completion may report.
  769. One set for every path that binds a print (new archive, expected print,
  770. restart resume, fallback): the archive's file name, the name the printer
  771. reported, and the subtask with and without ``.3mf``. Paths that registered
  772. fewer names lost the bound archive at completion, and with it the plate
  773. restore's height (#3240), whenever MQTT reported a name they had left out.
  774. """
  775. for name in {archive_filename, filename, f"{subtask_name}.3mf" if subtask_name else None, subtask_name}:
  776. if name:
  777. _active_prints[(printer_id, name)] = archive_id
  778. def _mark_owned_if_dispatched(archive) -> None:
  779. """Remember a running print's archive as Bambuddy's when it carries a
  780. dispatch marker Bambuddy writes itself: ``billing_run_id`` (minted per
  781. dispatch in the scheduler) or ``created_by_id`` (from the queue item)."""
  782. if archive.billing_run_id is not None or archive.created_by_id is not None:
  783. _owned_print_archive_ids.add(archive.id)
  784. async def _is_printer_kill_switch_enabled_cached() -> bool:
  785. """Return the kill-switch setting without querying on every MQTT frame."""
  786. global _kill_switch_setting_cache
  787. now = time.monotonic()
  788. if _kill_switch_setting_cache is not None:
  789. enabled, expires_at = _kill_switch_setting_cache
  790. if now < expires_at:
  791. return enabled
  792. async with async_session() as db:
  793. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  794. enabled = await is_printer_kill_switch_enabled(db)
  795. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  796. return enabled
  797. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  798. """Resolve whether the current print was started by Bambuddy.
  799. ``None`` means identity is not yet safe to decide. The kill switch must
  800. defer in that case: stopping a print is irreversible, and the first status
  801. frames after a restart may arrive before all subtask fields are populated.
  802. """
  803. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  804. return True
  805. # The printer's built-in calibration runs (Bambuddy's Calibrate, the
  806. # printer's screen) play gcode from its read-only system partition, where no
  807. # user file can be. Only that path counts: a calibration *name* proves
  808. # nothing, since Bambu Studio's pressure-advance print reports a user-style
  809. # path, and any print can be given that name.
  810. if str(getattr(state, "gcode_file", "") or "").startswith("/usr/"):
  811. return True
  812. # A1, A1 Mini, P1 and A2L report the same calibration as a bare file name,
  813. # which nothing distinguishes from a user's file given that name, so it is
  814. # not exempt: with the kill switch on, calibrate on those printers with the
  815. # switch off.
  816. possible_keys = _build_status_print_keys(printer_id, state)
  817. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  818. # is on disk. subtask_id is minted per print and pins the answer to the job
  819. # actually running, rather than to an unrelated one that reuses a filename.
  820. raw_subtask_id = getattr(state, "subtask_id", None)
  821. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  822. if subtask_id == "":
  823. # Not reported yet: the first frames after a restart can lack it.
  824. return None
  825. from backend.app.models.archive import PrintArchive
  826. if subtask_id == "0":
  827. # A print started outside the cloud from Bambu Studio, Handy or the
  828. # printer's screen reports "0", so there is no id to match: one of
  829. # Bambuddy's printing archives on this printer under the name the
  830. # printer reports, compared as the printer echoes names (spaces become
  831. # underscores). Nothing reported to compare yet: wait.
  832. reported = {_normalise_subtask_name(name) for _pid, name in possible_keys} - {""}
  833. if not reported:
  834. return None
  835. dispatched = await db.execute(
  836. select(PrintArchive)
  837. .where(
  838. PrintArchive.printer_id == printer_id,
  839. PrintArchive.status == "printing",
  840. or_(PrintArchive.billing_run_id.is_not(None), PrintArchive.created_by_id.is_not(None)),
  841. # An archive with a real id of its own is a print that reported
  842. # one: a "0" print is not it, even under the same name (one whose
  843. # completion was missed would otherwise cover it).
  844. or_(PrintArchive.subtask_id.is_(None), PrintArchive.subtask_id.in_(("", "0"))),
  845. )
  846. .order_by(PrintArchive.created_at.desc())
  847. )
  848. archive = next((a for a in dispatched.scalars() if _archive_name_forms(a) & reported), None)
  849. else:
  850. result = await db.execute(
  851. select(PrintArchive)
  852. .where(
  853. PrintArchive.printer_id == printer_id,
  854. PrintArchive.status == "printing",
  855. PrintArchive.subtask_id == subtask_id,
  856. )
  857. .order_by(PrintArchive.created_at.desc())
  858. .limit(1)
  859. )
  860. archive = result.scalar_one_or_none()
  861. # An archive row on its own proves nothing: `on_print_start` archives every
  862. # print it observes, including ones started from Bambu Studio or Handy, and
  863. # stamps them with the same status and subtask_id. Authorizing on its mere
  864. # existence would disable the kill switch the moment the 3MF finishes
  865. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  866. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  867. # (carried over from the queue item that started it).
  868. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  869. # Rehydrate the fast in-memory path for subsequent status frames. Include
  870. # both the archive filename and every normalized key reported by MQTT.
  871. _owned_print_archive_ids.add(archive.id)
  872. _active_prints[(printer_id, archive.filename)] = archive.id
  873. for key in possible_keys:
  874. _active_prints[key] = archive.id
  875. return True
  876. # No dispatch marker. Before calling this someone else's print, check whether
  877. # Bambuddy has a job of its own running on this printer: a library-file
  878. # dispatch has no archive at send time, and an archive created seconds later
  879. # by `on_print_start` carries neither marker. The queue row, which the
  880. # scheduler commits to status="printing" before the MQTT send, is the one
  881. # durable record every Bambuddy print has. It cannot be tied to this
  882. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  883. # print is irreversible, and refusing to act costs nothing but a log line.
  884. from backend.app.models.print_queue import PrintQueueItem
  885. dispatched_here = await db.scalar(
  886. select(PrintQueueItem.id)
  887. .where(
  888. PrintQueueItem.printer_id == printer_id,
  889. PrintQueueItem.status == "printing",
  890. )
  891. .limit(1)
  892. )
  893. if dispatched_here is not None:
  894. return None
  895. return False
  896. async def _send_kill_switch_provider_notification(
  897. printer_id: int,
  898. printer_name: str,
  899. data: dict,
  900. ) -> bool:
  901. """Send the immediate print-stopped provider notification.
  902. Returning a success flag lets the normal MQTT completion path retry when
  903. this early notification could not be delivered.
  904. """
  905. logger = logging.getLogger(__name__)
  906. try:
  907. async with async_session() as db:
  908. await notification_service.on_print_complete(
  909. printer_id,
  910. printer_name,
  911. "stopped",
  912. data,
  913. db,
  914. )
  915. return True
  916. except Exception as e:
  917. logger.warning(
  918. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  919. printer_id,
  920. e,
  921. )
  922. return False
  923. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  924. """Wait for an immediate kill-switch notification, if one was scheduled."""
  925. if task is None:
  926. return False
  927. try:
  928. return await task
  929. except Exception as e:
  930. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  931. return False
  932. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  933. """Capture the smart plug lifetime counter on the archive at print start.
  934. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  935. tracking survives a backend restart mid-print. The print-end handler reads
  936. this value back from the DB and computes the delta against the current
  937. plug counter.
  938. """
  939. _logger = logging.getLogger(__name__)
  940. try:
  941. candidates = await energy_plug_candidates(db, printer_id)
  942. if not candidates:
  943. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  944. return False
  945. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  946. if selected is None:
  947. # Naming the plugs matters here: with several linked to one printer
  948. # this is the difference between "the meter is offline" and "you
  949. # linked only accessories" (#2859).
  950. _logger.warning(
  951. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  952. printer_id,
  953. archive.id,
  954. ", ".join(plug.name for plug in candidates),
  955. )
  956. return False
  957. plug, energy = selected
  958. archive.energy_start_kwh = float(energy["total"])
  959. # With the plug's snapshots, what lets the cost follow the price over
  960. # the print rather than take the price at its end (#1251). A price that
  961. # can't be had must not cost the print its energy reading.
  962. archive.energy_start_at = utcnow_naive()
  963. archive.energy_start_plug_id = plug.id
  964. try:
  965. from backend.app.services.energy_price import current_price
  966. archive.energy_start_price = await current_price(db)
  967. except Exception as e:
  968. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  969. archive.energy_start_price = None
  970. await db.commit()
  971. _logger.info(
  972. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  973. f" ({context})" if context else "",
  974. archive.id,
  975. plug.name,
  976. energy["total"],
  977. )
  978. return True
  979. except Exception as e:
  980. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  981. return False
  982. def forget_print_creator(user_id: int) -> None:
  983. """The print-start emails of a deleted user's jobs go to nobody, not to
  984. whoever is given the id next (SQLite reuses it)."""
  985. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  986. del _expected_print_creators[key]
  987. async def forget_printer(printer_id: int) -> None:
  988. """Drop what is kept for a deleted printer's id, here and in the services.
  989. SQLite used to give the id to the next printer created, which inherited it
  990. all: the running print's owner (its prints passed the kill switch and were
  991. billed to that user), the plate-clear gate, pending and suppressed
  992. notifications, the camera feed, the plate references. Ids are no longer
  993. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  994. stay. Called after the delete is committed, and again by work that was in
  995. flight and wrote state back.
  996. Every printer-keyed map of this module is listed here or, with the reason,
  997. in tests/unit/test_forget_printer.py.
  998. """
  999. from backend.app.api.routes import camera
  1000. from backend.app.services import (
  1001. bambu_ftp,
  1002. kprofile_drift,
  1003. layer_timelapse,
  1004. plate_detection,
  1005. print_dispatch_context,
  1006. usage_tracker,
  1007. )
  1008. from backend.app.services.notify_live_activities import notify_live_activities
  1009. from backend.app.services.obico_detection import obico_detection_service
  1010. from backend.app.services.printer_file_cache import printer_file_cache
  1011. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  1012. archive_ids = set()
  1013. for tracked in (_active_prints, _expected_prints):
  1014. for key in [key for key in tracked if key[0] == printer_id]:
  1015. archive_ids.add(tracked.pop(key))
  1016. for archive_id in archive_ids:
  1017. _owned_print_archive_ids.discard(archive_id)
  1018. _print_ams_mappings.pop(archive_id, None)
  1019. _print_cost_center_ids.pop(archive_id, None)
  1020. _print_plate_ids.pop(archive_id, None)
  1021. for tracked in (_expected_print_creators, _expected_print_registered_at):
  1022. for key in [key for key in tracked if key[0] == printer_id]:
  1023. del tracked[key]
  1024. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  1025. _ams_index_only_logged.discard(key)
  1026. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  1027. del _ams_alarm_cooldown[key]
  1028. # Pending work that would act on the id: an offline notice, a 3MF retry.
  1029. # A kill-switch notice is about a stop that happened and is left to finish.
  1030. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  1031. task = tasks.pop(printer_id, None)
  1032. if task is not None:
  1033. task.cancel()
  1034. for keyed in (
  1035. _stage22_finish_frames,
  1036. _stage22_finish_in_flight,
  1037. _inprint_frame_bank,
  1038. _inprint_frame_bank_ts,
  1039. _printer_reconciled_since_connect,
  1040. _printer_kprofiles_primed_since_connect,
  1041. _last_progress_milestone,
  1042. _first_layer_notified,
  1043. _kill_switch_notification_tasks,
  1044. _notified_hms_errors,
  1045. _hms_print_state,
  1046. _hms_forget_when_gone,
  1047. _timelapse_baselines,
  1048. _bed_cool_waiters,
  1049. _printer_last_connected,
  1050. _unknown_tag_last_broadcast,
  1051. _last_status_broadcast,
  1052. _connection_watchdog_last_attempt,
  1053. ):
  1054. keyed.pop(printer_id, None)
  1055. for marked in (
  1056. _unauthorized_print_kill_sent,
  1057. _user_stopped_printers,
  1058. _kill_switch_stopped,
  1059. _printer_offline_published,
  1060. _nozzle_count_updated,
  1061. _runtime_seen_connected,
  1062. ):
  1063. marked.discard(printer_id)
  1064. printer_manager.forget_printer(printer_id)
  1065. printer_file_cache.forget_printer(printer_id)
  1066. print_dispatch_context.clear(printer_id)
  1067. kprofile_drift.forget_printer(printer_id, deleted=True)
  1068. layer_timelapse.cancel_session(printer_id)
  1069. usage_tracker.forget_printer(printer_id)
  1070. obico_detection_service.forget_printer(printer_id)
  1071. bambu_ftp.clear_3mf_cache(printer_id)
  1072. await camera.forget_printer(printer_id)
  1073. printers.clear_cover_cache(printer_id)
  1074. print_scheduler.forget_printer(printer_id)
  1075. notify_live_activities.forget_printer(printer_id)
  1076. plate_detection.remove_printer_references(printer_id)
  1077. def register_expected_print(
  1078. printer_id: int,
  1079. filename: str,
  1080. archive_id: int,
  1081. ams_mapping: list[int] | None = None,
  1082. created_by_id: int | None = None,
  1083. cost_center_id: int | None = None,
  1084. plate_id: int | None = None,
  1085. ):
  1086. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1087. # Store with multiple filename variations to catch different naming patterns
  1088. _expected_prints[(printer_id, filename)] = archive_id
  1089. # Also store without .3mf extension if present
  1090. if filename.endswith(".3mf"):
  1091. base = filename[:-4]
  1092. _expected_prints[(printer_id, base)] = archive_id
  1093. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1094. # Store AMS mapping for usage tracking at print completion, and plate_id for
  1095. # a single-plate dispatch from a multi-plate 3MF — without it, the direct-Print
  1096. # path attributes the whole file's filament total to the spool instead of just
  1097. # the printed plate (#1697). They describe this dispatch: one that has none
  1098. # drops what an earlier dispatch of the archive left (sent, never started),
  1099. # unless a plate of the archive is printing now and still needs them.
  1100. archive_printing = archive_id in set(_active_prints.values())
  1101. if ams_mapping is not None:
  1102. _print_ams_mappings[archive_id] = ams_mapping
  1103. elif not archive_printing:
  1104. _print_ams_mappings.pop(archive_id, None)
  1105. if cost_center_id is not None:
  1106. _print_cost_center_ids[archive_id] = cost_center_id
  1107. elif not archive_printing:
  1108. _print_cost_center_ids.pop(archive_id, None)
  1109. if plate_id is not None:
  1110. _print_plate_ids[archive_id] = plate_id
  1111. elif not archive_printing:
  1112. _print_plate_ids.pop(archive_id, None)
  1113. # Store created_by_id so the user start email can be sent even when the archive
  1114. # itself has no created_by_id (e.g. library-file-based queue prints)
  1115. if created_by_id is not None:
  1116. _expected_print_creators[(printer_id, filename)] = created_by_id
  1117. if filename.endswith(".3mf"):
  1118. base = filename[:-4]
  1119. _expected_print_creators[(printer_id, base)] = created_by_id
  1120. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1121. # Record registration time for TTL-based eviction
  1122. _registered_at = time.monotonic()
  1123. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1124. if filename.endswith(".3mf"):
  1125. base = filename[:-4]
  1126. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1127. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1128. logging.getLogger(__name__).info(
  1129. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1130. )
  1131. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1132. """Undo :func:`register_expected_print` when the print never went out.
  1133. Registration has to happen *before* the MQTT print command, because the
  1134. printer can report the print before the line after the send executes. So
  1135. every path that registers and then fails to send — a cancel winning the
  1136. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1137. between — leaves an expectation for a print that will never arrive.
  1138. The TTL sweep evicts those after two hours, which is far longer than it
  1139. takes a user to react to a failed dispatch by pressing print again: that
  1140. reprint would be folded into the *old* archive and take the stale
  1141. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1142. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1143. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1144. are keyed by archive, not by file, so they may only be dropped once no
  1145. live key still points at that archive.
  1146. """
  1147. keys = [(printer_id, filename)]
  1148. if filename.endswith(".3mf"):
  1149. base = filename[:-4]
  1150. keys.append((printer_id, base))
  1151. keys.append((printer_id, f"{base}.gcode"))
  1152. removed = False
  1153. for key in keys:
  1154. if _expected_prints.pop(key, None) is not None:
  1155. removed = True
  1156. _expected_print_creators.pop(key, None)
  1157. _expected_print_registered_at.pop(key, None)
  1158. # Still needed by another expected print of the archive, or a plate of it
  1159. # that is printing, as in the sweep.
  1160. if archive_id not in set(_expected_prints.values()) | set(_active_prints.values()):
  1161. _print_ams_mappings.pop(archive_id, None)
  1162. _print_cost_center_ids.pop(archive_id, None)
  1163. _print_plate_ids.pop(archive_id, None)
  1164. if removed:
  1165. logging.getLogger(__name__).info(
  1166. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1167. printer_id,
  1168. filename,
  1169. archive_id,
  1170. )
  1171. def _compute_run_filament_grams(
  1172. status: str,
  1173. archive_filament_used_grams: float | None,
  1174. progress: float | int | None,
  1175. usage_results: list[dict] | None,
  1176. ) -> float | None:
  1177. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1178. Priority for every status:
  1179. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1180. weight delta — same source that drives "Total Consumed" on the
  1181. Inventory page, so Stats and Inventory totals stay aligned).
  1182. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1183. back to the canonical "this print used X" value).
  1184. 3. For partial statuses: ``estimate * progress%``.
  1185. 4. ``None`` if nothing is known.
  1186. """
  1187. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1188. if tracked_grams > 0:
  1189. return round(tracked_grams, 1)
  1190. if status == "completed":
  1191. return archive_filament_used_grams
  1192. if archive_filament_used_grams:
  1193. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1194. if scale > 0:
  1195. return round(archive_filament_used_grams * scale, 1)
  1196. return None
  1197. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  1198. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1199. stored_ams_mapping = data.get("ams_mapping")
  1200. if not stored_ams_mapping and archive_id:
  1201. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  1202. return stored_ams_mapping
  1203. def _get_start_plate_id(archive_id: int | None) -> int | None:
  1204. """Resolve plate_id for print start without consuming stored direct-Print state.
  1205. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1206. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1207. read it back at print-start without popping (the entry is popped on print
  1208. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1209. """
  1210. if archive_id is None:
  1211. return None
  1212. return _print_plate_ids.get(archive_id)
  1213. def _partial_progress_scale(progress: int | float | None) -> float:
  1214. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1215. Used by every site that multiplies a "would-have-used" slicer estimate
  1216. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1217. so the three sites in ``_background_notifications`` (and the per-plate
  1218. override helper) can't drift apart on the coercion shape.
  1219. """
  1220. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1221. def _scope_notification_archive_data_to_plate(
  1222. archive_data: dict,
  1223. archive_file_path: str | None,
  1224. plate_id: int | None,
  1225. print_status: str,
  1226. progress: int | float | None,
  1227. base_dir: Path,
  1228. ) -> dict:
  1229. """Override summed-across-plates totals in ``archive_data`` with the values
  1230. for ``plate_id`` so the completion notification reports what was actually
  1231. printed, not the whole project (#1785).
  1232. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1233. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1234. the archive card's "whole project" headline, wrong for the completion
  1235. notification of a single-plate print. The queue UI already re-reads the
  1236. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1237. notification payload (filament grams, time estimate, per-slot breakdown).
  1238. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1239. no per-plate values — in every fail case the original ``archive_data`` is
  1240. returned unchanged so the notification still sends.
  1241. """
  1242. if plate_id is None or not archive_file_path:
  1243. return archive_data
  1244. from backend.app.utils.threemf_tools import (
  1245. extract_filament_usage_from_3mf,
  1246. extract_print_time_from_3mf,
  1247. )
  1248. archive_path = base_dir / archive_file_path
  1249. if not archive_path.exists():
  1250. return archive_data
  1251. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1252. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1253. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1254. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1255. if plate_time:
  1256. archive_data["print_time_seconds"] = plate_time
  1257. # Gate both the grams headline AND the per-slot breakdown on the same
  1258. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1259. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1260. # to the project-level grams the archive columns already provide rather
  1261. # than ship a project-level headline next to an all-zero per-plate
  1262. # breakdown.
  1263. if plate_grams > 0:
  1264. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1265. archive_data["filament_slots"] = [
  1266. {
  1267. "slot_id": s.get("slot_id"),
  1268. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1269. "type": s.get("type", ""),
  1270. "color": s.get("color", ""),
  1271. }
  1272. for s in plate_slots
  1273. ]
  1274. return archive_data
  1275. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1276. """Best-effort filament metadata from the MQTT print-start snapshot.
  1277. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1278. file during print, see #1533) so the fallback PrintArchive still has
  1279. enough filament info to support the inventory views and AMS-expansion
  1280. planning the operator opens it for. Returns a dict with optional
  1281. ``filament_type`` and ``filament_color`` keys in the same
  1282. comma-separated format the 3MF extractor produces, so the rest of the
  1283. codebase treats the fallback archive identically to a normal one.
  1284. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1285. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1286. entries). When supplied, only the slots actually consumed by this
  1287. print contribute. Without it the function falls back to every loaded
  1288. AMS slot — less accurate but still useful.
  1289. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1290. that the unit tests pass directly, AND the on_print_start callback
  1291. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1292. bambu_mqtt service hands to main.py at runtime. The original
  1293. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1294. handled the inner shape and silently returned ``{}`` for every real
  1295. print start, leaving fallback archives' filament fields NULL — the
  1296. exact regression the fix was meant to close. Reported with a log
  1297. proving the AMS state was right there at
  1298. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1299. """
  1300. result: dict[str, str] = {}
  1301. # Look at the on_print_start wrapper first, then the inner shape.
  1302. raw_data = (data or {}).get("raw_data")
  1303. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1304. if not isinstance(ams_root, dict):
  1305. ams_root = (data or {}).get("ams") or {}
  1306. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1307. if not isinstance(ams_units, list) or not ams_units:
  1308. return result
  1309. from backend.app.services.print_scheduler import _global_tray_id
  1310. # Map global tray id → (type, color), addressed as the print's ams_mapping
  1311. # is: unit * 4 + tray, or the bare unit id for an AMS-HT (from 128).
  1312. loaded: dict[int, tuple[str, str]] = {}
  1313. for unit in ams_units:
  1314. if not isinstance(unit, dict):
  1315. continue
  1316. try:
  1317. unit_id = int(unit.get("id", 0))
  1318. except (TypeError, ValueError):
  1319. continue
  1320. for tray in unit.get("tray") or []:
  1321. if not isinstance(tray, dict):
  1322. continue
  1323. try:
  1324. tray_id = int(tray.get("id", 0))
  1325. except (TypeError, ValueError):
  1326. continue
  1327. ttype = (tray.get("tray_type") or "").strip()
  1328. # RRGGBBAA from the printer, stored as the 3MF path stores it:
  1329. # "#RRGGBB" (the Archives page's swatches and colour filter).
  1330. hex_color = (tray.get("tray_color") or "").strip().upper()[:6]
  1331. tcolor = f"#{hex_color}" if re.fullmatch(r"[0-9A-F]{6}", hex_color) else ""
  1332. if not ttype:
  1333. continue # Empty / unloaded slot.
  1334. loaded[_global_tray_id(unit_id, tray_id)] = (ttype, tcolor)
  1335. if not loaded:
  1336. return result
  1337. if ams_mapping:
  1338. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1339. filaments = [loaded[g] for g in used_ids if g in loaded]
  1340. if not filaments:
  1341. return result # Mapping points entirely at slots we have no data for.
  1342. else:
  1343. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1344. types_joined = ",".join(f[0] for f in filaments)
  1345. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1346. # Column limits per backend/app/models/archive.py: filament_type=50,
  1347. # filament_color=200.
  1348. if types_joined:
  1349. result["filament_type"] = types_joined[:50]
  1350. if colors_joined:
  1351. result["filament_color"] = colors_joined[:200]
  1352. return result
  1353. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1354. """Start a layer-timelapse session for *archive_id* when the printer has
  1355. an external camera configured. Returns True if a session was started.
  1356. Three call sites in on_print_start (expected-archive promotion, fallback
  1357. archive creation, fresh-archive creation) used to inline this same
  1358. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1359. on the first pass). Centralising the conditional + call here makes the
  1360. contract testable in isolation and keeps the three sites locked in step.
  1361. """
  1362. if not (printer.external_camera_enabled and printer.external_camera_url):
  1363. return False
  1364. from backend.app.services.layer_timelapse import start_session
  1365. start_session(
  1366. printer_id,
  1367. archive_id,
  1368. printer.external_camera_url,
  1369. printer.external_camera_type or "mjpeg",
  1370. snapshot_url=printer.external_camera_snapshot_url,
  1371. rotation=getattr(printer, "camera_rotation", 0),
  1372. )
  1373. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1374. return True
  1375. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1376. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1377. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1378. — since #2926 — the description the parser already resolved, which is preferred
  1379. when present so the queue's failure reason reads the same as the status
  1380. response. The short code still produces the bracketed label, and still
  1381. resolves the sentence for a caller whose entries predate the field. An entry
  1382. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1383. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1384. label when no description is on file. Returns None for an empty list so
  1385. callers can leave error_message unset.
  1386. """
  1387. if not hms_errors:
  1388. return None
  1389. from backend.app.services.hms_errors import get_error_description
  1390. parts: list[str] = []
  1391. for err in hms_errors:
  1392. try:
  1393. # `_hms_short_code` rather than a local derivation: this one used to
  1394. # format the error without masking it to 16 bits, so an `hms[]` entry
  1395. # whose code carries an alert-level group produced a five-digit label
  1396. # like "0500_3000A" — not a code the user can look up, and never a
  1397. # catalogue key, so the sentence was lost with it.
  1398. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1399. except (TypeError, ValueError):
  1400. continue
  1401. description = err.get("description") or get_error_description(short_code)
  1402. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1403. # groups and is not a code anyone can look up; its full code in the
  1404. # printer screen's four groups is (#2728).
  1405. full_code = str(err.get("full_code") or "")
  1406. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1407. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1408. return "; ".join(parts) if parts else None
  1409. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1410. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1411. print completes successfully. Gated to status=='completed': failed, cancelled
  1412. and aborted prints do not count as usage. Caller is responsible for committing
  1413. the session. No-op when the queue item has no linked library file (e.g. reprints
  1414. from an archive). See #1008."""
  1415. if queue_status != "completed" or item.library_file_id is None:
  1416. return
  1417. from backend.app.models.library import LibraryFile
  1418. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1419. if lib_file is None:
  1420. return
  1421. lib_file.print_count = (lib_file.print_count or 0) + 1
  1422. lib_file.last_printed_at = datetime.now(timezone.utc)
  1423. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1424. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1425. When on_print_complete fires with status 'failed' for a printer in this set we
  1426. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1427. rather than a 'print failed' notification.
  1428. """
  1429. _user_stopped_printers.add(printer_id)
  1430. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1431. _last_status_broadcast: dict[int, str] = {}
  1432. # Track printers where we've updated nozzle_count
  1433. _nozzle_count_updated: set[int] = set()
  1434. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1435. """Wait the debounce window then fire `on_printer_offline` if the printer
  1436. is still offline.
  1437. Scheduled by `on_printer_status_change` on the connected → disconnected
  1438. edge (#1752). Cancelled by the same handler if the printer reconnects
  1439. before the window elapses, so a single MQTT blip + recovery doesn't
  1440. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1441. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1442. route through the same status-change callback, so this covers both.
  1443. """
  1444. logger = logging.getLogger(__name__)
  1445. try:
  1446. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1447. still_offline = not printer_manager.is_connected(printer_id)
  1448. logger.info(
  1449. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1450. printer_id,
  1451. still_offline,
  1452. )
  1453. if not still_offline:
  1454. return
  1455. async with async_session() as db:
  1456. from backend.app.models.printer import Printer
  1457. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1458. printer = result.scalar_one_or_none()
  1459. if not printer:
  1460. logger.warning(
  1461. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1462. printer_id,
  1463. )
  1464. return
  1465. # Recorded only when the relay can publish it, so the reconnect's
  1466. # online event always has an offline before it.
  1467. if mqtt_relay.enabled and mqtt_relay.connected:
  1468. _printer_offline_published.add(printer_id)
  1469. try:
  1470. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1471. except Exception as e:
  1472. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1473. logger.info(
  1474. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1475. printer_id,
  1476. printer.name,
  1477. )
  1478. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1479. except asyncio.CancelledError:
  1480. raise
  1481. except Exception as e:
  1482. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1483. finally:
  1484. _printer_offline_notify_tasks.pop(printer_id, None)
  1485. def _hms_notify_key(error) -> str:
  1486. """What identifies a fault for notification de-duplication.
  1487. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1488. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1489. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1490. and -0006 together) shared a key and only the first was ever notified. An
  1491. entry without a full code falls back to attr and code together.
  1492. """
  1493. full_code = getattr(error, "full_code", "") or ""
  1494. if full_code:
  1495. return full_code.upper()
  1496. return f"{error.attr:08X}:{error.code}"
  1497. def _hms_fault_counts(error) -> bool:
  1498. """Whether a fault counts as a problem: the same rule the frontend's
  1499. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1500. It counts when Bambu publishes text for it or it offers action buttons, and
  1501. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1502. no actions does not count: those are things like "the top cover is open" or
  1503. "the chamber is hot, fan speed increased", which a printer can hold through
  1504. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1505. it always has; those are prompts such as "unable to start drying" (#2728).
  1506. """
  1507. if error.severity < 1:
  1508. return False
  1509. has_actions = bool(getattr(error, "actions", None))
  1510. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1511. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1512. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1513. """The new faults that count (see ``_hms_fault_counts``).
  1514. These go to the MQTT relay; the caller also needs a description before it
  1515. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1516. used to read ``severity >= 2`` when severity held the part byte; on the real
  1517. level that would drop the task-stopping errors (#2728).
  1518. """
  1519. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1520. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1521. """The faults on this printer not notified yet, and record them as notified.
  1522. Tracking is updated before anything is sent, so concurrent status callbacks
  1523. cannot notify the same fault twice. A notified fault is forgotten once it
  1524. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1525. and on is notified once (#3226), while one that clears and comes back much
  1526. later is notified again.
  1527. When ``print_state`` changes (a print resumed, started or finished), every
  1528. fault recorded so far is forgotten the first time it is gone, without the
  1529. wait: a runout fixed before resuming must be notified if it happens again a
  1530. few minutes later, while the printer sits paused. Not only the faults gone
  1531. at the change itself, because the update that flips the state can still
  1532. carry the old fault (a ``print_error`` entry stays until a payload brings
  1533. ``hms``).
  1534. """
  1535. now = time.time()
  1536. current = {_hms_notify_key(e) for e in errors}
  1537. seen = _notified_hms_errors.setdefault(printer_id, {})
  1538. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1539. if print_state is not None:
  1540. print_state = print_state.upper()
  1541. if _hms_print_state.get(printer_id, print_state) != print_state:
  1542. forget_when_gone.update(seen)
  1543. _hms_print_state[printer_id] = print_state
  1544. for key, last_seen in list(seen.items()):
  1545. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1546. del seen[key]
  1547. forget_when_gone.discard(key)
  1548. new = current - seen.keys()
  1549. for key in current:
  1550. seen[key] = now
  1551. if not seen:
  1552. _notified_hms_errors.pop(printer_id, None)
  1553. if not forget_when_gone:
  1554. _hms_forget_when_gone.pop(printer_id, None)
  1555. return _hms_errors_to_notify(errors, new)
  1556. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1557. # "Printing", -1 and 255 are "no stage" (#3211).
  1558. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1559. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1560. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1561. Records it as notified. Called only for a printing state with progress above 0.
  1562. Progress before the first layer is not progress through the print (#3211).
  1563. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1564. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1565. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1566. 75% notification together with Print Started, and since 75 was then on
  1567. record, 25 and 50 could never fire. So nothing counts while the printer
  1568. reports a layer count but has not started layer 1.
  1569. Without a layer count -- a print whose first frame carried no
  1570. ``total_layer_num``, until the pushall that asks for it is answered
  1571. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1572. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1573. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1574. reports neither keeps the old behaviour rather than never notifying.
  1575. """
  1576. if (state.layer_num or 0) < 1:
  1577. if (state.total_layers or 0) > 0:
  1578. return None
  1579. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1580. return None
  1581. progress = state.progress or 0
  1582. current_milestone = 0
  1583. if progress >= 75:
  1584. current_milestone = 75
  1585. elif progress >= 50:
  1586. current_milestone = 50
  1587. elif progress >= 25:
  1588. current_milestone = 25
  1589. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1590. _last_progress_milestone[printer_id] = current_milestone
  1591. return current_milestone
  1592. return None
  1593. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1594. """Handle printer status changes - broadcast via WebSocket."""
  1595. try:
  1596. notify_live_activities.observe(printer_id, state)
  1597. except Exception:
  1598. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1599. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1600. # transitions disconnected → connected — which covers both Bambuddy
  1601. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1602. # `reconcile_stale_active_prints` exactly once for this connection so
  1603. # any archive still in `status="printing"` that can't actually be
  1604. # running anymore (printer IDLE / different subtask / empty subtask)
  1605. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1606. # finished during a disconnect window + a smart-plug power cycle
  1607. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1608. # next boot. Reconciliation runs concurrently — it must not block the
  1609. # WebSocket dedup / broadcast logic below, and the connected edge is
  1610. # marked True BEFORE the await so concurrent status updates inside
  1611. # the same connection don't re-trigger reconciliation.
  1612. #
  1613. # Wait for a real push_status before reconciling (#1679): MQTT
  1614. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1615. # the connection, BEFORE `_request_push_all` round-trips. At that
  1616. # instant the `PrinterState` is still on construction defaults — most
  1617. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1618. # If reconcile spawns here, every in-flight archive falls through to
  1619. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1620. # creates a duplicate archive on the real PRINT COMPLETE and
  1621. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1622. # keeps the #1542 mechanism intact: once the first real push_status
  1623. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1624. # fires again with the flag still False — reconcile then runs against
  1625. # actual evidence.
  1626. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1627. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1628. _printer_reconciled_since_connect[printer_id] = True
  1629. spawn_background_task(
  1630. reconcile_stale_active_prints(printer_id),
  1631. name=f"reconcile-stale-prints-{printer_id}",
  1632. )
  1633. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1634. # Re-arm so the next reconnect triggers reconciliation again.
  1635. _printer_reconciled_since_connect[printer_id] = False
  1636. # Same edge, for the calibration table the AMS card reads its K values from.
  1637. #
  1638. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1639. # tables to ask for. A `state_known` gate alone is not enough: the first
  1640. # real push_status is what makes the state known, and the nozzle fields do
  1641. # not always arrive in it. Latching there would spend this connection's one
  1642. # attempt on a printer that could not yet say what was fitted.
  1643. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1644. if (
  1645. state.connected
  1646. and state_known
  1647. and nozzle_known
  1648. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1649. ):
  1650. _printer_kprofiles_primed_since_connect[printer_id] = True
  1651. spawn_background_task(
  1652. prime_kprofile_table(printer_id),
  1653. name=f"prime-kprofiles-{printer_id}",
  1654. )
  1655. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1656. _printer_kprofiles_primed_since_connect[printer_id] = False
  1657. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1658. # else in the AMS report changing -- a power cycle does it to every slot --
  1659. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1660. # while the printer is idle; needs_check is cheap and throttled per slot.
  1661. # Guarded: nothing here may stop the status broadcast below.
  1662. try:
  1663. if not state.connected:
  1664. kprofile_drift.forget_printer(printer_id)
  1665. elif kprofile_drift.needs_check(printer_id, state):
  1666. spawn_background_task(
  1667. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1668. name=f"reapply-kprofiles-{printer_id}",
  1669. )
  1670. except Exception:
  1671. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1672. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1673. # connected → disconnected. The "back online" channel is already covered
  1674. # by the print-failure notification (firmware reports gcode_state=FAILED
  1675. # on reconnect of an interrupted print), so there is no online
  1676. # notification. The MQTT relay gets both: offline after the debounce, and
  1677. # online on the reconnect that follows a published offline.
  1678. prev_connected = _printer_last_connected.get(printer_id)
  1679. _printer_last_connected[printer_id] = state.connected
  1680. if prev_connected is True and not state.connected:
  1681. existing = _printer_offline_notify_tasks.get(printer_id)
  1682. if existing is None or existing.done():
  1683. logging.getLogger(__name__).info(
  1684. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1685. printer_id,
  1686. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1687. )
  1688. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1689. _maybe_notify_printer_offline(printer_id),
  1690. name=f"printer-offline-notify-{printer_id}",
  1691. )
  1692. elif state.connected:
  1693. # Kept until the relay can actually send online: with its broker down
  1694. # now, the next status update after the reconnect sends it.
  1695. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1696. _printer_offline_published.discard(printer_id)
  1697. printer_info = printer_manager.get_printer(printer_id)
  1698. if printer_info:
  1699. try:
  1700. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1701. except Exception as e:
  1702. logging.getLogger(__name__).warning(
  1703. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1704. )
  1705. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1706. if pending is not None and not pending.done():
  1707. logging.getLogger(__name__).info(
  1708. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1709. printer_id,
  1710. )
  1711. pending.cancel()
  1712. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1713. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1714. temps = state.temperatures or {}
  1715. nozzle_temp = round(temps.get("nozzle", 0))
  1716. bed_temp = round(temps.get("bed", 0))
  1717. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1718. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1719. # Auto-detect dual-nozzle printers from MQTT temperature data
  1720. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1721. _nozzle_count_updated.add(printer_id)
  1722. # Update nozzle_count in database
  1723. async with async_session() as db:
  1724. from backend.app.models.printer import Printer
  1725. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1726. printer = result.scalar_one_or_none()
  1727. if printer and printer.nozzle_count != 2:
  1728. printer.nozzle_count = 2
  1729. await db.commit()
  1730. logging.getLogger(__name__).info(
  1731. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1732. )
  1733. # Include target temps for heating phase detection
  1734. bed_target = round(temps.get("bed_target", 0))
  1735. nozzle_target = round(temps.get("nozzle_target", 0))
  1736. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1737. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1738. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1739. #
  1740. # dry_countdown_stalled rides along because it is the one drying signal the
  1741. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1742. # dry_time stopped moving, so on the frame that flips it every other member
  1743. # of this key is identical and the push would be deduplicated away. Mid-print
  1744. # a temperature would eventually break the tie, but a parked command on an
  1745. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1746. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1747. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1748. ams_dry_key = (
  1749. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1750. if state.raw_data
  1751. else ()
  1752. )
  1753. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1754. #
  1755. # The filament identity fields are here because Configure Slot writes
  1756. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1757. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1758. # matched, this function returned before broadcasting, and the card kept
  1759. # showing the old filament until the 30s fallback poll or a page reload —
  1760. # even though the configure route asks the printer for a fresh pushall and
  1761. # that push does carry the new values. Reset always worked, because it
  1762. # clears tray_type.
  1763. #
  1764. # These fields only change when someone configures a slot or swaps a spool,
  1765. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1766. ams_tray_key = (
  1767. tuple(
  1768. (
  1769. t.get("id"),
  1770. t.get("tray_type", ""),
  1771. t.get("state"),
  1772. t.get("tray_color", ""),
  1773. t.get("tray_info_idx", ""),
  1774. t.get("tray_sub_brands", ""),
  1775. t.get("cali_idx"),
  1776. )
  1777. for a in (state.raw_data.get("ams") or [])
  1778. for t in a.get("tray", [])
  1779. )
  1780. if state.raw_data
  1781. else ()
  1782. )
  1783. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1784. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1785. # in the AMS change-hash (tray fields only, and widening that would fire
  1786. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1787. # screen changed no key at all and the card's inlet badges sat stale until a
  1788. # reload. Like the filament-backup flag, these only move when someone
  1789. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1790. fts_key = (
  1791. state.fila_switch.installed if state.fila_switch else False,
  1792. tuple(sorted(state.ams_switch_inlet.items())),
  1793. # Which hotend holds which slot. Unlike the two above this does move
  1794. # mid-print, on every filament change — but only between discrete slots,
  1795. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1796. # it live: it decides which hotend the Load dialog may offer and whether
  1797. # Unload has anything to act on.
  1798. tuple(
  1799. sorted(
  1800. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1801. # Sort on the extruder id alone: the other members are nullable
  1802. # and comparing None with an int raises.
  1803. key=lambda entry: entry[0],
  1804. )
  1805. ),
  1806. )
  1807. status_key = (
  1808. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1809. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1810. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1811. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1812. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1813. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1814. )
  1815. # Fields that change only when the machine does (a nozzle swap, a firmware
  1816. # update, developer mode) or once per print (its AMS mapping): no traffic,
  1817. # but on an idle printer nothing else moves the key when they change.
  1818. machine_key = (
  1819. tuple((n.nozzle_type, n.nozzle_diameter) for n in (state.nozzles or [])),
  1820. state.firmware_version,
  1821. state.developer_mode,
  1822. tuple(state.print_ams_mapping) if isinstance(state.print_ams_mapping, list) else None,
  1823. # Cooling/heating, switched on the printer's screen too: on an idle
  1824. # printer nothing else moves the key (PSF-4).
  1825. state.airduct_mode,
  1826. )
  1827. status_key = f"{status_key}:{machine_key}"
  1828. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1829. if not is_active_print:
  1830. _unauthorized_print_kill_sent.discard(printer_id)
  1831. elif printer_id in _unauthorized_print_kill_sent:
  1832. # stop_print() was already sent for this print; avoid all further
  1833. # ownership and settings work until the printer leaves an active state.
  1834. pass
  1835. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1836. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1837. _unauthorized_print_kill_sent.discard(printer_id)
  1838. else:
  1839. kill_switch_enabled = False
  1840. authorization: bool | None = None
  1841. status_logger = logging.getLogger(__name__)
  1842. try:
  1843. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1844. if kill_switch_enabled:
  1845. async with async_session() as db:
  1846. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1847. except Exception as e:
  1848. # Fail safe: a database/reconciliation error must never turn into an
  1849. # irreversible stop of a print whose ownership is still unknown.
  1850. authorization = None
  1851. status_logger.warning(
  1852. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1853. )
  1854. if not kill_switch_enabled or authorization is True:
  1855. _unauthorized_print_kill_sent.discard(printer_id)
  1856. elif authorization is None:
  1857. _unauthorized_print_kill_sent.discard(printer_id)
  1858. status_logger.debug(
  1859. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1860. printer_id,
  1861. )
  1862. else:
  1863. try:
  1864. stopped = printer_manager.stop_print(printer_id)
  1865. if stopped:
  1866. _unauthorized_print_kill_sent.add(printer_id)
  1867. _kill_switch_stopped.add(printer_id)
  1868. printer_info = printer_manager.get_printer(printer_id)
  1869. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1870. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1871. notification_data = {
  1872. "status": "stopped",
  1873. "filename": state.gcode_file or state.current_print or "",
  1874. "subtask_name": state.subtask_name or "",
  1875. "progress": state.progress,
  1876. "reason": "unauthorized_print",
  1877. }
  1878. status_logger.warning(
  1879. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1880. printer_id,
  1881. state.state,
  1882. )
  1883. try:
  1884. await ws_manager.broadcast(
  1885. {
  1886. "type": "kill_switch_triggered",
  1887. "printer_id": printer_id,
  1888. "printer_name": printer_name,
  1889. "filename": filename,
  1890. "reason": "unauthorized_print",
  1891. }
  1892. )
  1893. except Exception as e:
  1894. status_logger.warning(
  1895. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1896. )
  1897. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1898. if previous_task is not None and not previous_task.done():
  1899. previous_task.cancel()
  1900. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1901. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1902. name=f"kill-switch-notification-{printer_id}",
  1903. )
  1904. else:
  1905. status_logger.warning(
  1906. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1907. printer_id,
  1908. state.state,
  1909. )
  1910. except Exception as e:
  1911. status_logger.warning(
  1912. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1913. )
  1914. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1915. try:
  1916. printer_info = printer_manager.get_printer(printer_id)
  1917. if printer_info:
  1918. await mqtt_relay.on_printer_status(
  1919. printer_id,
  1920. state,
  1921. printer_info.name,
  1922. printer_info.serial_number,
  1923. printer_manager.is_awaiting_plate_clear(printer_id),
  1924. )
  1925. except Exception:
  1926. pass # Don't fail status callback if MQTT fails
  1927. if _last_status_broadcast.get(printer_id) == status_key:
  1928. return # No change, skip WebSocket broadcast
  1929. _last_status_broadcast[printer_id] = status_key
  1930. # Check for progress milestone notifications (25%, 50%, 75%)
  1931. progress = state.progress or 0
  1932. is_printing = state.state in ("RUNNING", "PRINTING")
  1933. if is_printing and progress > 0:
  1934. current_milestone = _progress_milestone_to_notify(printer_id, state)
  1935. if current_milestone is not None:
  1936. try:
  1937. from backend.app.models.printer import Printer
  1938. # Read the printer in a short session and release the connection
  1939. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1940. # pinned a pooled connection per milestone, per printer (issue #2572).
  1941. async with async_session() as db:
  1942. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1943. printer = result.scalar_one_or_none()
  1944. printer_name = printer.name if printer else f"Printer {printer_id}"
  1945. filename = state.subtask_name or state.gcode_file or "Unknown"
  1946. # remaining_time is in minutes, convert to seconds for notification
  1947. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1948. # Capture camera snapshot for notification image attachment (no DB held).
  1949. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1950. # Notification send needs a session (provider/template lookups).
  1951. async with async_session() as db:
  1952. await notification_service.on_print_progress(
  1953. printer_id,
  1954. printer_name,
  1955. filename,
  1956. current_milestone,
  1957. db,
  1958. remaining_time_seconds,
  1959. image_data=image_data,
  1960. )
  1961. except Exception as e:
  1962. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1963. elif progress < 5:
  1964. # Reset milestone tracking when print restarts or new print begins
  1965. _last_progress_milestone[printer_id] = 0
  1966. _first_layer_notified[printer_id] = False
  1967. # HMS error codes that should not trigger notifications even though they
  1968. # have known descriptions (e.g. user-initiated actions, not real errors).
  1969. _HMS_NOTIFICATION_SUPPRESS = {
  1970. "0500_400E", # Printing was cancelled (user action, not an error)
  1971. }
  1972. # Check for new HMS errors and send notifications
  1973. current_hms_errors = getattr(state, "hms_errors", []) or []
  1974. if current_hms_errors:
  1975. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  1976. if new_errors:
  1977. try:
  1978. from backend.app.models.printer import Printer
  1979. # Read the printer in a short session and release the connection
  1980. # BEFORE the ~15s camera snapshot below (issue #2572).
  1981. async with async_session() as db:
  1982. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1983. printer = result.scalar_one_or_none()
  1984. printer_name = printer.name if printer else f"Printer {printer_id}"
  1985. # Format error details for notification
  1986. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1987. module_names = {
  1988. 0x03: "Print/Task",
  1989. 0x05: "Nozzle/Extruder",
  1990. 0x07: "AMS/Filament",
  1991. 0x0C: "Motion Controller",
  1992. 0x12: "Chamber",
  1993. }
  1994. # Capture camera snapshot once for all error notifications (no DB held).
  1995. error_image_data = await _capture_snapshot_for_notification(
  1996. printer_id, printer, logging.getLogger(__name__)
  1997. )
  1998. # Notification sends need a session (provider/template lookups).
  1999. async with async_session() as db:
  2000. sent_count = 0
  2001. for error in new_errors:
  2002. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  2003. # Build short code like "0700_8010"
  2004. # Mask to 16 bits to handle printers that send larger values
  2005. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  2006. error_code_masked = error_code_int & 0xFFFF
  2007. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  2008. # Only notify for errors Bambu publishes text for — printers
  2009. # send undocumented codes that aren't real errors, and Bambu
  2010. # lists some with empty text. Resolved at parse time (#2926);
  2011. # short_code is still needed for the suppression set below.
  2012. description = error.description
  2013. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  2014. continue
  2015. error_type = f"{module_name} Error"
  2016. error_detail = description
  2017. await notification_service.on_printer_error(
  2018. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  2019. )
  2020. sent_count += 1
  2021. if sent_count:
  2022. logging.getLogger(__name__).info(
  2023. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  2024. )
  2025. # Also publish to MQTT relay (no DB): every new fault that
  2026. # counts, with or without text, the same set the UI counts.
  2027. printer_info = printer_manager.get_printer(printer_id)
  2028. if printer_info:
  2029. errors_data = [
  2030. {
  2031. "code": e.code,
  2032. "attr": e.attr,
  2033. "module": e.module,
  2034. "severity": e.severity,
  2035. }
  2036. for e in new_errors
  2037. ]
  2038. await mqtt_relay.on_printer_error(
  2039. printer_id, printer_info.name, printer_info.serial_number, errors_data
  2040. )
  2041. except Exception as e:
  2042. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  2043. else:
  2044. # No HMS errors: nothing to send, but faults gone long enough (or gone
  2045. # across a print state change) are forgotten. Some codes, e.g. chamber
  2046. # temperature regulation during PETG prints, toggle every few seconds.
  2047. _take_new_hms_faults(printer_id, [], state.state)
  2048. await ws_manager.send_printer_status(
  2049. printer_id,
  2050. printer_state_to_dict(
  2051. state,
  2052. printer_id,
  2053. printer_manager.get_model(printer_id),
  2054. printer_manager.get_drying_targets(printer_id),
  2055. ),
  2056. )
  2057. def _is_bambu_uuid(tray_uuid: str) -> bool:
  2058. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  2059. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  2060. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  2061. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  2062. K-profiles are per-nozzle and the printer's calibration table is numbered
  2063. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  2064. switch's other inlet therefore silently invalidates every configured slot in
  2065. it: the index stays put and now resolves against the other nozzle's table.
  2066. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  2067. and 0.020 on the right kept the left profile after the move, and a manual
  2068. RFID re-read only re-asserted the same wrong one.
  2069. Configuring a slot is a deliberate preparation step, so this re-selects
  2070. rather than re-configures: only the calibration binding moves, and only for
  2071. slots whose spool already has a stored profile for the new nozzle. A slot
  2072. Bambuddy knows nothing about is left exactly as the operator left it.
  2073. """
  2074. logger = logging.getLogger(__name__)
  2075. target_extruder = extruder_for_inlet(inlet)
  2076. if target_extruder is None:
  2077. return
  2078. client = printer_manager.get_client(printer_id)
  2079. state = printer_manager.get_status(printer_id)
  2080. if not client or not state or not state.raw_data:
  2081. return
  2082. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  2083. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  2084. # the nozzle width, which changes both the K profile to select and the
  2085. # preset the slot should carry.
  2086. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  2087. ams_raw = state.raw_data.get("ams")
  2088. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2089. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  2090. if not unit:
  2091. return
  2092. try:
  2093. async with async_session() as db:
  2094. for tray in unit.get("tray", []):
  2095. tray_id = int(tray.get("id", -1))
  2096. if tray_id < 0 or not tray.get("tray_type"):
  2097. continue
  2098. current_idx = tray.get("cali_idx")
  2099. profile = await find_slot_kprofile_for_extruder(
  2100. db,
  2101. printer_id,
  2102. ams_id,
  2103. tray_id,
  2104. target_extruder,
  2105. nozzle_diameter,
  2106. printer_manager.get_model(printer_id),
  2107. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2108. )
  2109. if profile is None or profile.cali_idx is None:
  2110. continue
  2111. if current_idx == profile.cali_idx:
  2112. continue # Already on the right one.
  2113. logger.info(
  2114. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2115. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2116. printer_id,
  2117. ams_id,
  2118. tray_id,
  2119. inlet,
  2120. target_extruder,
  2121. profile.name,
  2122. current_idx,
  2123. profile.cali_idx,
  2124. profile.k_value,
  2125. )
  2126. client.extrusion_cali_sel(
  2127. ams_id=ams_id,
  2128. tray_id=tray_id,
  2129. cali_idx=profile.cali_idx,
  2130. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2131. nozzle_diameter=nozzle_diameter,
  2132. )
  2133. except Exception as e:
  2134. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2135. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2136. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2137. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2138. from the delayed re-check -- which is why it takes the AMS data and print
  2139. state as arguments instead of reading them from the push (#3186).
  2140. """
  2141. logger = logging.getLogger(__name__)
  2142. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2143. # Auto-unlink spool assignments with stale fingerprints. Under the
  2144. # per-printer assignment lock since #3186: the held-removal re-check runs
  2145. # this outside any MQTT push, so it can now overlap one.
  2146. try:
  2147. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2148. from sqlalchemy.orm import selectinload
  2149. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2150. from backend.app.models.spool import Spool as _Spool
  2151. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2152. from backend.app.services.ams_slot_presence import spool_present
  2153. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2154. # Built-in assignments only. Since #2812 they survive a switch to
  2155. # Spoolman mode rather than being deleted by it, and this pass ends
  2156. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2157. # time as the AMS contents changed under the other mode, undoing the
  2158. # preservation more slowly but just as completely.
  2159. assignments = []
  2160. if not await spoolman_owns_assignments(db):
  2161. result = await db.execute(
  2162. select(SA)
  2163. .where(SA.printer_id == printer_id)
  2164. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2165. )
  2166. assignments = result.scalars().all()
  2167. # ``printing_now`` (top of this function) keeps a runout from
  2168. # unlinking the spool that fed the print — the next idle-time pass
  2169. # unlinks it if the user really did take it out.
  2170. stale = []
  2171. # Removals this pass is holding rather than unlinking (#3186).
  2172. held: set[tuple] = set()
  2173. for assignment in assignments:
  2174. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2175. if assignment.ams_id == 255:
  2176. ps = printer_manager.get_status(printer_id)
  2177. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2178. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2179. current_tray = None
  2180. for vt in vt_tray_raw:
  2181. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2182. current_tray = vt
  2183. break
  2184. if not current_tray:
  2185. # vt_tray data may not have arrived yet — keep assignment
  2186. continue
  2187. else:
  2188. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2189. if not current_tray:
  2190. if printing_now:
  2191. logger.info(
  2192. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2193. assignment.spool_id,
  2194. assignment.ams_id,
  2195. assignment.tray_id,
  2196. )
  2197. continue
  2198. # A whole AMS unit can drop out of one push and come back in
  2199. # the next; only a slot that stays gone is a removal (#3186).
  2200. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2201. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2202. held.add(hold_key)
  2203. logger.info(
  2204. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2205. "unlinking if it is still gone in %ds",
  2206. assignment.spool_id,
  2207. assignment.ams_id,
  2208. assignment.tray_id,
  2209. int(slot_unlink_grace.GRACE_SECONDS),
  2210. )
  2211. continue
  2212. logger.info(
  2213. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2214. assignment.spool_id,
  2215. assignment.ams_id,
  2216. assignment.tray_id,
  2217. )
  2218. stale.append(assignment) # Slot empty
  2219. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2220. # A Bambu Lab spool is in this slot — check if it's the same spool
  2221. # that's currently assigned. If yes, keep the assignment (avoids
  2222. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2223. # the printer's filament preset on every startup).
  2224. tray_uuid = current_tray.get("tray_uuid", "")
  2225. tag_uid = current_tray.get("tag_uid", "")
  2226. spool = assignment.spool
  2227. spool_matches = False
  2228. if spool:
  2229. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2230. spool.tag_uid
  2231. and tag_uid
  2232. and tag_uid != "0000000000000000"
  2233. and spool.tag_uid.upper() == tag_uid.upper()
  2234. ):
  2235. spool_matches = True
  2236. if spool_matches:
  2237. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2238. cur_color = current_tray.get("tray_color", "")
  2239. cur_type = current_tray.get("tray_type", "")
  2240. fp_color = assignment.fingerprint_color or ""
  2241. fp_type = assignment.fingerprint_type or ""
  2242. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2243. assignment.fingerprint_color = cur_color
  2244. assignment.fingerprint_type = cur_type
  2245. logger.debug(
  2246. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2247. assignment.spool_id,
  2248. assignment.ams_id,
  2249. assignment.tray_id,
  2250. )
  2251. continue
  2252. # Different BL spool or unrecognized — unlink so auto-assign can match
  2253. logger.info(
  2254. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2255. assignment.spool_id,
  2256. assignment.ams_id,
  2257. assignment.tray_id,
  2258. tray_uuid,
  2259. )
  2260. stale.append(assignment)
  2261. else:
  2262. cur_color = current_tray.get("tray_color", "")
  2263. cur_type = current_tray.get("tray_type", "")
  2264. cur_state = current_tray.get("state")
  2265. fp_color = assignment.fingerprint_color or ""
  2266. fp_type = assignment.fingerprint_type or ""
  2267. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2268. # the slot was empty when the user pre-assigned via SpoolBuddy
  2269. # (the firmware drops ams_filament_setting on empty slots, so
  2270. # MQTT was deferred). The moment any filament gets inserted
  2271. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2272. # reconfigured spool — fire the deferred configuration.
  2273. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2274. # extruder" code) OR, on firmwares that don't use the state
  2275. # enum meaningfully, a non-empty tray_type when state is
  2276. # NOT one of the firmware's explicit empty signals (9, 10).
  2277. # state-only was wrong for firmwares that never set 11 — A1
  2278. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2279. # always report state=3 — so the replay never fired for them
  2280. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2281. # explicit "empty" signals authoritative over any stale
  2282. # tray_type that might survive the relay's auto-clearing.
  2283. #
  2284. # tray_exist_bits comes first because that guard cannot tell
  2285. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2286. # writes state=9 when the bit is 0 and leaves it there when the
  2287. # bit returns. A non-RFID spool inserted into a pre-assigned
  2288. # slot brings no tray_type with it, so the stale 9 made this
  2289. # expression false forever and the deferred config never fired
  2290. # — the deadlock #1322 removed from the assign path, still in
  2291. # place here (#3084, #3100).
  2292. loaded = spool_present(current_tray) is True or (
  2293. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2294. )
  2295. if not fp_type.strip() and loaded and assignment.spool:
  2296. # The fingerprint ends this replay. Not recorded when nothing
  2297. # could be sent (no MQTT client while the printer reconnects),
  2298. # so the next AMS change tries again. An attempt that raised is
  2299. # recorded as before: it may have sent part of the commands and
  2300. # would raise again on every change, remain% steps included.
  2301. configured: bool | None = False
  2302. try:
  2303. from backend.app.api.routes.inventory import (
  2304. apply_spool_to_slot_via_mqtt,
  2305. )
  2306. configured = await apply_spool_to_slot_via_mqtt(
  2307. db=db,
  2308. current_user=None,
  2309. spool=assignment.spool,
  2310. printer_id=printer_id,
  2311. ams_id=assignment.ams_id,
  2312. tray_id=assignment.tray_id,
  2313. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2314. current_tray_type=cur_type,
  2315. current_tray_sub_brands=current_tray.get("tray_sub_brands", ""),
  2316. )
  2317. except Exception:
  2318. logger.exception(
  2319. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2320. assignment.spool_id,
  2321. printer_id,
  2322. assignment.ams_id,
  2323. assignment.tray_id,
  2324. )
  2325. configured = None
  2326. if configured is False:
  2327. logger.warning(
  2328. "Pre-config not sent for spool %d on printer %d AMS%d-T%d (no MQTT client); "
  2329. "retrying on the next AMS change",
  2330. assignment.spool_id,
  2331. printer_id,
  2332. assignment.ams_id,
  2333. assignment.tray_id,
  2334. )
  2335. else:
  2336. if configured:
  2337. logger.info(
  2338. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2339. assignment.spool_id,
  2340. printer_id,
  2341. assignment.ams_id,
  2342. assignment.tray_id,
  2343. )
  2344. assignment.fingerprint_color = cur_color
  2345. assignment.fingerprint_type = cur_type
  2346. continue
  2347. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2348. # Blank tray data mid-print is a runout, not a swap: the
  2349. # firmware clears colour and type when it unloads a spool
  2350. # it just emptied. Unlinking here would erase the record
  2351. # of which spool fed the print so far.
  2352. if printing_now and not cur_color.strip() and not cur_type.strip():
  2353. logger.info(
  2354. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2355. "(runout?)",
  2356. assignment.spool_id,
  2357. assignment.ams_id,
  2358. assignment.tray_id,
  2359. )
  2360. continue
  2361. # Same reasoning off the print, on firmware's own say-so:
  2362. # a blank tray report from a slot whose tray_exist_bits
  2363. # bit is set describes a spool the AMS cannot identify —
  2364. # a non-RFID one, or one whose slot was reset — not a
  2365. # spool that was taken out. Deleting the assignment there
  2366. # threw away the identity the user had supplied, which is
  2367. # the only place it existed (#3100). A slot the bit calls
  2368. # empty, or one that carries no bit at all, still unlinks.
  2369. #
  2370. # Unless the slot was reported empty first: a removal
  2371. # already held means a spool came out and another went
  2372. # in, so the blank report keeps the hold running below
  2373. # rather than cancelling it (#3186).
  2374. if (
  2375. spool_present(current_tray) is True
  2376. and not cur_color.strip()
  2377. and not cur_type.strip()
  2378. and not slot_unlink_grace.is_held(
  2379. printer_id,
  2380. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2381. )
  2382. ):
  2383. logger.info(
  2384. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2385. "tray reports no filament data yet",
  2386. assignment.spool_id,
  2387. assignment.ams_id,
  2388. assignment.tray_id,
  2389. )
  2390. continue
  2391. # A blank report the presence bit does not vouch for is
  2392. # still only one push. An idle X1C cleared a whole AMS
  2393. # unit's bits, colour and type for a moment and lost
  2394. # four saved assignments that way (#3186); unlink only
  2395. # if the slot is still blank after the grace period.
  2396. if not cur_color.strip() and not cur_type.strip():
  2397. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2398. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2399. held.add(hold_key)
  2400. logger.info(
  2401. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2402. "unlinking if it is still blank in %ds",
  2403. assignment.spool_id,
  2404. assignment.ams_id,
  2405. assignment.tray_id,
  2406. int(slot_unlink_grace.GRACE_SECONDS),
  2407. )
  2408. continue
  2409. # Fingerprint mismatch — but check if tray now matches the
  2410. # assigned spool (e.g. auto-configure changed the tray).
  2411. # Both sides are reduced to the type the slot can carry
  2412. # before comparing: the assign path writes that rather
  2413. # than the spool's raw material (#2902), so a spool whose
  2414. # material is a product line — "PLA+", "HTPLA" — reports
  2415. # back as "PLA" and would otherwise fail this check and
  2416. # be auto-unlinked from the slot it was just assigned to.
  2417. # Reducing the printer's side too keeps slots configured
  2418. # by an older Bambuddy, still reporting "PLA+", matching.
  2419. spool = assignment.spool
  2420. if spool:
  2421. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2422. # Two ways the assign path can have arrived at the
  2423. # slot's type, so both count as "we wrote this".
  2424. # The material column is one; the spool's preset is
  2425. # the other, and it outranks the material when the
  2426. # spool has one -- a spool whose material says PLA
  2427. # and whose preset is "Bambu PLA Aero" puts
  2428. # PLA-AERO in the slot (#2902). Read from the stored
  2429. # preset name rather than resolving the preset,
  2430. # because this runs on every AMS push and a cloud
  2431. # lookup here would be both slow and unavailable on
  2432. # the unauthenticated replay path.
  2433. spool_types = {printer_filament_type(spool.material).upper()}
  2434. if spool.slicer_filament_name:
  2435. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2436. # An imported local preset stores its type outright,
  2437. # which is what the assign path used -- and the name
  2438. # above may be unset. One keyed read, and only on a
  2439. # mismatch, which is rare.
  2440. #
  2441. # slicer_filament is free text up to fifty characters,
  2442. # so the digits have to be checked against the range
  2443. # of the integer primary key they are about to be
  2444. # compared with. Postgres raises on an out-of-range
  2445. # integer rather than simply not matching, and that
  2446. # would poison this session and abandon the rest of
  2447. # the cleanup pass.
  2448. lp_ref = (spool.slicer_filament or "").strip()
  2449. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2450. from backend.app.models.local_preset import LocalPreset as _LP
  2451. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2452. if lp_type:
  2453. spool_types.add(printer_filament_type(lp_type).upper())
  2454. if (
  2455. _colors_similar(cur_color, spool_color)
  2456. and printer_filament_type(cur_type).upper() in spool_types
  2457. ):
  2458. logger.info(
  2459. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2460. assignment.spool_id,
  2461. assignment.ams_id,
  2462. assignment.tray_id,
  2463. )
  2464. assignment.fingerprint_color = cur_color
  2465. assignment.fingerprint_type = cur_type
  2466. continue
  2467. logger.info(
  2468. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2469. assignment.spool_id,
  2470. assignment.ams_id,
  2471. assignment.tray_id,
  2472. cur_color,
  2473. cur_type,
  2474. fp_color,
  2475. fp_type,
  2476. spool.rgba if spool else "?",
  2477. spool.material if spool else "?",
  2478. )
  2479. stale.append(assignment) # Spool changed
  2480. slot_unlink_grace.settle(printer_id, "inventory", held)
  2481. # Snapshot slots before delete — ORM attribute access after the
  2482. # commit would refresh against a deleted row.
  2483. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2484. for a in stale:
  2485. await db.delete(a)
  2486. if stale:
  2487. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2488. # Commit any changes (stale deletions and/or fingerprint updates)
  2489. await db.commit()
  2490. # Tell open browsers the assignment is gone (#2575). Only the manual
  2491. # REST assign/unassign endpoints broadcast this event; without it the
  2492. # frontend's spool-assignments cache keeps rendering the unlinked
  2493. # spool on the slot until an unrelated refetch — which reads exactly
  2494. # like "the fix didn't work" (reporter verified: a browser refresh
  2495. # after the swap showed the correct state all along).
  2496. for ams_id, tray_id in unlinked_slots:
  2497. await ws_manager.broadcast(
  2498. {
  2499. "type": "spool_assignment_changed",
  2500. "printer_id": printer_id,
  2501. "ams_id": ams_id,
  2502. "tray_id": tray_id,
  2503. }
  2504. )
  2505. except Exception as e:
  2506. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2507. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2508. """Delete Spoolman slot rows whose held removal has run its grace period.
  2509. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2510. talks to Spoolman for every tray; this only needs the local rows, so it
  2511. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2512. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2513. not in a slot the presence bit calls occupied -- and nothing else.
  2514. """
  2515. logger = logging.getLogger(__name__)
  2516. try:
  2517. async with async_session() as db:
  2518. from backend.app.api.routes.settings import get_setting
  2519. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2520. from backend.app.services.ams_slot_presence import spool_present
  2521. enabled = await get_setting(db, "spoolman_enabled")
  2522. if not enabled or enabled.lower() != "true":
  2523. return
  2524. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2525. if sync_mode and sync_mode != "auto":
  2526. return
  2527. trays: dict[tuple[int, int], dict] = {}
  2528. for ams_unit in ams_data or []:
  2529. if not isinstance(ams_unit, dict):
  2530. continue
  2531. for tray in ams_unit.get("tray", []):
  2532. if isinstance(tray, dict):
  2533. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2534. rows = (
  2535. (
  2536. await db.execute(
  2537. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2538. )
  2539. )
  2540. .scalars()
  2541. .all()
  2542. )
  2543. held: set[tuple] = set()
  2544. expired: list[tuple[int, int]] = []
  2545. for row in rows:
  2546. tray = trays.get((row.ams_id, row.tray_id))
  2547. if tray is None or printing_now:
  2548. continue
  2549. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2550. continue
  2551. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2552. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2553. continue
  2554. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2555. expired.append((row.ams_id, row.tray_id))
  2556. else:
  2557. held.add(hold_key)
  2558. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2559. if not expired:
  2560. return
  2561. # A statement rather than ORM deletes, like the sync pass: the two
  2562. # can overlap, and a row the other already removed must not fail
  2563. # this commit.
  2564. for ams_id, tray_id in expired:
  2565. await db.execute(
  2566. delete(SpoolmanSlotAssignment).where(
  2567. SpoolmanSlotAssignment.printer_id == printer_id,
  2568. SpoolmanSlotAssignment.ams_id == ams_id,
  2569. SpoolmanSlotAssignment.tray_id == tray_id,
  2570. )
  2571. )
  2572. await db.commit()
  2573. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2574. for ams_id, tray_id in expired:
  2575. await ws_manager.broadcast(
  2576. {
  2577. "type": "spool_assignment_changed",
  2578. "printer_id": printer_id,
  2579. "ams_id": ams_id,
  2580. "tray_id": tray_id,
  2581. }
  2582. )
  2583. except Exception as e:
  2584. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2585. async def _recheck_held_unlinks(printer_id: int) -> None:
  2586. """Re-run just the slot cleanup against the printer's current AMS state.
  2587. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2588. passes otherwise run only when the AMS hash changes, and a slot that went
  2589. empty and stayed empty may never change it again.
  2590. """
  2591. status = printer_manager.get_status(printer_id)
  2592. # A disconnected printer's state is its last report, not a new one: acting
  2593. # on it would "confirm" a removal nobody has seen for the whole grace
  2594. # period. Leave the holds; the first push after reconnecting decides.
  2595. if status is None or not status.connected:
  2596. return
  2597. ams_raw = status.raw_data.get("ams")
  2598. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2599. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2600. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2601. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2602. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2603. async def on_ams_change(printer_id: int, ams_data: list):
  2604. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2605. logger = logging.getLogger(__name__)
  2606. # Snapshot BEFORE any await: if a print is active, or a finished one is
  2607. # still being charged, skip weight sync later. on_print_complete may pop
  2608. # _active_sessions during our awaits (#880).
  2609. from backend.app.services.usage_tracker import printer_is_charging
  2610. _print_active = printer_is_charging(printer_id)
  2611. # A slot that reports empty while a print is running is a filament runout,
  2612. # not a spool swap: the spool is still physically in the AMS, just
  2613. # consumed. Dropping either inventory backend's slot link there loses the
  2614. # only record of which spool fed the print, so the completion path can't
  2615. # charge the runout segment to anything. Both cleanup passes below consult
  2616. # this; computed once, up front, so neither depends on the other having run.
  2617. _unlink_state = printer_manager.get_status(printer_id)
  2618. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2619. # The session alone is not enough: a restart that finds a stale persisted
  2620. # session registers none for the print that is running.
  2621. _print_active = _print_active or printing_now
  2622. # MQTT relay - publish AMS change
  2623. try:
  2624. printer_info = printer_manager.get_printer(printer_id)
  2625. if printer_info:
  2626. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2627. except Exception:
  2628. pass # Don't fail AMS callback if MQTT fails
  2629. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2630. # This ensures frontend gets immediate updates when AMS slots are configured
  2631. try:
  2632. state = printer_manager.get_status(printer_id)
  2633. if state:
  2634. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2635. await ws_manager.send_printer_status(
  2636. printer_id,
  2637. printer_state_to_dict(
  2638. state,
  2639. printer_id,
  2640. printer_manager.get_model(printer_id),
  2641. printer_manager.get_drying_targets(printer_id),
  2642. ),
  2643. )
  2644. except Exception as e:
  2645. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2646. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2647. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2648. # Serialised per-printer via services/ams_assignment_lock: MQTT bursts can deliver
  2649. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2650. # "no existing assignment" for the same (printer, ams, tray) and race to
  2651. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2652. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2653. # bug stayed latent there. See services/ams_assignment_lock for details.
  2654. try:
  2655. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2656. from sqlalchemy.orm import selectinload
  2657. from backend.app.api.routes.settings import get_setting
  2658. from backend.app.models.spool import Spool
  2659. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2660. from backend.app.services.spool_tag_matcher import (
  2661. auto_assign_spool,
  2662. create_spool_from_tray,
  2663. find_matching_untagged_spool,
  2664. get_spool_by_tag,
  2665. is_bambu_tag,
  2666. is_valid_tag,
  2667. link_tag_to_inventory_spool,
  2668. tag_belongs_to_archived_spool,
  2669. )
  2670. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2671. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2672. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2673. if not _spoolman_on or _spoolman_on.lower() != "true":
  2674. for ams_unit in ams_data:
  2675. if not isinstance(ams_unit, dict):
  2676. continue
  2677. ams_id = int(ams_unit.get("id", 0))
  2678. for tray in ams_unit.get("tray", []):
  2679. if not isinstance(tray, dict):
  2680. continue
  2681. tray_id = int(tray.get("id", 0))
  2682. tag_uid = tray.get("tag_uid", "")
  2683. tray_uuid = tray.get("tray_uuid", "")
  2684. tray_info_idx = tray.get("tray_info_idx", "")
  2685. if not tray.get("tray_type"):
  2686. # Slot reported empty — drop any cached unknown-tag
  2687. # broadcast so reinserting the same spool re-prompts.
  2688. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2689. continue # Empty slot
  2690. # Check if assignment already exists for this slot
  2691. existing = await db.execute(
  2692. select(SA)
  2693. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2694. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2695. )
  2696. existing_assignment = existing.scalar_one_or_none()
  2697. if existing_assignment:
  2698. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2699. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2700. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2701. # Skip during active prints: the usage tracker handles deduction
  2702. # precisely via 3MF data on print completion. Without this guard the
  2703. # AMS remain% SET and the usage tracker ADD both fire from the same
  2704. # MQTT message, doubling the deduction (#880).
  2705. if _print_active:
  2706. continue
  2707. remain_raw = tray.get("remain")
  2708. if (
  2709. remain_raw is not None
  2710. and existing_assignment.spool
  2711. and not existing_assignment.spool.weight_locked
  2712. ):
  2713. try:
  2714. remain_val = int(remain_raw)
  2715. except (TypeError, ValueError):
  2716. remain_val = -1
  2717. if 1 <= remain_val <= 100:
  2718. lw = existing_assignment.spool.label_weight or 1000
  2719. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2720. current_used = existing_assignment.spool.weight_used or 0
  2721. if new_used > current_used + 1:
  2722. # Rechecked in the statement: the spool was loaded
  2723. # before this, and a weight set by hand (or weighed)
  2724. # and locked since then must stay (WL-6).
  2725. result = cast(
  2726. CursorResult,
  2727. await db.execute(
  2728. update(Spool)
  2729. .where(
  2730. Spool.id == existing_assignment.spool_id,
  2731. Spool.weight_locked.is_not(True),
  2732. func.coalesce(Spool.weight_used, 0) < new_used - 1,
  2733. )
  2734. .values(weight_used=new_used)
  2735. ),
  2736. )
  2737. await db.commit()
  2738. if result.rowcount:
  2739. logger.info(
  2740. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2741. existing_assignment.spool_id,
  2742. current_used,
  2743. new_used,
  2744. remain_val,
  2745. )
  2746. await ws_manager.broadcast({"type": "inventory_changed"})
  2747. # A K-profile the slot lost (the default K after a reset or
  2748. # power cycle) is put back by kprofile_drift on the next idle
  2749. # push; a different real profile was picked on purpose and
  2750. # stays (#3219, item 44).
  2751. continue
  2752. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2753. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2754. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2755. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  2756. # An archived spool still in the AMS: the slot
  2757. # stays free rather than adopting its tag.
  2758. continue
  2759. if not spool:
  2760. # Try matching an untagged inventory spool (same material/color)
  2761. spool = await find_matching_untagged_spool(db, tray)
  2762. if spool:
  2763. await link_tag_to_inventory_spool(db, spool, tray)
  2764. elif _auto_add_unknown:
  2765. spool = await create_spool_from_tray(db, tray)
  2766. else:
  2767. # Auto-add disabled: surface the slot so the
  2768. # user can add it manually via the UI.
  2769. await _broadcast_unknown_tag(
  2770. printer_id=printer_id,
  2771. ams_id=ams_id,
  2772. tray_id=tray_id,
  2773. tag_uid=tag_uid,
  2774. tray_uuid=tray_uuid,
  2775. tray_type=tray.get("tray_type"),
  2776. tray_color=tray.get("tray_color"),
  2777. tray_sub_brands=tray.get("tray_sub_brands"),
  2778. tray_count=len(ams_unit.get("tray", [])),
  2779. )
  2780. continue
  2781. # Slot matched (existing tag, untagged inventory
  2782. # match, or freshly auto-created spool) — drop any
  2783. # stale dedup so a future tag swap re-prompts.
  2784. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2785. await auto_assign_spool(
  2786. printer_id,
  2787. ams_id,
  2788. tray_id,
  2789. spool,
  2790. printer_manager,
  2791. db,
  2792. tray_info_idx=tray_info_idx,
  2793. )
  2794. await db.commit()
  2795. await ws_manager.broadcast(
  2796. {
  2797. "type": "spool_auto_assigned",
  2798. "printer_id": printer_id,
  2799. "ams_id": ams_id,
  2800. "tray_id": tray_id,
  2801. "spool_id": spool.id,
  2802. }
  2803. )
  2804. logger.info(
  2805. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2806. spool.id,
  2807. printer_id,
  2808. ams_id,
  2809. tray_id,
  2810. )
  2811. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  2812. db, tag_uid, tray_uuid
  2813. ):
  2814. # Non-BL spool with some tag — let user choose (not
  2815. # an archived one's, whose slot stays free)
  2816. await _broadcast_unknown_tag(
  2817. printer_id=printer_id,
  2818. ams_id=ams_id,
  2819. tray_id=tray_id,
  2820. tag_uid=tag_uid,
  2821. tray_uuid=tray_uuid,
  2822. tray_type=tray.get("tray_type"),
  2823. tray_color=tray.get("tray_color"),
  2824. tray_sub_brands=tray.get("tray_sub_brands"),
  2825. tray_count=len(ams_unit.get("tray", [])),
  2826. )
  2827. # No-tag slots (generic non-RFID filament) are left alone:
  2828. # nothing to identify, prompting "+ Add" would just create
  2829. # ghost spools with empty tags on every confirm.
  2830. except Exception as e:
  2831. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2832. try:
  2833. async with async_session() as db:
  2834. from backend.app.api.routes.settings import get_setting
  2835. from backend.app.models.printer import Printer
  2836. # Check if Spoolman is enabled
  2837. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2838. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2839. return
  2840. # Check sync mode
  2841. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2842. if sync_mode and sync_mode != "auto":
  2843. return # Only sync on auto mode
  2844. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2845. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2846. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2847. # always owned by per-print tracking, never by AMS auto-sync. The
  2848. # setting is still read by the settings UI for backwards compat but
  2849. # has no effect on the sync path here.
  2850. # Get Spoolman URL
  2851. spoolman_url = await get_setting(db, "spoolman_url")
  2852. if not spoolman_url:
  2853. return
  2854. # Get or create Spoolman client
  2855. client = await get_spoolman_client()
  2856. if not client:
  2857. try:
  2858. client = await init_spoolman_client(spoolman_url)
  2859. except ValueError as exc:
  2860. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2861. return
  2862. # Check if Spoolman is reachable
  2863. if not await client.health_check():
  2864. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2865. return
  2866. # Get printer name for location
  2867. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2868. printer = result.scalar_one_or_none()
  2869. printer_name = printer.name if printer else f"Printer {printer_id}"
  2870. # OPTIMIZATION: Fetch all spools once before processing trays
  2871. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2872. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2873. try:
  2874. cached_spools = await client.get_spools()
  2875. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2876. except Exception as e:
  2877. logger.error(
  2878. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2879. printer_id,
  2880. e,
  2881. )
  2882. return
  2883. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2884. from sqlalchemy.orm import selectinload
  2885. from backend.app.models.spool_assignment import SpoolAssignment
  2886. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2887. from backend.app.services.ams_slot_presence import spool_present
  2888. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2889. # Built-in remaining weight, used by sync_ams_tray only when the
  2890. # firmware reports an unusable remain%/tray_weight for a slot.
  2891. #
  2892. # Left empty since #2812. This block runs in Spoolman mode only,
  2893. # and until then the built-in table was emptied on the switch, so
  2894. # there was never anything here to read and the fallback was inert.
  2895. # Preserving those rows makes it live again, and it is keyed by slot
  2896. # rather than by spool: after a mode switch the tray may well hold
  2897. # different filament, and ``create_spool`` writes ``remaining_weight``
  2898. # unconditionally, so a stale figure would be seeded into a brand new
  2899. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2900. # intent survives for whoever revisits the cross-mode fallback.
  2901. inventory_weights: dict[tuple[int, int], float] = {}
  2902. if not await spoolman_owns_assignments(db):
  2903. try:
  2904. assign_result = await db.execute(
  2905. select(SpoolAssignment)
  2906. .options(selectinload(SpoolAssignment.spool))
  2907. .where(SpoolAssignment.printer_id == printer_id)
  2908. )
  2909. for assignment in assign_result.scalars().all():
  2910. spool = assignment.spool
  2911. if spool and spool.label_weight > 0:
  2912. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2913. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2914. except Exception as e:
  2915. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2916. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2917. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2918. slot_map_read = False
  2919. try:
  2920. slot_result = await db.execute(
  2921. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2922. )
  2923. for slot in slot_result.scalars().all():
  2924. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2925. slot_map_read = True
  2926. except Exception as e:
  2927. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2928. # Sync each AMS tray and collect slot changes for DB persistence
  2929. synced = 0
  2930. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2931. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2932. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  2933. for ams_unit in ams_data:
  2934. if not isinstance(ams_unit, dict):
  2935. continue
  2936. ams_id = int(ams_unit.get("id", 0))
  2937. trays = ams_unit.get("tray", [])
  2938. for tray_data in trays:
  2939. if not isinstance(tray_data, dict):
  2940. continue
  2941. tray_id_raw = int(tray_data.get("id", 0))
  2942. tray = client.parse_ams_tray(ams_id, tray_data)
  2943. if not tray:
  2944. # Empty tray slot — record for local assignment cleanup
  2945. # and drop any cached unknown-tag broadcast so a
  2946. # reinserted spool re-prompts.
  2947. #
  2948. # Not during a running print: a slot that empties there
  2949. # is a filament runout, and the spool is still in the
  2950. # AMS. `spoolman_slot_assignments` is how a tag-less
  2951. # spool assigned through the Bambuddy UI is resolved at
  2952. # completion (#1459), so deleting the row mid-print
  2953. # loses the runout segment's usage — the same failure
  2954. # the internal inventory's auto-unlink had.
  2955. #
  2956. # Nor when firmware's presence bit says the slot is
  2957. # occupied. parse_ams_tray calls a tray with no type or
  2958. # no colour empty, and a spool the AMS cannot read has
  2959. # neither until something configures it — so a tag-less
  2960. # spool assigned through the UI had its row deleted by
  2961. # the first idle push after it was inserted. Same
  2962. # deletion as the internal inventory's in #3100, same
  2963. # answer, so the two modes stay in step.
  2964. #
  2965. # And only once the slot has stayed empty for the grace
  2966. # period -- the internal inventory's #3186 answer, for
  2967. # the same one-push blank.
  2968. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  2969. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  2970. if not printing_now and (
  2971. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  2972. ):
  2973. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2974. empty_slots.append((ams_id, tray_id_raw))
  2975. else:
  2976. spoolman_held.add(hold_key)
  2977. logger.info(
  2978. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  2979. "unlinking if it is still empty in %ds",
  2980. ams_id,
  2981. tray_id_raw,
  2982. linked_spool,
  2983. int(slot_unlink_grace.GRACE_SECONDS),
  2984. )
  2985. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2986. continue
  2987. spool_tag = (
  2988. tray.tray_uuid
  2989. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2990. else tray.tag_uid
  2991. )
  2992. # Provide the hint only when no RFID is available
  2993. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2994. try:
  2995. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2996. result = await client.sync_ams_tray(
  2997. tray,
  2998. printer_name,
  2999. db,
  3000. # Per-print tracking is the only weight writer (#1119).
  3001. # AMS auto-sync still maintains spool metadata / slot
  3002. # assignments but no longer touches remaining_weight.
  3003. disable_weight_sync=True,
  3004. cached_spools=cached_spools,
  3005. inventory_remaining=inv_remaining,
  3006. spoolman_spool_id_hint=hint,
  3007. auto_add_unknown_rfid=auto_add_unknown_rfid,
  3008. )
  3009. if result is None and spool_tag and not auto_add_unknown_rfid:
  3010. # Spoolman skipped auto-create per user setting — surface
  3011. # the slot so the UI can offer "+ Add to inventory".
  3012. await _broadcast_unknown_tag(
  3013. printer_id=printer_id,
  3014. ams_id=ams_id,
  3015. tray_id=tray.tray_id,
  3016. tag_uid=tray.tag_uid or "",
  3017. tray_uuid=tray.tray_uuid or "",
  3018. tray_type=tray.tray_type,
  3019. tray_color=tray.tray_color,
  3020. tray_sub_brands=tray.tray_sub_brands,
  3021. tray_count=len(trays),
  3022. )
  3023. elif result:
  3024. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  3025. if result:
  3026. synced += 1
  3027. if result.get("id"):
  3028. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  3029. # If a new spool was created, add it to the cache
  3030. # so subsequent trays can find it if they reference the same tag
  3031. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  3032. if not spool_exists:
  3033. cached_spools.append(result)
  3034. logger.debug(
  3035. "[Printer %s] Added newly created spool %s to cache",
  3036. printer_id,
  3037. result["id"],
  3038. )
  3039. # Reconcile slot_preset_mappings (the same row internal
  3040. # mode keeps in sync via inventory + spool_tag_matcher).
  3041. # Without this the slot card surfaces the previous spool's
  3042. # preset name — same bug shape, different inventory mode.
  3043. from backend.app.services.slot_preset_writer import (
  3044. upsert_slot_preset_for_spoolman_spool,
  3045. )
  3046. await upsert_slot_preset_for_spoolman_spool(
  3047. db=db,
  3048. spoolman_spool=result,
  3049. tray_info_idx=tray.tray_info_idx or "",
  3050. tray_sub_brands=tray.tray_sub_brands or "",
  3051. tray_type=tray.tray_type or "",
  3052. printer_id=printer_id,
  3053. ams_id=ams_id,
  3054. tray_id=tray.tray_id,
  3055. )
  3056. except Exception as e:
  3057. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3058. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3059. if synced > 0:
  3060. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3061. # Persist slot assignment changes to the local table: only slots
  3062. # whose spool this pass changed, and only while they still hold what
  3063. # it read before awaiting Spoolman, so a spool assigned by hand in
  3064. # between stays (SSA-3). The changed slots are announced: the slot
  3065. # card reads slot_preset_mappings (rewritten above) ahead of the live
  3066. # tray, so with no event it kept the previous spool's preset name.
  3067. if slot_changes or empty_slots:
  3068. from backend.app.services.spoolman_slot_sync import write_slot_results
  3069. try:
  3070. await write_slot_results(
  3071. db,
  3072. {(printer_id, a_id, t_id): spool_id for (a_id, t_id), spool_id in spoolman_slot_map.items()}
  3073. if slot_map_read
  3074. else None,
  3075. [(printer_id, a_id, t_id, spool_id) for a_id, t_id, spool_id in slot_changes],
  3076. [(printer_id, a_id, t_id) for a_id, t_id in empty_slots],
  3077. )
  3078. except Exception as e:
  3079. await db.rollback()
  3080. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3081. except Exception as e:
  3082. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3083. # Largest finish photo attached to a notification; a bigger one is still linked.
  3084. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3085. async def _finish_photo_for_notification(
  3086. db, archive, archive_id: int, filename: str
  3087. ) -> tuple[str | None, bytes | None]:
  3088. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3089. With authentication off the link is the archive's own photo route, as it
  3090. always was: it opens without a login and doesn't expire. With
  3091. authentication on that route needs a media token, which nothing tapping a
  3092. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3093. link only ever answered 401. The photo is then saved as a notification
  3094. photo as well (utils/notification_photos.py) and the link points there: an
  3095. unguessable name that opens this one photo and nothing else, for 3 days.
  3096. The link is relative when no External URL is set. Bytes over
  3097. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3098. ``(None, None)`` when the photo can't be found.
  3099. """
  3100. from backend.app.api.routes.settings import get_setting
  3101. from backend.app.core.auth import is_auth_enabled
  3102. from backend.app.utils.archive_paths import find_archive_photo
  3103. from backend.app.utils.notification_photos import save_notification_photo
  3104. log = logging.getLogger(__name__)
  3105. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3106. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3107. photo_bytes: bytes | None = None
  3108. try:
  3109. photo_path = find_archive_photo(archive, filename)
  3110. if photo_path is not None:
  3111. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3112. except Exception as e:
  3113. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3114. try:
  3115. auth_on = await is_auth_enabled(db)
  3116. except Exception:
  3117. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3118. if auth_on:
  3119. url = None
  3120. if photo_bytes:
  3121. try:
  3122. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3123. url = f"{base}/api/v1/notifications/photos/{name}"
  3124. except Exception as e:
  3125. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3126. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3127. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3128. return url, None
  3129. if photo_bytes:
  3130. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3131. return url, photo_bytes
  3132. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3133. """Capture a camera snapshot for notification image attachment.
  3134. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3135. Uses: external camera > buffered frame > fresh capture.
  3136. Turns the chamber light on for the picture when the printer asks for it
  3137. (#1655). ``light=False`` is for callers that capture all through a print,
  3138. where the light would flash with every frame.
  3139. """
  3140. if not printer:
  3141. return None
  3142. async with camera_light(printer if light else None):
  3143. return await _capture_snapshot_frame(printer_id, printer, logger)
  3144. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3145. """The capture behind ``_capture_snapshot_for_notification``."""
  3146. try:
  3147. from backend.app.api.routes.settings import get_setting
  3148. async with async_session() as db:
  3149. capture_enabled = await get_setting(db, "capture_finish_photo")
  3150. if capture_enabled is not None and capture_enabled.lower() != "true":
  3151. return None
  3152. # Try external camera first
  3153. if printer.external_camera_enabled and printer.external_camera_url:
  3154. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3155. from backend.app.api.routes.camera import live_frame_for_capture
  3156. from backend.app.services.external_camera import capture_frame
  3157. # An external camera allows one reader, so capturing while a viewer
  3158. # is attached fails (#2707). A None here falls through to the paths
  3159. # below exactly as a failed capture did.
  3160. defer, buffered = live_frame_for_capture(printer_id)
  3161. if defer:
  3162. frame_data = buffered
  3163. else:
  3164. frame_data = await capture_frame(
  3165. printer.external_camera_url,
  3166. printer.external_camera_type or "mjpeg",
  3167. snapshot_url=printer.external_camera_snapshot_url,
  3168. )
  3169. if frame_data and len(frame_data) <= 2_500_000:
  3170. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3171. return _apply_camera_rotation(frame_data, printer, logger)
  3172. # Try buffered frame from active stream
  3173. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3174. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3175. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3176. buffered_frame = get_buffered_frame(printer_id)
  3177. if (active_for_printer or active_chamber) and buffered_frame:
  3178. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3179. if len(buffered_frame) <= 2_500_000:
  3180. return _apply_camera_rotation(buffered_frame, printer, logger)
  3181. # Fresh capture from printer camera
  3182. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3183. from backend.app.services.camera import capture_camera_frame_bytes
  3184. frame_data = await capture_camera_frame_bytes(
  3185. printer.ip_address, printer.access_code, printer.model, timeout=15
  3186. )
  3187. if frame_data and len(frame_data) <= 2_500_000:
  3188. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3189. return _apply_camera_rotation(frame_data, printer, logger)
  3190. except Exception as e:
  3191. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3192. return None
  3193. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3194. """#1867: bank a recent in-print camera frame for the finish photo.
  3195. Called on every layer change and (#2547) on every print-progress advance.
  3196. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3197. path has a pre-End-G-code image for prints that end with a plate swap.
  3198. Both drivers are print telemetry that stops the instant printing ends: no
  3199. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3200. plate swap) executes. So the last banked frame is always the finished print,
  3201. never the swapped plate — that property is what the #1867 path relies on and
  3202. it must survive any change to the throttle below.
  3203. Layer changes alone were not enough: they stop when the *final* layer
  3204. begins, which on a three-minute last layer left the bank stale by the whole
  3205. length of that layer (#2547). Progress keeps ticking through it.
  3206. Best-effort: any failure just leaves the previous banked frame.
  3207. """
  3208. logger = logging.getLogger(__name__)
  3209. client = printer_manager.get_client(printer_id)
  3210. state = client.state if client else None
  3211. if not state or state.state != "RUNNING":
  3212. return
  3213. # Only during actual extrusion — firmware ticks layer_num during the
  3214. # pre-print calibration sequence, whose sub-stages are non-zero.
  3215. if state.mc_print_sub_stage not in (None, 0):
  3216. return
  3217. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3218. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3219. # now that progress advances also drive banking, that exemption would fire a
  3220. # camera grab on every percent tick of the last layer. Bambu printers accept
  3221. # one RTSP client at a time, so each grab contends with the live view.
  3222. now = time.monotonic()
  3223. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3224. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3225. return
  3226. total = state.total_layers or 0
  3227. try:
  3228. async with async_session() as db:
  3229. from backend.app.models.printer import Printer
  3230. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3231. printer = result.scalar_one_or_none()
  3232. if not printer:
  3233. return
  3234. # Reuses the notification snapshot path, which honours the
  3235. # `capture_finish_photo` setting (returns None when disabled) so we
  3236. # don't bank frames the user never asked for. Without the chamber light
  3237. # (#1655): this runs every 25 seconds for the whole print.
  3238. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3239. if frame:
  3240. _inprint_frame_bank[printer_id] = frame
  3241. _inprint_frame_bank_ts[printer_id] = now
  3242. logger.debug(
  3243. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3244. printer_id,
  3245. layer_num,
  3246. total,
  3247. len(frame),
  3248. )
  3249. except Exception as e:
  3250. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3251. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3252. """Apply camera rotation to snapshot image if configured."""
  3253. from backend.app.services.camera import apply_camera_rotation
  3254. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3255. async def _send_print_start_notification(
  3256. printer_id: int,
  3257. data: dict,
  3258. archive_data: dict | None = None,
  3259. logger=None,
  3260. ):
  3261. """Helper to send print start notification with optional archive data."""
  3262. if logger is None:
  3263. logger = logging.getLogger(__name__)
  3264. try:
  3265. async with async_session() as db:
  3266. from backend.app.models.printer import Printer
  3267. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3268. printer = result.scalar_one_or_none()
  3269. printer_name = printer.name if printer else f"Printer {printer_id}"
  3270. # Capture camera snapshot for notification image attachment
  3271. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3272. if image_data:
  3273. if archive_data is None:
  3274. archive_data = {}
  3275. archive_data["image_data"] = image_data
  3276. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3277. # Send user-specific email notification for print start
  3278. if archive_data and archive_data.get("created_by_id"):
  3279. await notification_service.send_user_print_email(
  3280. event_type="user_print_start",
  3281. created_by_id=archive_data["created_by_id"],
  3282. printer_name=printer_name,
  3283. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3284. db=db,
  3285. )
  3286. except Exception as e:
  3287. logger.warning("Notification on_print_start failed: %s", e)
  3288. async def _dispatch_user_print_email(
  3289. status: str,
  3290. created_by_id: int | None,
  3291. printer_name: str,
  3292. filename: str,
  3293. db,
  3294. image_data: bytes | None = None,
  3295. finish_photo_url: str | None = None,
  3296. ) -> None:
  3297. """Send a user-specific print-completion email based on print status.
  3298. Maps the normalised print status to the correct event type and delegates
  3299. to :meth:`NotificationService.send_user_print_email`. A single helper
  3300. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3301. "stopped"`` dispatch block at every call site.
  3302. Does nothing if *created_by_id* is ``None``.
  3303. """
  3304. if created_by_id is None:
  3305. return
  3306. if status == "completed":
  3307. event_type = "user_print_complete"
  3308. elif status == "failed":
  3309. event_type = "user_print_failed"
  3310. elif status in ("stopped", "aborted", "cancelled"):
  3311. event_type = "user_print_stopped"
  3312. else:
  3313. return
  3314. await notification_service.send_user_print_email(
  3315. event_type=event_type,
  3316. created_by_id=created_by_id,
  3317. printer_name=printer_name,
  3318. filename=filename,
  3319. db=db,
  3320. image_data=image_data,
  3321. finish_photo_url=finish_photo_url,
  3322. )
  3323. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3324. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3325. try:
  3326. from backend.app.services.archive import extract_printable_objects_from_archive
  3327. client = printer_manager.get_client(printer_id)
  3328. if not client:
  3329. return
  3330. # Extract with positions for UI overlay, scoped to the plate that
  3331. # is printing — resolve_plate_id is the same resolver /cover uses,
  3332. # so the object list can't disagree with the thumbnail it is drawn
  3333. # over (#2522).
  3334. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3335. app_settings.base_dir / archive.file_path,
  3336. plate_number=resolve_plate_id(client.state),
  3337. )
  3338. if printable_objects:
  3339. client.state.printable_objects = printable_objects
  3340. client.state.printable_objects_bbox_all = bbox_all
  3341. client.state.skipped_objects = []
  3342. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3343. except Exception as e:
  3344. logger.debug("Failed to extract printable objects from archive: %s", e)
  3345. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3346. """Put the skip-objects list back after a restart mid-print.
  3347. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3348. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3349. which the #1304 guard suppresses on the first RUNNING push after startup.
  3350. Everything else this hook restores (the archive, the usage-tracking session,
  3351. the timelapse baseline) was already handled; the object list was not, so a
  3352. restart mid-print took skip-objects away for the rest of that print.
  3353. Nothing recovered it either: the printer card gates its Skip button on the
  3354. object count, and the one endpoint that can rebuild the list is reachable
  3355. only from the modal that button opens.
  3356. Anchored on ``subtask_id``, which the firmware mints per print, so a
  3357. leftover ``status="printing"`` row from a completion we never saw cannot
  3358. hand this print someone else's objects. Without one, nothing is loaded
  3359. rather than guessed — the reload path on ``GET /print/objects`` covers that
  3360. case on demand.
  3361. """
  3362. client = printer_manager.get_client(printer_id)
  3363. if client is None or client.state.printable_objects:
  3364. return
  3365. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  3366. if subtask_id in ("", "0"):
  3367. return
  3368. from backend.app.models.archive import PrintArchive
  3369. archive = await db.scalar(
  3370. select(PrintArchive)
  3371. .where(
  3372. PrintArchive.printer_id == printer_id,
  3373. PrintArchive.status == "printing",
  3374. PrintArchive.subtask_id == subtask_id,
  3375. )
  3376. .order_by(PrintArchive.created_at.desc())
  3377. .limit(1)
  3378. )
  3379. if archive is not None:
  3380. _load_objects_from_archive(archive, printer_id, logger)
  3381. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3382. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3383. # past it; the second covers a handshake that failed again on the way back and
  3384. # armed a fresh one. Module-level so tests can shrink them.
  3385. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3386. # Retry ladder for the other temporary give-up: the file service answered and
  3387. # the transfer still did not finish, which at print start is usually the printer
  3388. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3389. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3390. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3391. # two cover a printer that stays busy well into the print.
  3392. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3393. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3394. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3395. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3396. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3397. # by view, so two views race), the cool-off retry task, and print completion.
  3398. # Without this they each read file_path == "" and each run a full copy, so the row
  3399. # ends up pointing at one timestamped directory while the others sit orphaned.
  3400. #
  3401. # Keyed by printer rather than archive because a printer runs one print at a time,
  3402. # which makes the two equally strong here — and it bounds the dict by printer
  3403. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3404. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3405. # resuming, so "no waiters" is not a question this API can answer.
  3406. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3407. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True) -> bool:
  3408. """Fill in a no-3MF archive from a 3MF that turned up later.
  3409. Returns True when the row was upgraded. Safe to call speculatively: it
  3410. verifies the archive still exists, is still a fallback, and that the file
  3411. is a readable 3MF before touching anything.
  3412. Serialised per printer — see ``_fallback_recovery_locks``.
  3413. """
  3414. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3415. async with lock:
  3416. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id, price=price)
  3417. async def _recover_fallback_archive_locked(
  3418. archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True
  3419. ) -> bool:
  3420. """The body of :func:`_recover_fallback_archive`, under its per-printer lock.
  3421. ``price`` is False when the print's end is being handled: the archive
  3422. still reads "printing" then, and its end prices it.
  3423. """
  3424. import zipfile
  3425. from backend.app.models.archive import PrintArchive
  3426. from backend.app.services.archive import ArchiveService
  3427. logger = logging.getLogger(__name__)
  3428. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3429. return False
  3430. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3431. # A truncated or half-written download is worse than no download: it
  3432. # would replace an honest empty archive with wrong metadata.
  3433. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3434. return False
  3435. async with async_session() as db:
  3436. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3437. if archive is None or archive.deleted_at is not None:
  3438. return False
  3439. if archive.file_path:
  3440. # Already recovered, or never was a fallback. Either way there is a
  3441. # real 3MF attached and overwriting it is not this function's job.
  3442. return False
  3443. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3444. service = ArchiveService(db)
  3445. recovered = await service.archive_print(
  3446. printer_id=printer_id,
  3447. source_file=source_3mf,
  3448. print_data={**print_data, "status": archive.status or "printing"},
  3449. subtask_id=archive.subtask_id,
  3450. update_archive_id=archive.id,
  3451. )
  3452. if recovered is None:
  3453. return False
  3454. logger.info(
  3455. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3456. archive_id,
  3457. source_3mf,
  3458. recovered.file_size,
  3459. )
  3460. # Spoolman's tracking stored no 3MF usage at print start and would
  3461. # charge the AMS remain% change; the built-in tracker reads the archive
  3462. # at completion and needs nothing. Also at the print's end (``price``
  3463. # False): that recovery runs inside the close-out, before the charge.
  3464. try:
  3465. from backend.app.services.spoolman_tracking import attach_recovered_3mf
  3466. from backend.app.services.usage_tracker import is_completing
  3467. await attach_recovered_3mf(
  3468. printer_id,
  3469. recovered.id,
  3470. recovered.file_path,
  3471. db,
  3472. printer_manager,
  3473. plate_id=_get_start_plate_id(recovered.id) or recovered.plate_id,
  3474. may_start=not price or (recovered.status == "printing" and not is_completing(printer_id)),
  3475. )
  3476. except Exception:
  3477. logger.warning(
  3478. "[RECOVER] Archive %s: could not add the 3MF to Spoolman's usage tracking", archive_id, exc_info=True
  3479. )
  3480. if price and recovered.status == "printing":
  3481. # Print start priced it from the default rate, having no 3MF to
  3482. # estimate from; now it has one. An ended print is left alone: its
  3483. # end prices it. A print Bambuddy didn't dispatch has no start
  3484. # plate; the one the archive just read from the 3MF stands in.
  3485. _schedule_archive_cost_estimate(
  3486. printer_id,
  3487. recovered.id,
  3488. printer_manager,
  3489. ams_mapping=_get_start_ams_mapping(print_data, recovered.id),
  3490. plate_id=_get_start_plate_id(recovered.id) or recovered.plate_id,
  3491. session_factory=async_session,
  3492. )
  3493. # `archive_updated`, not `archive_created` — the row was already on the
  3494. # Archives page as an empty card and is now filled in, not new.
  3495. await ws_manager.send_archive_updated(
  3496. {
  3497. "id": recovered.id,
  3498. "printer_id": recovered.printer_id,
  3499. "filename": recovered.filename,
  3500. "print_name": recovered.print_name,
  3501. "status": recovered.status,
  3502. }
  3503. )
  3504. return True
  3505. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path, *, price: bool = True) -> bool:
  3506. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3507. Called from the paths that pull a 3MF for a print that is already under way
  3508. — chiefly the cover endpoint, which downloads the very file the archive flow
  3509. could not get and, before #2957, used it for a thumbnail and nothing else.
  3510. The bytes are already local, so this costs a parse and a row update.
  3511. No-op when the running print has a real archive, which is the common case.
  3512. """
  3513. from backend.app.models.archive import PrintArchive
  3514. logger = logging.getLogger(__name__)
  3515. # `_active_prints` is keyed on the raw names seen at print start — the
  3516. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3517. # Callers here arrive with whichever variant their own path produced, so
  3518. # match on the same normalization the download cache uses rather than on an
  3519. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3520. # endpoint find an archive registered under "Desktop_Goose".
  3521. wanted = normalize_3mf_name(name)
  3522. archive_id = None
  3523. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3524. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3525. archive_id = value
  3526. break
  3527. if archive_id is None:
  3528. return False
  3529. async with async_session() as db:
  3530. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3531. # Cheap pre-check so the common case (a normal archive) does no work.
  3532. if archive is None or archive.file_path or archive.deleted_at is not None:
  3533. return False
  3534. try:
  3535. return await _recover_fallback_archive(archive_id, path, printer_id, price=price)
  3536. except Exception as e:
  3537. # Recovery is opportunistic. A failure here must never take down the
  3538. # caller, which is usually just trying to render a thumbnail.
  3539. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3540. return False
  3541. def _schedule_fallback_3mf_retry(
  3542. printer_id: int,
  3543. archive_id: int,
  3544. filenames: list[str],
  3545. delays: tuple[float, ...] | None = None,
  3546. reason: str = REASON_FTPS_COOLOFF,
  3547. ) -> None:
  3548. """Re-attempt the 3MF download after a temporary give-up.
  3549. ``reason`` says which give-up this is, and picks the default ladder: an
  3550. FTPS cool-off has to be waited out, while a transfer that timed out under
  3551. contention is worth asking about again straight away (#3063). It is only
  3552. read for the ladder and the log line -- the retry itself is identical, since
  3553. in both cases the file is on the printer and the last attempt at it failed
  3554. for a reason that does not last.
  3555. """
  3556. logger = logging.getLogger(__name__)
  3557. if delays is None:
  3558. delays = (
  3559. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3560. if reason == REASON_FTP_TRANSFER_FAILED
  3561. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3562. )
  3563. async def _retry() -> None:
  3564. from backend.app.models.archive import PrintArchive
  3565. from backend.app.models.printer import Printer
  3566. for delay in delays:
  3567. await asyncio.sleep(delay)
  3568. async with async_session() as db:
  3569. archive = (
  3570. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3571. ).scalar_one_or_none()
  3572. if archive is None or archive.deleted_at is not None or archive.file_path:
  3573. return
  3574. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3575. if printer is None:
  3576. return
  3577. # Read the fields while the session is open rather than touching
  3578. # a detached instance minutes later, mid-download.
  3579. printer_ip = printer.ip_address
  3580. printer_code = printer.access_code
  3581. printer_model = printer.model
  3582. # Someone else may have fetched it in the meantime — the cover
  3583. # endpoint routinely does, and its copy is the same bytes.
  3584. for name in filenames:
  3585. cached = get_cached_3mf(printer_id, name)
  3586. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3587. return
  3588. if ftps_handshake_blocked(printer_ip):
  3589. logger.info(
  3590. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3591. printer_id,
  3592. archive_id,
  3593. )
  3594. continue
  3595. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3596. for candidate in filenames:
  3597. # Bare name only. These come from the print-start flow, which
  3598. # already strips the path, but the local temp write must not
  3599. # depend on that holding for every future caller — a name that
  3600. # is absolute or contains ".." would otherwise escape the data
  3601. # volume via the `/` operator.
  3602. name = Path(candidate).name
  3603. if not name or name in (".", ".."):
  3604. continue
  3605. if not name.endswith(".3mf"):
  3606. name = f"{name}.3mf"
  3607. temp_path = app_settings.archive_dir / "temp" / name
  3608. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3609. try:
  3610. hit = await download_file_try_paths_async(
  3611. printer_ip,
  3612. printer_code,
  3613. ftp_probe_paths(name),
  3614. temp_path,
  3615. socket_timeout=ftp_timeout,
  3616. printer_model=printer_model,
  3617. max_total_timeout=RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  3618. )
  3619. except Exception as e:
  3620. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3621. continue
  3622. if not hit:
  3623. continue
  3624. cache_3mf_download(printer_id, name, temp_path)
  3625. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3626. return
  3627. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3628. async def _guarded() -> None:
  3629. try:
  3630. await _retry()
  3631. except asyncio.CancelledError:
  3632. raise
  3633. except Exception as e:
  3634. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3635. finally:
  3636. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3637. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3638. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3639. if existing and not existing.done():
  3640. existing.cancel()
  3641. task = asyncio.create_task(_guarded())
  3642. _fallback_3mf_retry_tasks[printer_id] = task
  3643. logger.info(
  3644. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3645. archive_id,
  3646. reason,
  3647. printer_id,
  3648. ", ".join(f"{d:g}s" for d in delays),
  3649. )
  3650. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3651. """Whether an archive created here should ask for the print's outcome (#1898).
  3652. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3653. branches below: a queued job already has its archive and takes the
  3654. expected-print branch, where the queue item's own ``confirm_outcome``
  3655. decides. The queue is still consulted, because a restart mid-print empties
  3656. ``_expected_prints`` — without the check the setting could override a queue
  3657. item that deliberately has the flag off. Any failure answers "don't ask":
  3658. an unwanted prompt is worse than a missing one, and this must never be the
  3659. reason a print goes unarchived.
  3660. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3661. leaves one behind when a completion cannot be matched to it
  3662. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3663. only takes it back once the printer has sat connected and terminal for
  3664. minutes. Until then every screen-started print on that printer would
  3665. silently lose its prompt, so the row is held against ``observed_name`` by
  3666. the same comparison a completion uses: a positive disagreement means the row
  3667. is about some other run and this print is external after all.
  3668. """
  3669. logger = logging.getLogger(__name__)
  3670. try:
  3671. # A savepoint rather than a rollback of the caller's transaction on
  3672. # failure: a failed statement leaves the transaction unusable, but a
  3673. # full rollback also expires every object the caller has loaded (the
  3674. # printer, the archive it just created), and on an async session the
  3675. # next attribute read then raises instead of reloading. Everything here
  3676. # is a read, so undoing the savepoint loses nothing.
  3677. async with db.begin_nested():
  3678. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3679. except Exception as e:
  3680. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3681. return False
  3682. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3683. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3684. from backend.app.api.routes.settings import get_setting, setting_is_true
  3685. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3686. return False
  3687. from backend.app.models.print_queue import PrintQueueItem
  3688. dispatched_here = await db.scalar(
  3689. select(PrintQueueItem)
  3690. .where(
  3691. PrintQueueItem.printer_id == printer_id,
  3692. PrintQueueItem.status == "printing",
  3693. )
  3694. .limit(1)
  3695. )
  3696. if dispatched_here is None:
  3697. return True
  3698. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3699. observed = (observed_name or "").strip()
  3700. if not expected or not observed or _subtask_names_match(expected, observed):
  3701. logger.info(
  3702. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3703. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3704. printer_id,
  3705. dispatched_here.id,
  3706. )
  3707. return False
  3708. logger.info(
  3709. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3710. "%r; treating this as an externally started print.",
  3711. dispatched_here.id,
  3712. printer_id,
  3713. expected,
  3714. observed,
  3715. )
  3716. return True
  3717. async def _dispatch_outcome_confirmation_safely(
  3718. db,
  3719. printer_id: int,
  3720. printer_name: str,
  3721. data: dict,
  3722. archive_id: int,
  3723. archive_data: dict | None = None,
  3724. ) -> None:
  3725. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3726. The completion task sends the per-user print email on the same session
  3727. right after the prompt. A failed statement in the prompt leaves that
  3728. session needing a rollback, and without one the email step fails with
  3729. PendingRollbackError; the prompt is the optional part, so it must not be
  3730. the reason the email never goes out.
  3731. """
  3732. try:
  3733. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3734. except Exception as e:
  3735. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  3736. try:
  3737. await db.rollback()
  3738. except Exception:
  3739. pass
  3740. async def dispatch_outcome_confirmation(
  3741. db,
  3742. printer_id: int,
  3743. printer_name: str,
  3744. data: dict,
  3745. archive_id: int,
  3746. archive_data: dict | None = None,
  3747. ) -> bool:
  3748. """Emit the post-print outcome prompt for a completed archive (#1898).
  3749. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3750. queue item, or from ``confirm_outcome_external_prints`` for a print
  3751. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3752. question still open. Mints the per-archive capability token the one-tap
  3753. verdict links carry.
  3754. Lives here rather than inline in ``on_print_complete``'s notification task
  3755. because that task swallows every exception: extracted, the gate and the two
  3756. emissions can be driven by a test, which is the only thing standing between
  3757. a regression here and a farm that quietly stops asking.
  3758. Returns whether a prompt was sent.
  3759. """
  3760. logger = logging.getLogger(__name__)
  3761. from backend.app.models.archive import PrintArchive
  3762. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3763. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3764. return False
  3765. import secrets as _secrets
  3766. # A spent token stays on the row so the one-tap route can recognise it, so
  3767. # "has a token" no longer means "answerable". A prompt going out now needs a
  3768. # live one: mint a new token whenever the stored one is already spent, or
  3769. # every button in the new message would land on the already-answered page.
  3770. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  3771. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  3772. confirm_archive.confirm_token_used_at = None
  3773. await db.commit()
  3774. from backend.app.api.routes.settings import get_external_base_url, get_setting
  3775. base = await get_external_base_url(db)
  3776. if not await get_setting(db, "external_url"):
  3777. # Both the Telegram inline keyboard and the ntfy action buttons need an
  3778. # absolute URL, so an unconfigured install used to get a message body
  3779. # with two unusable relative paths and no buttons at all. The shared
  3780. # fallback at least produces tappable links; say which setting makes
  3781. # them resolve from a phone.
  3782. logger.warning(
  3783. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  3784. "Set Settings → External URL so they resolve away from this host.",
  3785. base,
  3786. )
  3787. token = confirm_archive.confirm_token
  3788. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  3789. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  3790. confirm_url = f"{base}/archives?confirm={archive_id}"
  3791. await ws_manager.send_print_confirm_request(
  3792. printer_id,
  3793. {
  3794. "archive_id": archive_id,
  3795. "print_name": confirm_archive.print_name or confirm_archive.filename,
  3796. },
  3797. )
  3798. await notification_service.on_print_confirm_request(
  3799. printer_id,
  3800. printer_name,
  3801. data,
  3802. db,
  3803. archive_data=archive_data,
  3804. good_url=good_url,
  3805. reject_url=reject_url,
  3806. confirm_url=confirm_url,
  3807. archive_id=archive_id,
  3808. )
  3809. return True
  3810. async def _printer_gone(db, printer_id: int) -> bool:
  3811. """Whether the printer was deleted. A column read: the session's loaded
  3812. Printer would otherwise answer for the database."""
  3813. from backend.app.models.printer import Printer
  3814. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  3815. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  3816. """Remove the archive just written if its printer was deleted meanwhile.
  3817. The delete route sweeps the printer's archives before it commits, so a row
  3818. committed after that sweep (the check before writing passed while the
  3819. delete was still uncommitted) is left for a printer that will never report
  3820. the print's end. A row the sweep reached is the route's: deleted with the
  3821. printer's archives, or detached (printer_id NULL) when the user kept them,
  3822. and then left as it is. Either way nothing is registered for it. Run after
  3823. the archive's commit, before anything is registered for it.
  3824. """
  3825. from backend.app.models.archive import PrintArchive
  3826. if not await _printer_gone(db, printer_id):
  3827. return False
  3828. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  3829. if owner == printer_id:
  3830. logging.getLogger(__name__).info(
  3831. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  3832. )
  3833. await ArchiveService(db).delete_archive(archive_id)
  3834. await forget_printer(printer_id)
  3835. return True
  3836. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  3837. """After an IntegrityError on a print start's archive write: whether it was
  3838. the printer being deleted, forgotten then (the caller returns).
  3839. PostgreSQL: the delete route locks the printer from its archive sweep to its
  3840. commit, so an archive written or adopted for it meanwhile (one that sets
  3841. printer_id) waits and the printer's foreign key then refuses it. That is
  3842. the printer being deleted, not an error; anything else is re-raised by the
  3843. caller.
  3844. """
  3845. await db.rollback()
  3846. if not await _printer_gone(db, printer_id):
  3847. return False
  3848. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  3849. await forget_printer(printer_id)
  3850. return True
  3851. async def _forget_if_printer_gone(printer_id: int) -> None:
  3852. """At the end of a print start: the slow steps after the last check (smart
  3853. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  3854. printer's delete and its forget_printer, and then wrote state back.
  3855. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  3856. SQLite; PostgreSQL refuses it.)
  3857. Its own session: those steps can leave the handler's needing a rollback (a
  3858. write to the archive the delete removed). Never raises: it runs inside the
  3859. fallback branch's try, whose except reports the archive as failed.
  3860. """
  3861. try:
  3862. async with async_session() as db:
  3863. gone = await _printer_gone(db, printer_id)
  3864. if gone:
  3865. await forget_printer(printer_id)
  3866. except Exception:
  3867. logging.getLogger(__name__).warning(
  3868. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  3869. )
  3870. async def _announce_plate_check_failed(printer_id: int, printer_name: str, reason: str) -> None:
  3871. """Tell the UI a plate check could not run. It does not block the print,
  3872. but an unchecked plate is not an empty one."""
  3873. try:
  3874. await ws_manager.broadcast(
  3875. {"type": "plate_check_failed", "printer_id": printer_id, "printer_name": printer_name, "reason": reason}
  3876. )
  3877. except Exception as e:
  3878. logging.getLogger(__name__).warning("[PLATE CHECK] Could not announce the failed check: %s", e)
  3879. def _expected_print_keys(printer_id: int, filename: str | None, subtask_name: str | None) -> list[tuple[int, str]]:
  3880. """The ``_expected_prints`` keys a print start may be registered under."""
  3881. keys: list[tuple[int, str]] = []
  3882. if subtask_name:
  3883. keys.append((printer_id, subtask_name))
  3884. keys.append((printer_id, f"{subtask_name}.3mf"))
  3885. keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3886. if filename:
  3887. fname = filename.split("/")[-1] if "/" in filename else filename
  3888. keys.append((printer_id, fname))
  3889. # Strip extensions to match
  3890. base = fname.replace(".gcode", "").replace(".3mf", "")
  3891. keys.append((printer_id, base))
  3892. keys.append((printer_id, f"{base}.3mf"))
  3893. return keys
  3894. async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, subtask_name: str | None) -> bool:
  3895. """Whether this print start is one Bambuddy sent to the printer."""
  3896. if any(key in _expected_prints for key in _expected_print_keys(printer_id, filename, subtask_name)):
  3897. return True
  3898. from backend.app.models.archive import PrintArchive
  3899. from backend.app.models.print_queue import PrintQueueItem
  3900. # The queue row the scheduler sets to printing before it sends -- but only
  3901. # when it was sent as this print: a row left printing by a run whose end
  3902. # was missed names another file.
  3903. dispatched_names = (
  3904. await db.execute(
  3905. select(PrintArchive.filename)
  3906. .join(PrintQueueItem, PrintQueueItem.archive_id == PrintArchive.id)
  3907. .where(PrintQueueItem.printer_id == printer_id, PrintQueueItem.status == "printing")
  3908. )
  3909. ).scalars()
  3910. observed = [name for name in (subtask_name, (filename or "").rsplit("/", 1)[-1]) if name]
  3911. return any(
  3912. _subtask_names_match(_subtask_name_from_filename(dispatched), _subtask_name_from_filename(seen))
  3913. for dispatched in dispatched_names
  3914. if dispatched
  3915. for seen in observed
  3916. )
  3917. async def on_print_start(printer_id: int, data: dict):
  3918. """Handle print start - archive the 3MF file immediately."""
  3919. logger = logging.getLogger(__name__)
  3920. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3921. try:
  3922. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  3923. except Exception:
  3924. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  3925. # Clear any stale user-stopped flag from previous print cycles
  3926. _user_stopped_printers.discard(printer_id)
  3927. _kill_switch_stopped.discard(printer_id)
  3928. # A new print starts its milestones from zero (#3211). The status path only
  3929. # resets on progress below 5 while not printing, which a printer that goes
  3930. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  3931. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  3932. # or on resume from pause, so it cannot repeat a milestone mid-print.
  3933. _last_progress_milestone[printer_id] = 0
  3934. _kill_switch_notification_tasks.pop(printer_id, None)
  3935. # #1721: drop any leftover pre-captured finish frame from a prior print
  3936. # so a never-consumed cache entry can't bleed into the new print's photo.
  3937. _stage22_finish_frames.pop(printer_id, None)
  3938. # #1867: same for the in-print frame bank — a queued print must not reuse
  3939. # the previous job's banked frame.
  3940. _inprint_frame_bank.pop(printer_id, None)
  3941. _inprint_frame_bank_ts.pop(printer_id, None)
  3942. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3943. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3944. # print's flag instead of inheriting it.
  3945. print_dispatch_context.adopt(printer_id)
  3946. # Cancel any active bed cooldown waiter for this printer
  3947. if _bed_cool_waiters.pop(printer_id, None):
  3948. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  3949. # Clear cached cover images so the new print's thumbnail is fetched fresh
  3950. from backend.app.api.routes.printers import clear_cover_cache
  3951. clear_cover_cache(printer_id)
  3952. await ws_manager.send_print_start(printer_id, data)
  3953. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  3954. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  3955. # MQTT relay - publish print start
  3956. try:
  3957. printer_info = printer_manager.get_printer(printer_id)
  3958. if printer_info:
  3959. await mqtt_relay.on_print_start(
  3960. printer_id,
  3961. printer_info.name,
  3962. printer_info.serial_number,
  3963. data.get("filename", ""),
  3964. data.get("subtask_name", ""),
  3965. )
  3966. except Exception:
  3967. pass # Don't fail print start callback if MQTT fails
  3968. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  3969. # and mapping, and the seeded tray-change log.
  3970. #
  3971. # Unconditional, for both inventory backends. This only *captures* — the
  3972. # writing is still split, with the internal tracker skipped at completion
  3973. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  3974. # carries its plate-scoped 3MF figures and stored mapping, but not the
  3975. # tray-change log, and that log is the only record of which spool fed
  3976. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  3977. # it on one side only would leave Spoolman users with the mid-print
  3978. # restart bug this fixes for everyone else.
  3979. try:
  3980. async with async_session() as db:
  3981. from backend.app.api.routes.settings import get_setting
  3982. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  3983. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3984. await usage_on_print_start(
  3985. printer_id,
  3986. data,
  3987. printer_manager,
  3988. db=db,
  3989. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  3990. )
  3991. except Exception as e:
  3992. logger.warning("Usage tracker on_print_start failed: %s", e)
  3993. # Track if notification was sent (to avoid sending twice)
  3994. notification_sent = False
  3995. # Smart plug automation: turn on plug when print starts
  3996. try:
  3997. async with async_session() as db:
  3998. await smart_plug_manager.on_print_start(printer_id, db)
  3999. except Exception as e:
  4000. logger.warning("Smart plug on_print_start failed: %s", e)
  4001. async with async_session() as db:
  4002. from backend.app.models.printer import Printer
  4003. from backend.app.services.bambu_ftp import list_files_async
  4004. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4005. printer = result.scalar_one_or_none()
  4006. # Plate detection check - pause if objects detected on build plate
  4007. logger.info(
  4008. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  4009. )
  4010. if printer and printer.plate_detection_enabled:
  4011. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  4012. # Release the pooled DB connection before the plate-detection camera
  4013. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  4014. # printer SELECT has run so far — nothing to persist — so this commit
  4015. # is a data-noop that ends the read transaction and returns the
  4016. # connection to the pool during the I/O (issue #2572). expire_on_commit
  4017. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  4018. # archive lookups below re-acquire a fresh connection on next execute.
  4019. await db.commit()
  4020. try:
  4021. from backend.app.services.plate_detection import check_plate_empty
  4022. # Build ROI tuple from printer settings if available
  4023. roi = None
  4024. if all(
  4025. [
  4026. printer.plate_detection_roi_x is not None,
  4027. printer.plate_detection_roi_y is not None,
  4028. printer.plate_detection_roi_w is not None,
  4029. printer.plate_detection_roi_h is not None,
  4030. ]
  4031. ):
  4032. roi = (
  4033. printer.plate_detection_roi_x,
  4034. printer.plate_detection_roi_y,
  4035. printer.plate_detection_roi_w,
  4036. printer.plate_detection_roi_h,
  4037. )
  4038. # The light is held, not switched, so a live view opened
  4039. # meanwhile keeps it when the check lets go (SP-C11). Every
  4040. # printer, whatever the camera light mode: detection needs it.
  4041. plate_photo_data = None
  4042. objects_detected = False
  4043. check_failure: str | None = None
  4044. async with camera_light(printer, any_mode=True, settle=2.5):
  4045. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  4046. plate_result = await check_plate_empty(
  4047. printer_id=printer_id,
  4048. ip_address=printer.ip_address,
  4049. access_code=printer.access_code,
  4050. model=printer.model,
  4051. include_debug_image=False,
  4052. external_camera_url=printer.external_camera_url,
  4053. external_camera_type=printer.external_camera_type,
  4054. use_external=printer.external_camera_enabled,
  4055. roi=roi,
  4056. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  4057. )
  4058. # No reference to compare against is a check that did not
  4059. # run either: say so rather than call the plate empty.
  4060. check_failure = getattr(plate_result, "failure_reason", None) or (
  4061. "not_calibrated" if plate_result.needs_calibration else None
  4062. )
  4063. objects_detected = not check_failure and not plate_result.is_empty
  4064. if objects_detected:
  4065. # Objects detected - pause the print!
  4066. logger.warning(
  4067. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  4068. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  4069. )
  4070. pause_client = printer_manager.get_client(printer_id)
  4071. if pause_client:
  4072. pause_client.pause_print()
  4073. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  4074. # Snapshot while the light's still on — restoring it first
  4075. # would leave the notification with a dark photo.
  4076. try:
  4077. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  4078. except Exception as snap_err:
  4079. logger.warning(
  4080. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  4081. )
  4082. if objects_detected:
  4083. # Send notification about plate not empty
  4084. await ws_manager.broadcast(
  4085. {
  4086. "type": "plate_not_empty",
  4087. "printer_id": printer_id,
  4088. "printer_name": printer.name,
  4089. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  4090. }
  4091. )
  4092. # Also send push notification
  4093. try:
  4094. await notification_service.on_plate_not_empty(
  4095. printer_id=printer_id,
  4096. printer_name=printer.name,
  4097. db=db,
  4098. difference_percent=plate_result.difference_percent,
  4099. image_data=plate_photo_data,
  4100. )
  4101. except Exception as notif_err:
  4102. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4103. elif check_failure:
  4104. logger.warning(
  4105. "[PLATE CHECK] Plate check could not run for printer %s (%s): %s; proceeding with print",
  4106. printer_id,
  4107. check_failure,
  4108. plate_result.message,
  4109. )
  4110. await _announce_plate_check_failed(printer_id, printer.name, check_failure)
  4111. else:
  4112. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4113. except Exception as plate_err:
  4114. # Don't block print on plate detection errors
  4115. logger.warning(
  4116. "[PLATE CHECK] Plate check could not run for printer %s: %s; proceeding with print",
  4117. printer_id,
  4118. plate_err,
  4119. )
  4120. await _announce_plate_check_failed(printer_id, printer.name, "error")
  4121. if not printer:
  4122. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4123. if not notification_sent:
  4124. await _send_print_start_notification(printer_id, data, logger=logger)
  4125. return
  4126. # Skip the printer's own jobs — a calibration run is not a user's print.
  4127. # See is_internal_printer_job for what counts and why both fields are
  4128. # tested; the pressure-advance line reports as a subtask name with no
  4129. # /usr/ path, which the old prefix-only test here missed entirely.
  4130. #
  4131. # No notification either. The event describes the printer calibrating
  4132. # itself, so "Print started" is as wrong as the archive was, and the
  4133. # matching completion is suppressed in on_print_complete for the same
  4134. # reason. Checked before the auto-archive switches, whose "off" path
  4135. # still notifies.
  4136. # A /usr/ path is the printer's own file. A name alone is not proof: a
  4137. # print Bambuddy dispatched is never one, whatever it is called.
  4138. # Dispatched = an expected print, or, after a restart that lost those,
  4139. # a queue job printing on the printer.
  4140. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")) and (
  4141. (data.get("filename") or "").startswith("/usr/")
  4142. or not await _dispatched_by_bambuddy(db, printer_id, data.get("filename", ""), data.get("subtask_name", ""))
  4143. ):
  4144. logger.info(
  4145. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4146. data.get("filename", ""),
  4147. data.get("subtask_name", ""),
  4148. )
  4149. return
  4150. # The global switch is the master: off, no printer archives prints
  4151. # started outside Bambuddy; on, each printer's own switch decides.
  4152. from backend.app.api.routes.settings import get_setting
  4153. _global_auto_archive = await get_setting(db, "auto_archive")
  4154. archives_prints = printer.auto_archive and (
  4155. _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4156. )
  4157. if not archives_prints:
  4158. # auto-archive disabled — check if there's an expected print (dispatched
  4159. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4160. # If so, fall through to the expected-print handling below so the archive
  4161. # is tracked in _active_prints and usage tracking works at completion.
  4162. _fn = data.get("filename", "")
  4163. _sn = data.get("subtask_name", "")
  4164. _check_keys: list[tuple[int, str]] = []
  4165. if _sn:
  4166. _check_keys += [
  4167. (printer_id, _sn),
  4168. (printer_id, f"{_sn}.3mf"),
  4169. (printer_id, f"{_sn}.gcode.3mf"),
  4170. ]
  4171. if _fn:
  4172. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4173. _check_keys.append((printer_id, _base_fn))
  4174. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4175. _check_keys += [
  4176. (printer_id, _no_archive_base),
  4177. (printer_id, f"{_no_archive_base}.3mf"),
  4178. ]
  4179. _has_expected = any(k in _expected_prints for k in _check_keys)
  4180. if not _has_expected:
  4181. # No expected print — truly external print (started from slicer/touchscreen)
  4182. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4183. if not notification_sent:
  4184. _no_archive_creator: int | None = None
  4185. for _key in _check_keys:
  4186. _expected_prints.pop(_key, None)
  4187. _expected_print_registered_at.pop(_key, None)
  4188. popped_creator = _expected_print_creators.pop(_key, None)
  4189. if _no_archive_creator is None:
  4190. _no_archive_creator = popped_creator
  4191. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4192. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4193. return
  4194. else:
  4195. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4196. # Get the filename and subtask_name
  4197. filename = data.get("filename", "")
  4198. subtask_name = data.get("subtask_name", "")
  4199. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4200. # present, it lets us match an archive across a backend restart (#972):
  4201. # same id → same print → resume the existing row instead of cancelling
  4202. # it and recreating from scratch (which loses started_at). Treat "0"
  4203. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4204. raw_mqtt = data.get("raw_data") or {}
  4205. subtask_id = raw_mqtt.get("subtask_id")
  4206. if subtask_id is not None:
  4207. subtask_id = str(subtask_id).strip()
  4208. if subtask_id in ("", "0"):
  4209. subtask_id = None
  4210. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4211. if not filename and not subtask_name:
  4212. # Send notification without archive data (no filename)
  4213. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4214. if not notification_sent:
  4215. await _send_print_start_notification(printer_id, data, logger=logger)
  4216. return
  4217. # Check if this is an expected print from reprint/scheduled
  4218. expected_keys = _expected_print_keys(printer_id, filename, subtask_name)
  4219. expected_archive_id = None
  4220. # Who queued it, taken with the entries it was registered beside: left
  4221. # behind once those are gone (the archive deleted mid-dispatch, or the
  4222. # start notification already sent), the expiry never saw it, and an
  4223. # unrelated later print of that name was attributed to that user (EP-2).
  4224. fallback_creator = None
  4225. for key in expected_keys:
  4226. expected_archive_id = _expected_prints.pop(key, None)
  4227. _expected_print_registered_at.pop(key, None)
  4228. if expected_archive_id:
  4229. # Clean up other possible keys for this print
  4230. for other_key in expected_keys:
  4231. _expected_prints.pop(other_key, None)
  4232. _expected_print_registered_at.pop(other_key, None)
  4233. creator = _expected_print_creators.pop(other_key, None)
  4234. if fallback_creator is None:
  4235. fallback_creator = creator
  4236. break
  4237. if expected_archive_id:
  4238. # This is a reprint/scheduled print - use existing archive, don't create new one
  4239. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4240. # Bambuddy dispatched it: the kill switch's fast path keeps it as
  4241. # Bambuddy's once the expected entry is consumed here.
  4242. _owned_print_archive_ids.add(expected_archive_id)
  4243. from backend.app.models.archive import PrintArchive
  4244. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4245. archive = result.scalar_one_or_none()
  4246. # Deleted after this handler loaded it (the plate check waits
  4247. # seconds) but before the route forgot the expected print: the
  4248. # archive the route kept or deleted is left as the route left it.
  4249. if archive and await _printer_gone(db, printer_id):
  4250. logger.info(
  4251. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4252. )
  4253. await forget_printer(printer_id)
  4254. return
  4255. if archive:
  4256. # As it was before this adoption: put back if the printer turns
  4257. # out to have been deleted while it was adopted (below).
  4258. before_adoption = {
  4259. attr.columns[0].name: getattr(archive, attr.key)
  4260. for attr in sa_inspect(PrintArchive).column_attrs
  4261. if attr.key != "id"
  4262. }
  4263. # Update archive status to printing
  4264. archive.status = "printing"
  4265. archive.started_at = datetime.now(timezone.utc)
  4266. # The previous run's outcome is not this one's: a reprint that
  4267. # completes must not keep showing why the last one failed.
  4268. archive.failure_reason = None
  4269. archive.completed_at = None
  4270. # The previous run's answer is still on this row and the
  4271. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4272. # so without a reset the second run inherits the first run's
  4273. # verdict: no prompt at all, and a green "good" badge on a run
  4274. # nobody ever judged.
  4275. if archive.confirm_requested:
  4276. archive.user_verdict = None
  4277. archive.user_verdict_source = None
  4278. archive.user_verdict_at = None
  4279. archive.confirm_token = None
  4280. archive.confirm_token_used_at = None
  4281. # Reprint of an archive reuses the source row. Without resetting
  4282. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4283. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4284. # extracts the *original* print's last frame, which then ships in
  4285. # the completion notification (#1707). Clear the path so the
  4286. # scanner runs fresh; also unlink the old video file so reprints
  4287. # don't accumulate orphans in the archive directory. Photos list
  4288. # is left alone — accumulating one finish photo per run is fine.
  4289. # The print-start baseline (#2704) is stale for the same reason:
  4290. # it describes the printer before the previous run. The capture
  4291. # below overwrites it, but clear it here too so an early failure
  4292. # can't leave the scan diffing against the wrong snapshot.
  4293. #
  4294. # Unlinked only when it is the same plate printing again. Every
  4295. # plate of a Send All shares this archive, and the video on it
  4296. # can be the only copy of another plate's run -- the printer's
  4297. # was deleted once it attached (#3275). That one is left in the
  4298. # archive directory, which goes with the archive. A video whose
  4299. # plate is not on record (attached by hand, or before the
  4300. # column existed) is kept too where the 3MF has other plates,
  4301. # or cannot be read: nothing tells it apart from another plate's,
  4302. # and keeping costs one file where deleting can cost the only
  4303. # copy. On an archive with exactly one plate it is that plate's.
  4304. archive.timelapse_baseline = None
  4305. stale_timelapse_relpath = archive.timelapse_path
  4306. stale_timelapse_plate_id = archive.timelapse_plate_id
  4307. starting_plate_id = _print_plate_ids.get(expected_archive_id)
  4308. if stale_timelapse_relpath:
  4309. archive.timelapse_path = None
  4310. archive.timelapse_plate_id = None
  4311. stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
  4312. if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
  4313. from backend.app.services.archive import plate_indexes_in_3mf
  4314. plates = await asyncio.to_thread(
  4315. plate_indexes_in_3mf,
  4316. app_settings.base_dir / archive.file_path, # SEC-PATH-OK: stored relative archive path
  4317. )
  4318. stale_is_this_plates = len(plates) == 1
  4319. if stale_timelapse_relpath and not stale_is_this_plates:
  4320. logger.info(
  4321. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4322. stale_timelapse_relpath,
  4323. stale_timelapse_plate_id,
  4324. expected_archive_id,
  4325. starting_plate_id,
  4326. )
  4327. # The video is deleted once the adoption stands (below).
  4328. delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
  4329. # Persist a restart-stable id so a later restart resumes this
  4330. # archive by subtask_id instead of name-matching + duplicating
  4331. # it (#1485). The printer often hasn't echoed subtask_id back
  4332. # this soon after dispatch, so fall back to the id Bambuddy
  4333. # minted when it sent the print command. Scoped to this
  4334. # expected-print branch on purpose: an expected match means
  4335. # Bambuddy dispatched this exact print in this process, so the
  4336. # client's last-dispatch id genuinely belongs to it — using it
  4337. # for an externally-started print could mis-tag the archive.
  4338. effective_subtask_id = subtask_id
  4339. if not effective_subtask_id:
  4340. _client = printer_manager.get_client(printer_id)
  4341. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4342. if _dispatched:
  4343. effective_subtask_id = str(_dispatched).strip() or None
  4344. # Update on first-set OR on reprint (the queue dispatcher mints
  4345. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4346. # the rewrite for reprints leaves the archive holding the FIRST
  4347. # run's id; if MQTT then reconnects mid-print, the reconciler
  4348. # (#1542) compares the stale stored id against the printer's
  4349. # live id, sees a mismatch, and synthesises a bogus PRINT
  4350. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4351. # in #1807. Inequality check preserves the noop-on-stable-push
  4352. # behaviour the earlier `not archive.subtask_id` guard provided.
  4353. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4354. archive.subtask_id = effective_subtask_id
  4355. # #1403 follow-up: VP-queue archives are created with
  4356. # printer_id=None at queue-add time (we don't know which
  4357. # printer will run the job yet). When the print actually
  4358. # starts on a specific printer the expected-archive lookup
  4359. # used to skip this assignment, leaving printer_id=None
  4360. # forever — which then disables the "Scan for timelapse"
  4361. # button in ArchivesPage (gated on !archive.printer_id).
  4362. if archive.printer_id != printer_id:
  4363. archive.printer_id = printer_id
  4364. adopting_id = archive.id # a rollback expires the object
  4365. try:
  4366. await db.commit()
  4367. except (IntegrityError, StaleDataError):
  4368. # The archive stays unchanged, or is gone: "delete archives"
  4369. # removed the row under the adoption, which then matched no
  4370. # row (StaleDataError) rather than being refused.
  4371. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4372. return
  4373. raise
  4374. # The printer can be deleted between the check above and this
  4375. # commit (the route's transaction lasts seconds), and the commit
  4376. # then adopted the archive anyway: status, verdict and timelapse
  4377. # changed, and the deleted printer's id written on a row the
  4378. # route had detached or never touched. Undo the adoption.
  4379. if await _printer_gone(db, printer_id):
  4380. logger.info(
  4381. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4382. printer_id,
  4383. archive.id,
  4384. )
  4385. # Everything as before this adoption. The printer it had
  4386. # then stays, unless it was the deleted one: the route
  4387. # detached that row (kept) or deleted it (no row matches).
  4388. previous_printer = before_adoption["printer_id"]
  4389. await db.execute(
  4390. update(PrintArchive)
  4391. .where(PrintArchive.id == archive.id)
  4392. .values(
  4393. {
  4394. **before_adoption,
  4395. "printer_id": None if previous_printer == printer_id else previous_printer,
  4396. }
  4397. )
  4398. )
  4399. await db.commit()
  4400. await forget_printer(printer_id)
  4401. return
  4402. if delete_stale_video and stale_timelapse_relpath:
  4403. try:
  4404. stale_path = app_settings.base_dir / stale_timelapse_relpath
  4405. if stale_path.is_file():
  4406. stale_path.unlink()
  4407. logger.info(
  4408. "Deleted stale timelapse %s on reprint of archive %s",
  4409. stale_timelapse_relpath,
  4410. expected_archive_id,
  4411. )
  4412. except OSError as e:
  4413. logger.warning(
  4414. "Failed to delete stale timelapse %s on reprint: %s",
  4415. stale_timelapse_relpath,
  4416. e,
  4417. )
  4418. # Track as active print
  4419. _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
  4420. # Start timelapse session if external camera is enabled (#1353).
  4421. # Queue / VP-dispatched prints land here in the expected-archive
  4422. # branch and used to skip start_session entirely — frames were
  4423. # never captured and the post-print stitch silently returned None.
  4424. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4425. # Inject ams_mapping into usage tracker session — the session was created
  4426. # before expected-print promotion, so it may have ams_mapping=None when
  4427. # the MQTT request topic subscription failed (common on P1S/A1).
  4428. _stored_map = _print_ams_mappings.get(expected_archive_id)
  4429. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  4430. if _stored_map or _stored_plate_id is not None:
  4431. try:
  4432. from backend.app.services.usage_tracker import _active_sessions
  4433. _ut_session = _active_sessions.get(printer_id)
  4434. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4435. _ut_session.ams_mapping = _stored_map
  4436. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4437. # plate_id injection covers direct-Print of plate N of a multi-plate
  4438. # 3MF — queue prints already capture it via the on_print_start queue
  4439. # lookup, but direct-Print never goes through the queue (#1697).
  4440. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4441. _ut_session.plate_id = _stored_plate_id
  4442. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4443. except Exception:
  4444. pass
  4445. # Set up energy tracking (#941: persist start on archive row)
  4446. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4447. await ws_manager.send_archive_updated(
  4448. {
  4449. "id": archive.id,
  4450. "status": "printing",
  4451. }
  4452. )
  4453. # Send notification with archive data (reprint/scheduled)
  4454. if not notification_sent:
  4455. # Use archive's created_by_id; fall back to the creator registered via
  4456. # register_expected_print (handles library-file-based queue items where
  4457. # the freshly-created archive has no created_by_id yet), taken above.
  4458. archive_data = {
  4459. "print_time_seconds": archive.print_time_seconds,
  4460. "created_by_id": archive.created_by_id or fallback_creator,
  4461. }
  4462. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4463. # Extract printable objects from the archived 3MF file
  4464. _load_objects_from_archive(archive, printer_id, logger)
  4465. # Store Spoolman tracking data for per-filament usage reporting
  4466. try:
  4467. await _store_spoolman_print_data(
  4468. printer_id,
  4469. archive.id,
  4470. archive.file_path,
  4471. db,
  4472. printer_manager,
  4473. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4474. plate_id=_get_start_plate_id(archive.id),
  4475. )
  4476. except Exception as e:
  4477. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4478. # Price the print from its spools now rather than only at completion (#3261)
  4479. _schedule_archive_cost_estimate(
  4480. printer_id,
  4481. archive.id,
  4482. printer_manager,
  4483. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4484. plate_id=_get_start_plate_id(archive.id),
  4485. session_factory=async_session,
  4486. )
  4487. # Capture timelapse file baseline for snapshot-diff on completion
  4488. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4489. # hit this branch — without the baseline the completion-time scan
  4490. # falls into its "take baseline now" fallback, which snapshots
  4491. # AFTER the new MP4 already exists and never matches a diff
  4492. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4493. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4494. await _forget_if_printer_gone(printer_id)
  4495. return # Skip creating a new archive
  4496. # The archive was deleted after the job was queued.
  4497. if not archives_prints:
  4498. # Only the expected print brought a printer that does not
  4499. # archive this far; with it gone, nothing is archived.
  4500. return
  4501. # Otherwise archive the print anew rather than drop it, so it still
  4502. # gets its notification, usage tracking and history.
  4503. logger.warning(
  4504. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4505. expected_archive_id,
  4506. printer_id,
  4507. )
  4508. # Check if there's already a "printing" archive for this printer/file
  4509. # This prevents duplicates when backend restarts during an active print
  4510. from backend.app.models.archive import PrintArchive
  4511. existing_archive: PrintArchive | None = None
  4512. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4513. # across a backend restart for the same print, so this is the most
  4514. # reliable way to reattach. Only a row still printing: a cancelled one
  4515. # has been through completion (usage, history, notifications) already,
  4516. # and reopening it would count the print twice.
  4517. if subtask_id:
  4518. by_id = await db.execute(
  4519. select(PrintArchive)
  4520. .where(PrintArchive.printer_id == printer_id)
  4521. .where(PrintArchive.subtask_id == subtask_id)
  4522. .where(PrintArchive.status == "printing")
  4523. .order_by(PrintArchive.created_at.desc())
  4524. .limit(1)
  4525. )
  4526. existing_archive = by_id.scalar_one_or_none()
  4527. # Fallback match: name-based lookup. Kept as-is for prints whose
  4528. # subtask_id is missing ("0" / local / non-cloud prints).
  4529. if existing_archive is None:
  4530. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4531. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4532. # A print started from the printer's screen names its file in full,
  4533. # so the forms above double its extension. The file itself is the
  4534. # one exact match, and nothing looser is added (#3009).
  4535. if _subtask_is_the_file(subtask_name, filename):
  4536. archive_filenames.append(subtask_name)
  4537. existing = await db.execute(
  4538. select(PrintArchive)
  4539. .where(PrintArchive.printer_id == printer_id)
  4540. .where(PrintArchive.status == "printing")
  4541. .where(
  4542. or_(
  4543. PrintArchive.print_name == check_name,
  4544. PrintArchive.filename.in_(archive_filenames),
  4545. )
  4546. )
  4547. .order_by(PrintArchive.created_at.desc())
  4548. .limit(1)
  4549. )
  4550. existing_archive = existing.scalar_one_or_none()
  4551. if existing_archive:
  4552. # subtask_id match → always resume, regardless of age. Same print,
  4553. # just a backend restart.
  4554. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4555. if subtask_match:
  4556. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4557. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4558. _mark_owned_if_dispatched(existing_archive)
  4559. if existing_archive.energy_start_kwh is None:
  4560. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4561. if not notification_sent:
  4562. archive_data = {
  4563. "print_time_seconds": existing_archive.print_time_seconds,
  4564. "created_by_id": existing_archive.created_by_id,
  4565. }
  4566. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4567. _load_objects_from_archive(existing_archive, printer_id, logger)
  4568. return
  4569. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4570. # stale from the printer's *current* progress, not wall-clock age.
  4571. # A genuinely long print used to trip a blind 4h cutoff and have its
  4572. # live archive cancelled + duplicated on every backend restart
  4573. # (#1485). If the printer reports real progress, this name-matched
  4574. # 'printing' archive IS that ongoing print — resume it whatever its
  4575. # age. Only treat it as a stale leftover when the printer clearly
  4576. # shows a different, freshly-started print: near-0% progress on an
  4577. # archive far too old to still be at 0%. Unknown progress (printer
  4578. # not connected) never cancels — resuming is the safe default.
  4579. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4580. live_status = printer_manager.get_status(printer_id)
  4581. live_progress = getattr(live_status, "progress", None) if live_status else None
  4582. looks_stale = (
  4583. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4584. )
  4585. # Two subtask ids are two prints, however young the archive: one
  4586. # whose completion was missed must not swallow the next print of
  4587. # the same file. Except Bambuddy's own reprint, which reuses the
  4588. # row and mints a fresh id (#1807): the id it last sent says so,
  4589. # and after a restart, which forgets it, this printer's queue job
  4590. # running the archive.
  4591. if (
  4592. not looks_stale
  4593. and subtask_id
  4594. and existing_archive.subtask_id
  4595. and existing_archive.subtask_id != subtask_id
  4596. ):
  4597. _client = printer_manager.get_client(printer_id)
  4598. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  4599. if _dispatched:
  4600. looks_stale = _dispatched != subtask_id
  4601. else:
  4602. from backend.app.models.print_queue import PrintQueueItem as _PQI
  4603. queue_run = await db.scalar(
  4604. select(_PQI.id)
  4605. .where(_PQI.archive_id == existing_archive.id)
  4606. .where(_PQI.printer_id == printer_id)
  4607. .where(_PQI.status == "printing")
  4608. .limit(1)
  4609. )
  4610. looks_stale = queue_run is None
  4611. if looks_stale:
  4612. logger.warning(
  4613. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  4614. " — marking cancelled and creating new archive",
  4615. existing_archive.id,
  4616. archive_age,
  4617. live_progress,
  4618. existing_archive.subtask_id,
  4619. subtask_id,
  4620. )
  4621. existing_archive.status = "cancelled"
  4622. # Canonical key, not a sentence (issue #2974). "No status update
  4623. # received" is what both stale paths actually observed; which of
  4624. # the two it was is already carried by ``status`` -- cancelled
  4625. # here, the reconciled outcome at the reconnect site -- so one
  4626. # key loses no information and gives the Statistics breakdown a
  4627. # single bucket instead of two untranslatable prose strings.
  4628. existing_archive.failure_reason = "noStatusUpdate"
  4629. await db.commit()
  4630. # Its print keys go with it; the new archive registers its own.
  4631. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id]:
  4632. del _active_prints[_key]
  4633. # Fall through to create new archive (don't return)
  4634. else:
  4635. logger.info(
  4636. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4637. )
  4638. # Track this as the active print
  4639. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4640. _mark_owned_if_dispatched(existing_archive)
  4641. # Attach subtask_id retroactively so future restarts can resume.
  4642. # Compare for inequality (not "is empty") to also pick up reprint
  4643. # dispatches that mint a fresh id — see #1807 for the bogus
  4644. # "Print Stopped" the strict-empty guard caused on reconnect.
  4645. if subtask_id and existing_archive.subtask_id != subtask_id:
  4646. existing_archive.subtask_id = subtask_id
  4647. await db.commit()
  4648. # Also set up energy tracking if not already tracked (#941: persisted column)
  4649. if existing_archive.energy_start_kwh is None:
  4650. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4651. # Send notification with archive data (existing archive)
  4652. if not notification_sent:
  4653. archive_data = {
  4654. "print_time_seconds": existing_archive.print_time_seconds,
  4655. "created_by_id": existing_archive.created_by_id,
  4656. }
  4657. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4658. # Extract printable objects from the archived 3MF file
  4659. _load_objects_from_archive(existing_archive, printer_id, logger)
  4660. return
  4661. # Build list of possible 3MF filenames to try
  4662. possible_names = []
  4663. # Bambu printers typically store files as "Name.gcode.3mf"
  4664. # The subtask_name is usually the best source for the filename
  4665. if subtask_name:
  4666. if _subtask_is_the_file(subtask_name, filename):
  4667. # A print started from the printer's own screen reports the
  4668. # file's full name, extension included. That is the file, so
  4669. # no extension is appended to it (#3009).
  4670. possible_names.append(subtask_name)
  4671. else:
  4672. # Try common Bambu naming patterns
  4673. possible_names.append(f"{subtask_name}.gcode.3mf")
  4674. possible_names.append(f"{subtask_name}.3mf")
  4675. # Try original filename with .3mf extension
  4676. if filename:
  4677. # Extract just the filename part, not the full path
  4678. fname = filename.split("/")[-1] if "/" in filename else filename
  4679. if fname.endswith(".3mf"):
  4680. possible_names.append(fname)
  4681. elif fname.endswith(".gcode"):
  4682. base = fname.rsplit(".", 1)[0]
  4683. possible_names.append(f"{base}.gcode.3mf")
  4684. possible_names.append(f"{base}.3mf")
  4685. else:
  4686. possible_names.append(f"{fname}.gcode.3mf")
  4687. possible_names.append(f"{fname}.3mf")
  4688. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4689. space_variants = []
  4690. for name in possible_names:
  4691. if " " in name:
  4692. space_variants.append(name.replace(" ", "_"))
  4693. possible_names.extend(space_variants)
  4694. # Remove duplicates while preserving order
  4695. seen = set()
  4696. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4697. logger.info("Trying filenames: %s", possible_names)
  4698. # Release the pooled DB connection before the 3MF FTP download. Reaching
  4699. # here means none of the expected-/existing-archive write branches ran
  4700. # (they all return earlier) — only SELECTs have executed on this path, so
  4701. # this commit persists nothing; it ends the read transaction so the
  4702. # connection returns to the pool during the download. That download tries
  4703. # up to five remote paths per candidate filename with retry/backoff and
  4704. # can run for minutes under FTP contention; holding the session across it
  4705. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  4706. # work runs during the download — the new-archive writes below re-acquire
  4707. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  4708. await db.commit()
  4709. # Try to find and download the 3MF file
  4710. temp_path = None
  4711. downloaded_filename = None
  4712. # Cache check: cover endpoint may have already pulled this 3MF during
  4713. # the print (frontend opens the card and shows the thumbnail) — reuse
  4714. # that file instead of re-downloading 36MB over the same FTP link that
  4715. # just served it (#972). The cache keys on a normalized filename so
  4716. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  4717. for try_filename in possible_names:
  4718. if not try_filename.endswith(".3mf"):
  4719. continue
  4720. cached = get_cached_3mf(printer_id, try_filename)
  4721. if cached:
  4722. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  4723. temp_path = cached
  4724. downloaded_filename = try_filename
  4725. break
  4726. # Does this printer keep the sliced file somewhere FTPS can reach? On
  4727. # H2-series and P2S the answer is routinely no — the file stays on
  4728. # internal eMMC and port 990 only ever serves external storage — and
  4729. # then the whole sweep below (six filenames x five directories x four
  4730. # retries, then the directory walk) is ~110 connections that cannot
  4731. # succeed. Skip it and say why (#2780).
  4732. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  4733. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  4734. # running rather than because the file is somewhere unreachable. The
  4735. # distinction is the whole of #2957: one is permanent, the other clears
  4736. # in minutes with the file still sitting on the printer.
  4737. blocked_by_ftps_cooloff = False
  4738. # Set when a probe reached the printer and still came back without the
  4739. # file -- a timeout mid-transfer, a refused connection, anything that is
  4740. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  4741. # caught by name below, so a file that genuinely is not on the card
  4742. # leaves this False and schedules nothing. Anything else means the
  4743. # transfer, not the file, is what failed, and that does not last (#3063).
  4744. ftp_transfer_failed = False
  4745. # The print's name, for a fallback archive whose `subtask_name` the
  4746. # plate guard below had to disown. Display only, and deliberately kept
  4747. # apart from `subtask_name`: that variable is what every file lookup
  4748. # here is built from, and once a name has been shown to fetch another
  4749. # plate's 3MF it must not key `_active_prints` either, or the cover
  4750. # endpoint hands the same contradicted file to
  4751. # `_recover_fallback_archive` and fills the row in with it (#3126).
  4752. display_name_after_plate_reject: str | None = None
  4753. # Get FTP retry settings
  4754. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  4755. # ...but "the printer put it on eMMC" is where it went, not whether we
  4756. # can read it. An H2D with a card in mirrors the job to /cache and
  4757. # serves it happily, and skipping on the URL alone cost that reporter
  4758. # every archive for two days (#2856). So ask the printer instead of
  4759. # guessing: the dispatch named the exact file, which is one connection
  4760. # walking five paths rather than the sweep's ~110. Only when the probe
  4761. # comes back empty does the verdict's reason stand.
  4762. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  4763. if ftps_handshake_blocked(printer.ip_address):
  4764. # Deliberately NOT recorded as a cool-off give-up. This branch
  4765. # only runs on an unreachable verdict, and that verdict is the
  4766. # honest, permanent reason the archive is empty — the probe was
  4767. # a long shot on top of it. Blaming the cool-off here would
  4768. # schedule a retry for a file sitting on internal eMMC, which is
  4769. # the sweep #2780 removed (#2957).
  4770. logger.debug(
  4771. "Not probing for %s on printer %s: its file service is not answering over TLS",
  4772. storage.probe_filename,
  4773. printer_id,
  4774. )
  4775. else:
  4776. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  4777. probe_path.parent.mkdir(parents=True, exist_ok=True)
  4778. try:
  4779. probe_hit = await download_file_try_paths_async(
  4780. printer.ip_address,
  4781. printer.access_code,
  4782. ftp_probe_paths(storage.probe_filename),
  4783. probe_path,
  4784. socket_timeout=ftp_timeout,
  4785. printer_model=printer.model,
  4786. )
  4787. except Exception as e:
  4788. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  4789. probe_hit = False
  4790. if probe_hit:
  4791. downloaded_filename = storage.probe_filename
  4792. temp_path = probe_path
  4793. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  4794. # Naming the path, not just the file: a printer that keeps
  4795. # uploads around for weeks can serve a same-named copy of an
  4796. # earlier slice, and without the directory in the log that
  4797. # mismatch is invisible rather than merely rare (#1820).
  4798. logger.info(
  4799. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  4800. downloaded_filename,
  4801. probe_hit,
  4802. printer_id,
  4803. storage.reason,
  4804. )
  4805. if not storage.reachable and not downloaded_filename:
  4806. # Same opening words whether or not a probe ran, because that is
  4807. # the phrase support asks people to grep for — only the tail says
  4808. # which of the two happened.
  4809. logger.info(
  4810. "Skipping the 3MF lookup for printer %s: %s — %s",
  4811. printer_id,
  4812. storage.reason,
  4813. "no copy of it on external storage either"
  4814. if storage.probe_filename
  4815. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  4816. )
  4817. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  4818. if not try_filename.endswith(".3mf"):
  4819. continue
  4820. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  4821. # printers, so try it first — deferring it to last cost #972's reporter
  4822. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  4823. # landing on the path that actually had the file.
  4824. remote_paths = [
  4825. f"/{try_filename}",
  4826. f"/cache/{try_filename}",
  4827. f"/model/{try_filename}",
  4828. f"/data/{try_filename}",
  4829. f"/data/Metadata/{try_filename}",
  4830. ]
  4831. temp_path = app_settings.archive_dir / "temp" / try_filename
  4832. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4833. for remote_path in remote_paths:
  4834. if ftps_handshake_blocked(printer.ip_address):
  4835. # The printer's FTPS service is not completing a TLS
  4836. # handshake, so it has no path we could reach — walking the
  4837. # remaining candidates only re-runs the same failure
  4838. # (#2780). Fall through to the no-3MF archive now.
  4839. #
  4840. # Remember *why*, though. This is the one give-up that is
  4841. # temporary: the cool-off clears in minutes and the file was
  4842. # on the printer the whole time. The fallback archive is
  4843. # stamped with it so a retry can be scheduled, and so the
  4844. # Archives banner stops blaming storage (#2957).
  4845. blocked_by_ftps_cooloff = True
  4846. logger.warning(
  4847. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  4848. printer_id,
  4849. )
  4850. break
  4851. logger.debug("Trying FTP download: %s", remote_path)
  4852. try:
  4853. if ftp_retry_enabled:
  4854. downloaded = await with_ftp_retry(
  4855. download_file_async,
  4856. printer.ip_address,
  4857. printer.access_code,
  4858. remote_path,
  4859. temp_path,
  4860. timeout=ftp_timeout,
  4861. socket_timeout=ftp_timeout,
  4862. printer_model=printer.model,
  4863. max_retries=ftp_retry_count,
  4864. retry_delay=ftp_retry_delay,
  4865. operation_name=f"Download 3MF from {remote_path}",
  4866. cooloff_ip=printer.ip_address,
  4867. non_retry_exceptions=(FileNotOnPrinterError,),
  4868. )
  4869. else:
  4870. downloaded = await download_file_async(
  4871. printer.ip_address,
  4872. printer.access_code,
  4873. remote_path,
  4874. temp_path,
  4875. timeout=ftp_timeout,
  4876. socket_timeout=ftp_timeout,
  4877. printer_model=printer.model,
  4878. )
  4879. if downloaded:
  4880. downloaded_filename = try_filename
  4881. logger.info("Downloaded: %s", remote_path)
  4882. # Populate shared cache so the cover endpoint (if it
  4883. # runs next) doesn't refetch the same 36MB over FTP.
  4884. cache_3mf_download(printer_id, try_filename, temp_path)
  4885. break
  4886. # with_ftp_retry returns None once it has spent its budget,
  4887. # and download_file_async returns False on a timeout, so an
  4888. # exhausted transfer arrives here rather than as an
  4889. # exception (#3063).
  4890. ftp_transfer_failed = True
  4891. except FileNotOnPrinterError:
  4892. # 550 — file isn't at this path. Advance to next candidate
  4893. # without burning the retry budget.
  4894. logger.debug("3MF not at %s (550), trying next path", remote_path)
  4895. except Exception as e:
  4896. ftp_transfer_failed = True
  4897. logger.debug("FTP download failed for %s: %s", remote_path, e)
  4898. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  4899. break
  4900. # If still not found, try listing directories to find matching file
  4901. # Different printer models use different directory structures. Skipped
  4902. # when the printer's FTPS handshake is failing — the directory walk is
  4903. # five more connections that cannot get further than the download did.
  4904. if (
  4905. not downloaded_filename
  4906. and storage.reachable
  4907. and (filename or subtask_name)
  4908. and not ftps_handshake_blocked(printer.ip_address)
  4909. ):
  4910. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  4911. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  4912. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  4913. # Every folder is listed before one file is picked, so a file named
  4914. # for the print in a later folder wins over one that merely
  4915. # contains the name in an earlier folder.
  4916. listed_paths: list[str] = []
  4917. for search_dir in search_dirs:
  4918. try:
  4919. dir_files = await list_files_async(
  4920. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  4921. )
  4922. except Exception as e:
  4923. logger.debug("Failed to list %s: %s", search_dir, e)
  4924. continue
  4925. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  4926. if threemf_files:
  4927. logger.info(
  4928. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  4929. )
  4930. listed_paths += [
  4931. posixpath.join(search_dir, f.get("name", "")) for f in dir_files if not f.get("is_directory")
  4932. ]
  4933. for remote_full_path in _3mf_files_for_print(listed_paths, search_term):
  4934. fname = posixpath.basename(remote_full_path)
  4935. logger.info("Found matching file: %s", remote_full_path)
  4936. temp_path = app_settings.archive_dir / "temp" / fname
  4937. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4938. try:
  4939. if ftp_retry_enabled:
  4940. downloaded = await with_ftp_retry(
  4941. download_file_async,
  4942. printer.ip_address,
  4943. printer.access_code,
  4944. remote_full_path,
  4945. temp_path,
  4946. timeout=ftp_timeout,
  4947. socket_timeout=ftp_timeout,
  4948. printer_model=printer.model,
  4949. max_retries=ftp_retry_count,
  4950. retry_delay=ftp_retry_delay,
  4951. operation_name=f"Download 3MF from {remote_full_path}",
  4952. cooloff_ip=printer.ip_address,
  4953. )
  4954. else:
  4955. downloaded = await download_file_async(
  4956. printer.ip_address,
  4957. printer.access_code,
  4958. remote_full_path,
  4959. temp_path,
  4960. timeout=ftp_timeout,
  4961. socket_timeout=ftp_timeout,
  4962. printer_model=printer.model,
  4963. )
  4964. except Exception as e:
  4965. logger.debug("Failed to download %s: %s", remote_full_path, e)
  4966. continue
  4967. if downloaded:
  4968. downloaded_filename = fname
  4969. logger.info("Found and downloaded: %s", remote_full_path)
  4970. cache_3mf_download(printer_id, fname, temp_path)
  4971. break
  4972. # The listing named the file, so it is on the card;
  4973. # only the transfer failed (#3063).
  4974. ftp_transfer_failed = True
  4975. # Validate the downloaded 3MF actually matches the plate that's running
  4976. # (#1204): subtask_name lags across consecutive plates of the same model,
  4977. # so the first FTP candidate (built from subtask_name) can land on the
  4978. # previous plate's still-resident upload. Cross-check the slice_info
  4979. # plate index against the plate parsed from gcode_file (always fresh —
  4980. # it's the field whose change triggered this callback).
  4981. if downloaded_filename and temp_path:
  4982. expected_plate = parse_plate_id(filename)
  4983. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  4984. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  4985. logger.warning(
  4986. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  4987. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  4988. downloaded_filename,
  4989. actual_plate,
  4990. expected_plate,
  4991. subtask_name,
  4992. )
  4993. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  4994. retry_succeeded = False
  4995. if corrected_subtask and corrected_subtask != subtask_name:
  4996. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  4997. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  4998. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  4999. for remote_path in (
  5000. f"/{try_filename}",
  5001. f"/cache/{try_filename}",
  5002. f"/model/{try_filename}",
  5003. f"/data/{try_filename}",
  5004. f"/data/Metadata/{try_filename}",
  5005. ):
  5006. try:
  5007. if ftp_retry_enabled:
  5008. downloaded = await with_ftp_retry(
  5009. download_file_async,
  5010. printer.ip_address,
  5011. printer.access_code,
  5012. remote_path,
  5013. retry_temp_path,
  5014. timeout=ftp_timeout,
  5015. socket_timeout=ftp_timeout,
  5016. printer_model=printer.model,
  5017. max_retries=ftp_retry_count,
  5018. retry_delay=ftp_retry_delay,
  5019. operation_name=f"Re-download 3MF from {remote_path}",
  5020. cooloff_ip=printer.ip_address,
  5021. non_retry_exceptions=(FileNotOnPrinterError,),
  5022. )
  5023. else:
  5024. downloaded = await download_file_async(
  5025. printer.ip_address,
  5026. printer.access_code,
  5027. remote_path,
  5028. retry_temp_path,
  5029. timeout=ftp_timeout,
  5030. socket_timeout=ftp_timeout,
  5031. printer_model=printer.model,
  5032. )
  5033. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  5034. logger.info(
  5035. "[CALLBACK] Re-download succeeded with corrected name %s "
  5036. "(plate %s) — replacing wrong file",
  5037. try_filename,
  5038. expected_plate,
  5039. )
  5040. try:
  5041. temp_path.unlink(missing_ok=True)
  5042. except OSError:
  5043. pass
  5044. temp_path = retry_temp_path
  5045. downloaded_filename = try_filename
  5046. subtask_name = corrected_subtask
  5047. cache_3mf_download(printer_id, try_filename, temp_path)
  5048. retry_succeeded = True
  5049. break
  5050. elif downloaded:
  5051. # Wrong plate again — discard and keep trying
  5052. try:
  5053. retry_temp_path.unlink(missing_ok=True)
  5054. except OSError:
  5055. pass
  5056. except FileNotOnPrinterError:
  5057. continue
  5058. except Exception as e:
  5059. logger.debug("Re-download failed for %s: %s", remote_path, e)
  5060. if retry_succeeded:
  5061. break
  5062. # If the retry didn't find a matching file, drop the wrong 3MF
  5063. # so the no-3MF fallback below creates an archive whose name
  5064. # at least reflects the right plate.
  5065. if not retry_succeeded:
  5066. logger.warning(
  5067. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  5068. expected_plate,
  5069. )
  5070. try:
  5071. temp_path.unlink(missing_ok=True)
  5072. except OSError:
  5073. pass
  5074. temp_path = None
  5075. downloaded_filename = None
  5076. # Whatever the sweep's transport did earlier, it is not why
  5077. # this archive ends up empty: a 3MF downloaded fine, it was
  5078. # just the wrong plate. Retrying would re-fetch that same
  5079. # contradicted file under the same stale names and hand it
  5080. # to _recover_fallback_archive, which checks that a
  5081. # candidate is a readable 3MF but not which plate it is --
  5082. # so the row would be filled in with another plate's
  5083. # filament and cost, the exact swap #2957 removed (#3063).
  5084. ftp_transfer_failed = False
  5085. # Disown the name for *lookups*: it has just been shown to
  5086. # fetch another plate's 3MF, and it keys `_active_prints`
  5087. # below, where the cover endpoint's own download of that
  5088. # same name would find this archive and fill it in with the
  5089. # file we are discarding here.
  5090. #
  5091. # Keep it for the *title*, which is a separate question.
  5092. # ``swap_plate_suffix`` returns None both for a name that
  5093. # carries no "- Plate N" / "_plate_N" suffix and for no
  5094. # name at all, and those are not the same situation: a name
  5095. # without a suffix holds no stale plate number to be wrong
  5096. # about. Blanking both uses at once dropped the project
  5097. # name too, and the row fell through to the gcode_file path
  5098. # titled "plate_1" though the real name was in hand.
  5099. # #1204's own premise is consecutive plates *of the same
  5100. # model*, so the project part is right either way (#3126).
  5101. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  5102. subtask_name = corrected_subtask or ""
  5103. # Deleted while the 3MF was being fetched (that can take minutes): no
  5104. # archive, timelapse or tracking for a printer that will never report
  5105. # the print's end. forget_printer again: the download registered its
  5106. # 3MF cache entry after the delete cleared the id. (A delete committing
  5107. # while the archive is written is caught after its commit.)
  5108. if await _printer_gone(db, printer_id):
  5109. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  5110. await forget_printer(printer_id)
  5111. return
  5112. if not downloaded_filename or not temp_path:
  5113. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  5114. # Create a fallback archive without 3MF data so the print is still tracked
  5115. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  5116. try:
  5117. from backend.app.models.archive import PrintArchive
  5118. # Why the card is empty. The two temporary causes outrank the
  5119. # storage verdict because they say the sweep never got a fair
  5120. # answer: a cool-off skipped it at the transport, and a failed
  5121. # transfer reached the printer but never finished. Either way
  5122. # the file is still on the card, so reporting where the printer
  5123. # files its jobs would describe a setting that is not the
  5124. # problem (#2957, #3063).
  5125. if blocked_by_ftps_cooloff:
  5126. no_3mf_reason = REASON_FTPS_COOLOFF
  5127. elif storage.reachable and ftp_transfer_failed:
  5128. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5129. else:
  5130. no_3mf_reason = storage.reason
  5131. # Derive print name from subtask_name or filename. The
  5132. # plate guard's disowned name comes second: it is a real name
  5133. # for a real print, and only the gcode_file path is left
  5134. # otherwise -- which titles the row "plate_1" (#3126).
  5135. print_name = subtask_name or display_name_after_plate_reject or filename
  5136. if print_name:
  5137. # Clean up the name (remove extensions, path parts)
  5138. print_name = print_name.split("/")[-1]
  5139. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5140. else:
  5141. print_name = "Unknown Print"
  5142. # Recover estimated print time from MQTT (best-effort for notifications)
  5143. fallback_print_time = None
  5144. mqtt_remaining = data.get("remaining_time")
  5145. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5146. fallback_print_time = int(mqtt_remaining)
  5147. if fallback_print_time is None:
  5148. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5149. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5150. fallback_print_time = int(mc_remaining * 60)
  5151. # Best-effort filament metadata from MQTT — see
  5152. # _extract_filament_data_from_mqtt. Without this the fallback
  5153. # archive's filament fields stayed NULL even though the AMS
  5154. # state at print start was sitting right there in `data`.
  5155. # The slicer's ams_mapping (when present) narrows the result
  5156. # to slots actually used by the print (#1533).
  5157. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  5158. # Create minimal archive entry
  5159. fallback_archive = PrintArchive(
  5160. printer_id=printer_id,
  5161. filename=filename or f"{print_name}.3mf",
  5162. file_path="", # Empty - no 3MF file available
  5163. file_size=0,
  5164. print_name=print_name,
  5165. print_time_seconds=fallback_print_time,
  5166. status="printing",
  5167. started_at=datetime.now(timezone.utc),
  5168. subtask_id=subtask_id,
  5169. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5170. filament_type=mqtt_filament_meta.get("filament_type"),
  5171. filament_color=mqtt_filament_meta.get("filament_color"),
  5172. extra_data={
  5173. "no_3mf_available": True,
  5174. # Why the card is empty, when we know -- see above. The
  5175. # banner reads this to stop telling H2/P2 owners to
  5176. # switch on a setting that is already on and would not
  5177. # have helped (#2780).
  5178. "no_3mf_reason": no_3mf_reason,
  5179. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5180. "_print_data": data,
  5181. },
  5182. )
  5183. db.add(fallback_archive)
  5184. try:
  5185. await db.commit()
  5186. except IntegrityError:
  5187. # Not "Failed to create fallback archive" below, and no
  5188. # start notification for a printer that is gone.
  5189. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5190. return
  5191. raise
  5192. await db.refresh(fallback_archive)
  5193. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5194. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5195. return
  5196. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5197. # Track as active print
  5198. _bind_active_print(printer_id, fallback_archive.id, fallback_archive.filename, filename, subtask_name)
  5199. # Record starting energy if smart plug available (#941: persisted column)
  5200. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5201. # Send WebSocket notification
  5202. await ws_manager.send_archive_created(
  5203. {
  5204. "id": fallback_archive.id,
  5205. "printer_id": fallback_archive.printer_id,
  5206. "filename": fallback_archive.filename,
  5207. "print_name": fallback_archive.print_name,
  5208. "status": fallback_archive.status,
  5209. }
  5210. )
  5211. # MQTT relay - publish archive created
  5212. try:
  5213. await mqtt_relay.on_archive_created(
  5214. archive_id=fallback_archive.id,
  5215. print_name=fallback_archive.print_name,
  5216. printer_name=printer.name,
  5217. status=fallback_archive.status,
  5218. )
  5219. except Exception:
  5220. pass # Don't fail if MQTT fails
  5221. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5222. try:
  5223. await _store_spoolman_print_data(
  5224. printer_id,
  5225. fallback_archive.id,
  5226. fallback_archive.file_path,
  5227. db,
  5228. printer_manager,
  5229. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  5230. plate_id=_get_start_plate_id(fallback_archive.id),
  5231. )
  5232. except Exception as e:
  5233. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5234. # Both temporary give-ups are worth coming back for, and for
  5235. # the same reason: the file is on the printer and the last look
  5236. # failed at the transport rather than finding nothing. One waits
  5237. # out the handshake block (#2957), the other waits for the
  5238. # printer to stop being busy (#3063). Deliberately not scheduled
  5239. # for a storage verdict: a file on internal eMMC will not appear
  5240. # at any FTPS path however long we wait, and retrying it is
  5241. # exactly the sweep #2780 removed.
  5242. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5243. # `possible_names`, not the raw MQTT strings: it is the exact
  5244. # list this flow just tried, already stripped of any path
  5245. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5246. # some firmware) and deduped.
  5247. _schedule_fallback_3mf_retry(
  5248. printer_id=printer_id,
  5249. archive_id=fallback_archive.id,
  5250. filenames=list(possible_names),
  5251. reason=no_3mf_reason,
  5252. )
  5253. # Send notification without archive data (file not found)
  5254. if not notification_sent:
  5255. await _send_print_start_notification(printer_id, data, logger=logger)
  5256. # The same baseline the other two on_print_start branches take
  5257. # (#2704), and last for the same reason they are: it lists the
  5258. # printer's timelapse directory, so a slow card must not delay
  5259. # the _active_prints registration, the energy reading, the
  5260. # archive-created event or the start notification above it.
  5261. #
  5262. # This branch never took one, so every no-3MF archive reached
  5263. # completion with no baseline in memory and none on the row, and
  5264. # the completion scan fell into its "snapshot now" fallback --
  5265. # which runs after the printer has written the video, so the new
  5266. # file landed inside the baseline and no diff ever matched
  5267. # (#2957 follow-up).
  5268. #
  5269. # Skipped when the FTPS cool-off is what produced this fallback:
  5270. # the listing needs the same connection that just failed, so it
  5271. # could only record that the card was unreadable. The scan
  5272. # handles that case by refusing to choose between candidates.
  5273. if not blocked_by_ftps_cooloff:
  5274. await _capture_timelapse_baseline_at_start(
  5275. printer, printer_id, logger, archive_id=fallback_archive.id
  5276. )
  5277. await _forget_if_printer_gone(printer_id)
  5278. return
  5279. except Exception as e:
  5280. logger.error("Failed to create fallback archive: %s", e)
  5281. # Send notification without archive data (file not found)
  5282. if not notification_sent:
  5283. await _send_print_start_notification(printer_id, data, logger=logger)
  5284. return
  5285. try:
  5286. # Archive the file with status "printing"
  5287. service = ArchiveService(db)
  5288. try:
  5289. archive = await service.archive_print(
  5290. printer_id=printer_id,
  5291. source_file=temp_path,
  5292. print_data={**data, "status": "printing"},
  5293. subtask_id=subtask_id,
  5294. )
  5295. except IntegrityError:
  5296. # archive_print removed the folder it had copied the 3MF into.
  5297. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5298. return
  5299. raise
  5300. if archive:
  5301. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5302. # Set on the row rather than passed to archive_print, which also
  5303. # serves the queue dispatcher — there the queue item decides.
  5304. # Guarded because this branch has no ``except``: an unhandled
  5305. # write error would take the _active_prints registration, the
  5306. # start notification, the energy reading and the timelapse
  5307. # baseline below it with it, and a missing prompt is by far the
  5308. # cheaper failure.
  5309. archive_id = archive.id
  5310. try:
  5311. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5312. archive.confirm_requested = True
  5313. await db.commit()
  5314. except Exception as e:
  5315. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5316. # The rollback expires every loaded object, and on an async
  5317. # session reading one afterwards raises instead of
  5318. # reloading, so the two this branch goes on to use are
  5319. # fetched again. The archive itself was committed by
  5320. # archive_print; only the flag is lost.
  5321. try:
  5322. await db.rollback()
  5323. archive = await db.get(PrintArchive, archive_id)
  5324. printer = await db.get(Printer, printer_id)
  5325. except Exception as reload_error:
  5326. logger.warning(
  5327. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5328. )
  5329. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5330. return
  5331. # Track this active print (use both original filename and downloaded filename)
  5332. _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
  5333. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5334. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5335. # Record starting energy from smart plug if available (#941: persisted column)
  5336. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5337. await ws_manager.send_archive_created(
  5338. {
  5339. "id": archive.id,
  5340. "printer_id": archive.printer_id,
  5341. "filename": archive.filename,
  5342. "print_name": archive.print_name,
  5343. "status": archive.status,
  5344. }
  5345. )
  5346. # MQTT relay - publish archive created
  5347. try:
  5348. await mqtt_relay.on_archive_created(
  5349. archive_id=archive.id,
  5350. print_name=archive.print_name,
  5351. printer_name=printer.name,
  5352. status=archive.status,
  5353. )
  5354. except Exception:
  5355. pass # Don't fail if MQTT fails
  5356. # Send notification with archive data (new archive created)
  5357. if not notification_sent:
  5358. archive_data = {
  5359. "print_time_seconds": archive.print_time_seconds,
  5360. "created_by_id": archive.created_by_id,
  5361. }
  5362. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5363. # Extract printable objects for skip object functionality
  5364. try:
  5365. from backend.app.services.archive import extract_printable_objects_from_3mf
  5366. client = printer_manager.get_client(printer_id)
  5367. if client:
  5368. with open(temp_path, "rb") as f:
  5369. threemf_data = f.read()
  5370. # Extract with positions for UI overlay, scoped to the
  5371. # plate that is printing — an all-plates 3MF carries
  5372. # every plate's objects (#2522).
  5373. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5374. threemf_data,
  5375. plate_number=resolve_plate_id(client.state),
  5376. include_positions=True,
  5377. )
  5378. if printable_objects:
  5379. # Store objects in printer state
  5380. client.state.printable_objects = printable_objects
  5381. client.state.printable_objects_bbox_all = bbox_all
  5382. client.state.skipped_objects = [] # Reset skipped objects for new print
  5383. logger.info(
  5384. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5385. )
  5386. except Exception as e:
  5387. logger.debug("Failed to extract printable objects: %s", e)
  5388. # Store Spoolman tracking data for per-filament usage reporting
  5389. try:
  5390. await _store_spoolman_print_data(
  5391. printer_id,
  5392. archive.id,
  5393. archive.file_path,
  5394. db,
  5395. printer_manager,
  5396. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5397. plate_id=_get_start_plate_id(archive.id),
  5398. )
  5399. except Exception as e:
  5400. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5401. # Price the print from its spools now rather than only at completion (#3261)
  5402. _schedule_archive_cost_estimate(
  5403. printer_id,
  5404. archive.id,
  5405. printer_manager,
  5406. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5407. plate_id=_get_start_plate_id(archive.id),
  5408. session_factory=async_session,
  5409. )
  5410. # Capture timelapse file baseline for snapshot-diff on completion
  5411. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5412. await _forget_if_printer_gone(printer_id)
  5413. finally:
  5414. # Keep temp_path around until print completes so the cover endpoint
  5415. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5416. # the file. If the cache entry was evicted early (file vanished),
  5417. # clean up any stragglers here to avoid leaking disk on retries.
  5418. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5419. if temp_path and temp_path.exists() and cached_now != temp_path:
  5420. temp_path.unlink()
  5421. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5422. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5423. # tests can shrink them without waiting out real delays.
  5424. #
  5425. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  5426. # looking. Across 247 support bundles the attempt that found the video was #1
  5427. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  5428. # decaying one, which is the signature of a budget that expires while files are
  5429. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  5430. # prints make big videos and the printer writes them after the print ends, so
  5431. # the poll now runs for minutes and costs one FTP LIST per round.
  5432. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  5433. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  5434. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  5435. def _timelapse_scan_max_attempts() -> int:
  5436. """Round cap for the poll, derived from the wall-clock budget.
  5437. The deadline alone is not a sufficient bound: it assumes each round really
  5438. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5439. and an FTP list that fails immediately would otherwise spin against the
  5440. printer at full speed for the whole window. Whichever bound is reached
  5441. first ends the poll.
  5442. """
  5443. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5444. # A zero interval makes the wall-clock budget meaningless; fall back to
  5445. # the round count the production interval would have given.
  5446. return 32
  5447. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5448. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  5449. """Video filenames already attached to some other archive of this printer.
  5450. Used to disambiguate when more than one file is new since the baseline —
  5451. which happens when a previous print's video landed after this print's
  5452. baseline was taken. Ordering the candidates would be the obvious fix and is
  5453. the wrong one: it can only be done on mtime or on the filename timestamp,
  5454. both of which come from the printer's own clock, and a LAN-only printer
  5455. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  5456. ``attach_timelapse`` saves the video into the archive directory under the
  5457. printer's original filename, and the later MP4 conversion keeps the stem,
  5458. so the stem of ``timelapse_path`` recovers what was claimed.
  5459. """
  5460. from backend.app.models.archive import PrintArchive
  5461. rows = await db.execute(
  5462. select(PrintArchive.timelapse_path).where(
  5463. PrintArchive.printer_id == printer_id,
  5464. PrintArchive.id != exclude_archive_id,
  5465. PrintArchive.timelapse_path.is_not(None),
  5466. )
  5467. )
  5468. return {Path(p).stem for p in rows.scalars().all() if p}
  5469. def _timelapse_listing_is_trustworthy(printer) -> bool:
  5470. """Whether an *empty* timelapse listing for *printer* can be believed.
  5471. ``list_files_async`` answers ``[]`` when its connect fails rather than
  5472. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  5473. from one holding no videos. Everywhere that only wants to know "is there a
  5474. video yet" the difference does not matter — both mean "not yet, retry".
  5475. It matters where an empty listing is recorded as a *baseline*. Recording
  5476. "the card held nothing" for a card that was never read means every video on
  5477. it counts as new once the cool-off expires, and the completion scan then
  5478. attaches a stale video to this print and deletes it from the printer
  5479. (#2957 follow-up). Those two callers ask this first.
  5480. """
  5481. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  5482. ip_address = getattr(printer, "ip_address", None)
  5483. if not ip_address:
  5484. return True
  5485. return not ftps_handshake_blocked(ip_address)
  5486. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5487. """List video files from printer's timelapse directory.
  5488. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5489. Returns (video_files, found_path) where video_files is a list of file dicts
  5490. and found_path is the directory where they were found, or ([], None).
  5491. An empty return does not distinguish "no videos" from "could not read the
  5492. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  5493. baseline callers consult before believing one.
  5494. """
  5495. from backend.app.services.bambu_ftp import list_files_async
  5496. logger = logging.getLogger(__name__)
  5497. # No card in the slot means no /timelapse to walk — four connections that
  5498. # can only fail, on a path whose failures are swallowed and so would go on
  5499. # costing time silently forever (#2780).
  5500. #
  5501. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5502. # inside the loop's own try/except, so a caller that passed something
  5503. # unexpected used to get an empty listing rather than an exception. Keep
  5504. # that, instead of making this gate the first thing that can raise here.
  5505. printer_id = getattr(printer, "id", None)
  5506. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5507. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5508. return [], None
  5509. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  5510. try:
  5511. found_files = await list_files_async(
  5512. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5513. )
  5514. if found_files:
  5515. video_files = [
  5516. f
  5517. for f in found_files
  5518. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5519. ]
  5520. if video_files:
  5521. return video_files, timelapse_path
  5522. except Exception as e:
  5523. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5524. continue
  5525. return [], None
  5526. async def _capture_timelapse_baseline_at_start(
  5527. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5528. ) -> None:
  5529. """Snapshot the printer's timelapse directory at print start so the
  5530. completion-time scan can pick the new file by set-difference.
  5531. Must be called from every on_print_start path that proceeds to a real
  5532. print — both the new-archive branch and the expected-archive branch (which
  5533. queue / VP-dispatched prints take). Without a baseline,
  5534. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5535. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5536. so the new file ends up in the "baseline" set and no diff ever matches.
  5537. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  5538. unreliable — the snapshot-diff approach sidesteps that entirely.
  5539. When ``archive_id`` is known the baseline is also written to the archive
  5540. row, so it survives a restart and the manual "Scan for Timelapse" button
  5541. can run the same diff instead of falling back to clock-based matching
  5542. (#2704). Only baselines taken at print start are persisted — one taken at
  5543. completion already contains the new video and would poison a later scan.
  5544. """
  5545. names: set[str] | None = None
  5546. try:
  5547. if not _timelapse_listing_is_trustworthy(printer):
  5548. # Recorded anyway, deliberately. An empty baseline taken off a card
  5549. # we could not read is not authoritative, but it is still the right
  5550. # *default*: Bambuddy deletes each video from the printer once it is
  5551. # attached, so the usual card holds exactly one video at completion
  5552. # and an empty baseline resolves it correctly. Persisting NULL
  5553. # instead would send completion to take its own snapshot, by which
  5554. # point this print's video is on the card and would be swallowed by
  5555. # it. The ambiguity is handled where it actually bites — see
  5556. # ``require_unambiguous`` in the scan (#2957 follow-up).
  5557. logger.warning(
  5558. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  5559. "handshake cool-off, so the card could not be read — treating it as empty",
  5560. printer_id,
  5561. )
  5562. baseline_files, _ = await _list_timelapse_videos(printer)
  5563. names = {f.get("name", "") for f in baseline_files}
  5564. _timelapse_baselines[printer_id] = names
  5565. logger.info(
  5566. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  5567. len(names),
  5568. printer_id,
  5569. )
  5570. except Exception as e:
  5571. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  5572. if archive_id is None:
  5573. return
  5574. try:
  5575. async with async_session() as db:
  5576. from backend.app.models.archive import PrintArchive
  5577. archive = await db.get(PrintArchive, archive_id)
  5578. if archive is not None:
  5579. # Written even when the listing failed, and then as NULL. A
  5580. # reprint reuses the archive row, so leaving the previous run's
  5581. # baseline in place would have the scan diff this print against
  5582. # the state of the printer before the *last* one — and a stale
  5583. # baseline reads as authoritative, where NULL correctly falls
  5584. # back to a fresh snapshot.
  5585. archive.timelapse_baseline = sorted(names) if names is not None else None
  5586. await db.commit()
  5587. except Exception as e:
  5588. # In-memory baseline still covers the normal completion path.
  5589. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  5590. async def _scan_for_timelapse_with_retries(
  5591. archive_id: int, baseline_names: set[str] | None = None, *, plate_id: int | None = None
  5592. ):
  5593. """Poll the printer for this print's timelapse and attach it.
  5594. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  5595. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  5596. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  5597. (#2704). Comparing the current listing against the set of filenames that
  5598. existed when the print started needs no clock at all, because the printer
  5599. writes the video only once the print has ended.
  5600. Baseline precedence: the caller's in-memory set, then the one persisted on
  5601. the archive at print start, then a snapshot taken now. The last of those is
  5602. a poor substitute — by completion the new video may already be on the card,
  5603. in which case it lands in the "baseline" and no diff can ever match — but it
  5604. is all that is available for a print that began before Bambuddy started.
  5605. On success the video is deleted from the printer, which keeps ``/timelapse``
  5606. down to the unclaimed files and makes the next diff unambiguous.
  5607. """
  5608. logger = logging.getLogger(__name__)
  5609. # Cleared when the baseline had to be taken off a card we could not read, so
  5610. # the attach step refuses to choose between several candidates (#2957).
  5611. baseline_trusted = True
  5612. # --- Phase 1: establish the baseline -------------------------------------
  5613. try:
  5614. async with async_session() as db:
  5615. from backend.app.models.printer import Printer
  5616. service = ArchiveService(db)
  5617. archive = await service.get_archive(archive_id)
  5618. if not archive:
  5619. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  5620. return
  5621. if archive.timelapse_path:
  5622. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  5623. return
  5624. if not archive.printer_id:
  5625. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  5626. return
  5627. # The run this scan is for. The archive row passes to a newer run
  5628. # when it prints again (the next plate, a reprint), and that run's
  5629. # video is its own.
  5630. run_started_at = archive.started_at
  5631. if baseline_names is not None:
  5632. logger.info(
  5633. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  5634. len(baseline_names),
  5635. archive_id,
  5636. )
  5637. elif archive.timelapse_baseline is not None:
  5638. # Persisted at print start — survives a restart mid-print.
  5639. baseline_names = set(archive.timelapse_baseline)
  5640. logger.info(
  5641. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  5642. len(baseline_names),
  5643. archive_id,
  5644. )
  5645. else:
  5646. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5647. printer = result.scalar_one_or_none()
  5648. if not printer:
  5649. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  5650. return
  5651. if not _timelapse_listing_is_trustworthy(printer):
  5652. # The card is unreadable at the one moment a baseline has to
  5653. # be taken, so the empty listing below means "we never
  5654. # looked", not "these are all new". Carry on with it anyway
  5655. # — the usual card holds exactly one video, which resolves
  5656. # correctly — but stop the poll from *choosing* between
  5657. # several, which is how a stale video got attached to this
  5658. # print and then deleted off the printer (#2957 follow-up).
  5659. baseline_trusted = False
  5660. logger.warning(
  5661. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  5662. "handshake cool-off. A single new video still resolves; several will not be "
  5663. "guessed between — use Scan for Timelapse to pick one by hand",
  5664. archive_id,
  5665. archive.printer_id,
  5666. )
  5667. baseline_files, _ = await _list_timelapse_videos(printer)
  5668. baseline_names = {f.get("name", "") for f in baseline_files}
  5669. logger.info(
  5670. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  5671. len(baseline_names),
  5672. archive_id,
  5673. )
  5674. except Exception as e:
  5675. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  5676. return
  5677. # --- Phase 2: poll for a file that was not there when the print began -----
  5678. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  5679. max_attempts = _timelapse_scan_max_attempts()
  5680. seen_names: set[str] = set()
  5681. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  5682. attempt = 0
  5683. while True:
  5684. await asyncio.sleep(delay)
  5685. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  5686. attempt += 1
  5687. try:
  5688. from backend.app.models.printer import Printer
  5689. # Read phase: fetch archive + printer in a short session and release
  5690. # the pooled connection BEFORE the FTP list/download below. Holding it
  5691. # across the FTP round-trips left one connection idle-in-transaction per
  5692. # in-flight scan (issue #2572).
  5693. async with async_session() as db:
  5694. service = ArchiveService(db)
  5695. archive = await service.get_archive(archive_id)
  5696. if not archive:
  5697. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  5698. return
  5699. if archive.timelapse_path:
  5700. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  5701. return
  5702. if archive.started_at != run_started_at:
  5703. logger.info(
  5704. "[TIMELAPSE] Archive %s is printing again, stopping the previous run's poll", archive_id
  5705. )
  5706. return
  5707. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5708. printer = result.scalar_one_or_none()
  5709. if not printer:
  5710. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  5711. return
  5712. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  5713. # I/O phase (no DB connection held): FTP list + download.
  5714. video_files, found_path = await _list_timelapse_videos(printer)
  5715. # The poll can run for dozens of rounds, so only narrate a round
  5716. # that saw something change. Repeating the whole listing every 30 s
  5717. # would bury the one interesting line in the support bundle.
  5718. names_now = {f.get("name", "") for f in video_files}
  5719. changed = attempt == 1 or names_now != seen_names
  5720. seen_names = names_now
  5721. speak = logger.info if changed else logger.debug
  5722. if video_files:
  5723. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  5724. if changed:
  5725. for f in video_files[:5]:
  5726. logger.info("[TIMELAPSE] - %s", f.get("name"))
  5727. attached = await _attach_first_unclaimed_timelapse(
  5728. archive_id,
  5729. printer,
  5730. video_files,
  5731. baseline_names,
  5732. claimed,
  5733. attempt,
  5734. logger,
  5735. quiet=not changed,
  5736. require_unambiguous=not baseline_trusted,
  5737. plate_id=plate_id,
  5738. run_started_at=run_started_at,
  5739. )
  5740. if attached:
  5741. return
  5742. else:
  5743. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  5744. except Exception as e:
  5745. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  5746. if attempt >= max_attempts or time.monotonic() >= deadline:
  5747. break
  5748. # No name-match fallback: it compared the print name against the filename,
  5749. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  5750. # bundles it fired 159 times and matched zero times, so all it added was a
  5751. # misleading log line before giving up.
  5752. logger.warning(
  5753. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  5754. archive_id,
  5755. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  5756. )
  5757. async def _attach_layer_timelapse(
  5758. archive_id: int, timelapse_path: Path, plate_id: int | None, run_started_at: datetime | None
  5759. ) -> None:
  5760. """Attach the external camera's stitched timelapse to the archive.
  5761. The camera's video is the one the user set up in Bambuddy, so it wins
  5762. over the printer's own when both are on: it replaces the printer's video
  5763. (usually there first; stitching takes minutes) and that file is deleted,
  5764. leaving nothing in the archive folder unreferenced. ``run_started_at`` is
  5765. the run the frames were taken for: when the archive is printing again by
  5766. the time the stitch is done, the video is not the new run's and is
  5767. dropped. The stitched file is a temporary either way.
  5768. """
  5769. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  5770. logger = logging.getLogger(__name__)
  5771. try:
  5772. async with async_session() as db:
  5773. service = ArchiveService(db)
  5774. archive = await service.get_archive(archive_id)
  5775. if archive is None:
  5776. return
  5777. if archive.started_at != run_started_at:
  5778. logger.info(
  5779. "[LAYER-TL] Archive %s is printing again; dropping the previous run's layer timelapse", archive_id
  5780. )
  5781. return
  5782. replaced = archive.timelapse_path
  5783. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  5784. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  5785. if not await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=plate_id):
  5786. return
  5787. attached = archive.timelapse_path
  5788. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  5789. if replaced and replaced != attached:
  5790. try:
  5791. old = safe_join_under(app_settings.base_dir, replaced, http=False)
  5792. except PathTraversalError:
  5793. return
  5794. await asyncio.to_thread(old.unlink, missing_ok=True)
  5795. logger.info("[LAYER-TL] Replaced the printer's timelapse %s on archive %s", replaced, archive_id)
  5796. finally:
  5797. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  5798. # ``run_started_at`` not given: attach whichever run the archive is on.
  5799. _ANY_RUN = object()
  5800. async def _attach_first_unclaimed_timelapse(
  5801. archive_id: int,
  5802. printer,
  5803. video_files: list[dict],
  5804. baseline_names: set[str],
  5805. claimed: set[str],
  5806. attempt: int,
  5807. logger: logging.Logger,
  5808. *,
  5809. quiet: bool = False,
  5810. require_unambiguous: bool = False,
  5811. plate_id: int | None = None,
  5812. run_started_at: datetime | None | object = _ANY_RUN,
  5813. ) -> bool:
  5814. """Download and attach the one video that belongs to this print.
  5815. A candidate is any file absent from the print-start baseline. More than one
  5816. can qualify when a previous print's video landed late, after this print's
  5817. baseline was taken — those are filtered out by name, because they are
  5818. already attached to another archive. Sorting the candidates instead would
  5819. mean sorting on mtime or on the filename timestamp, both of which come from
  5820. the printer's unsynced clock.
  5821. Returns True once a video is attached. The printer's copy is deleted only
  5822. after the attach succeeds on bytes whose length matched the listing.
  5823. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  5824. already seen this exact listing — the poll runs for many rounds and only the
  5825. rounds where something changed are worth an INFO line.
  5826. """
  5827. from backend.app.services.bambu_ftp import (
  5828. DownloadDeadlineExceeded,
  5829. delete_archived_timelapse,
  5830. download_file_bytes_async,
  5831. remote_file_settled,
  5832. )
  5833. speak = logger.debug if quiet else logger.info
  5834. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  5835. if not new_files:
  5836. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  5837. return False
  5838. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  5839. if not candidates:
  5840. speak(
  5841. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  5842. attempt,
  5843. len(new_files),
  5844. )
  5845. return False
  5846. if len(candidates) > 1:
  5847. if require_unambiguous:
  5848. # The baseline is not evidence -- it was taken off a card that could
  5849. # not be read -- so "new since the baseline" does not narrow these
  5850. # down at all. Taking the first would attach an arbitrary video to
  5851. # this print and then delete it from the printer.
  5852. logger.warning(
  5853. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  5854. "leaving all of them on the printer for manual selection",
  5855. attempt,
  5856. len(candidates),
  5857. ", ".join(str(f.get("name")) for f in candidates),
  5858. )
  5859. return False
  5860. logger.warning(
  5861. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  5862. "the rest stay on the printer for manual selection",
  5863. attempt,
  5864. len(candidates),
  5865. ", ".join(str(f.get("name")) for f in candidates),
  5866. )
  5867. target = candidates[0]
  5868. file_name = str(target.get("name") or "") # every listed entry has one
  5869. remote_path = target.get("path") or f"/timelapse/{file_name}"
  5870. logger.info(
  5871. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  5872. attempt,
  5873. file_name,
  5874. archive_id,
  5875. )
  5876. # The listing always carries a size (`list_files` skips entries it can't
  5877. # parse), but read it explicitly: the delete below is destructive and must
  5878. # depend on a size we actually had, not on one we hoped was there.
  5879. expected_size = target.get("size")
  5880. try:
  5881. timelapse_data = await download_file_bytes_async(
  5882. printer.ip_address,
  5883. printer.access_code,
  5884. remote_path,
  5885. printer_model=printer.model,
  5886. expected_size=expected_size,
  5887. )
  5888. except DownloadDeadlineExceeded:
  5889. # Too slow for its size this round; the printer keeps its copy.
  5890. timelapse_data = None
  5891. if not timelapse_data:
  5892. # Short or failed transfer. The printer keeps its copy, so the next
  5893. # round can try again — which is exactly why the delete below is
  5894. # gated on a verified download.
  5895. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  5896. return False
  5897. # The length check above proves we got what the listing said, not that the
  5898. # printer had finished writing. A video still being written can be listed
  5899. # short, served short, and pass — so confirm it has stopped growing before
  5900. # committing to it and deleting the original (#2704).
  5901. if not await remote_file_settled(
  5902. printer.ip_address,
  5903. printer.access_code,
  5904. remote_path,
  5905. len(timelapse_data),
  5906. printer_model=printer.model,
  5907. ):
  5908. return False
  5909. # Write phase: attach in a fresh short-lived session. The download took a
  5910. # while: by now the archive may have its video, or be printing again for a
  5911. # newer run, whose video this is not. Then nothing is attached or deleted,
  5912. # and the poll ends (True).
  5913. async with async_session() as db:
  5914. service = ArchiveService(db)
  5915. if run_started_at is not _ANY_RUN:
  5916. current = await service.get_archive(archive_id)
  5917. if current is None or current.timelapse_path or current.started_at != run_started_at:
  5918. logger.info(
  5919. "[TIMELAPSE] Archive %s moved on during the download (video attached or printing again); "
  5920. "%s stays on the printer",
  5921. archive_id,
  5922. file_name,
  5923. )
  5924. return True
  5925. success = await service.attach_timelapse(archive_id, timelapse_data, file_name, plate_id=plate_id)
  5926. if not success:
  5927. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  5928. return False
  5929. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  5930. await delete_archived_timelapse(
  5931. printer.ip_address,
  5932. printer.access_code,
  5933. remote_path,
  5934. verified=expected_size is not None,
  5935. printer_model=printer.model,
  5936. printer_name=printer.name,
  5937. )
  5938. return True
  5939. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  5940. # module-level so tests can monkeypatch them down to ~0 without timing out.
  5941. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  5942. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  5943. # How long the *background* upgrade keeps waiting after the notification has
  5944. # already gone out (#2704 follow-up). The short bound above exists so a slow
  5945. # printer can't hold up the print-complete notification; this one exists so the
  5946. # archive still ends up with the better frame afterwards.
  5947. #
  5948. # Measured across 261 attaches in the support bundles, the video lands a median
  5949. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  5950. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  5951. # was 546s. Every other model was inside 26s. The long budget is therefore
  5952. # almost entirely for P1-series users; on everything else the short wait already
  5953. # wins and this task never runs.
  5954. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  5955. async def _capture_finish_photo_from_timelapse(
  5956. archive_id: int,
  5957. archive_dir: Path,
  5958. timeout: float | None = None,
  5959. rotation: int = 0,
  5960. ) -> tuple[str | None, bool]:
  5961. """Wait for the per-print timelapse to land on the archive and extract its
  5962. last frame as the finish photo (#1397).
  5963. Bambu firmware stops timelapse recording after the toolhead parks but
  5964. before the bed-drop end-gcode runs, so the last frame frames the finished
  5965. print correctly. A live camera grab at gcode_state=FINISH captures the
  5966. bed already lowered.
  5967. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  5968. ``archive.timelapse_path`` when the file lands. This function polls for
  5969. that field.
  5970. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  5971. the wait ran out with no video on the archive yet — i.e. the video may
  5972. still be coming and a later attempt could succeed. It is False when the
  5973. video landed (whether or not extraction worked), because in that case
  5974. waiting longer changes nothing. The caller uses that to decide between
  5975. falling back permanently and scheduling a background upgrade.
  5976. ``rotation`` is the printer's camera_rotation, applied to the extracted
  5977. still (#2708) so this source agrees with every other finish-photo source.
  5978. The archived video itself is the printer's own file and is left alone —
  5979. rotating it would mean re-encoding it.
  5980. """
  5981. import uuid
  5982. from backend.app.models.archive import PrintArchive
  5983. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  5984. logger = logging.getLogger(__name__)
  5985. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  5986. deadline = asyncio.get_event_loop().time() + budget
  5987. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  5988. while True:
  5989. async with async_session() as db:
  5990. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5991. archive = result.scalar_one_or_none()
  5992. timelapse_relpath = archive.timelapse_path if archive else None
  5993. if timelapse_relpath:
  5994. video_path = app_settings.base_dir / timelapse_relpath
  5995. if video_path.exists() and video_path.stat().st_size > 0:
  5996. photos_dir = archive_dir / "photos"
  5997. photos_dir.mkdir(parents=True, exist_ok=True)
  5998. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5999. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6000. output_path = photos_dir / filename
  6001. if await extract_video_last_frame(video_path, output_path):
  6002. await apply_camera_rotation_to_file(output_path, rotation, logger)
  6003. logger.info(
  6004. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  6005. video_path.name,
  6006. archive_id,
  6007. )
  6008. return filename, False
  6009. logger.warning(
  6010. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  6011. video_path.name,
  6012. archive_id,
  6013. )
  6014. return None, False
  6015. if asyncio.get_event_loop().time() >= deadline:
  6016. logger.info(
  6017. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  6018. archive_id,
  6019. budget,
  6020. )
  6021. return None, True
  6022. await asyncio.sleep(poll_interval)
  6023. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  6024. """Add the timelapse's last frame to an archive after the fact (#2704).
  6025. The print-complete notification waits only ~60s for the video, because
  6026. holding a notification for minutes is worse than sending it with a live
  6027. camera grab. On a P1-series printer the video often lands well after that,
  6028. so the archive used to be stuck with the live grab — which is taken at
  6029. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  6030. the worse photo of the two.
  6031. This keeps waiting in the background and, when the video arrives, extracts
  6032. the frame and puts it *first* in the archive's photo list, so opening the
  6033. gallery shows it. The live grab is deliberately kept: the notification that
  6034. already went out links to that exact file, and deleting it would leave a
  6035. broken image in Discord or Telegram.
  6036. """
  6037. logger = logging.getLogger(__name__)
  6038. filename, _ = await _capture_finish_photo_from_timelapse(
  6039. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  6040. )
  6041. if not filename:
  6042. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  6043. return
  6044. try:
  6045. async with async_session() as db:
  6046. from backend.app.models.archive import PrintArchive
  6047. archive = await db.get(PrintArchive, archive_id)
  6048. if archive is None:
  6049. return
  6050. photos = list(archive.photos or [])
  6051. if filename in photos:
  6052. return
  6053. # Front of the list: PhotoGalleryModal opens at index 0.
  6054. archive.photos = [filename, *photos]
  6055. await db.commit()
  6056. except Exception as e:
  6057. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  6058. return
  6059. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  6060. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  6061. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  6062. """Put the filament-attribution context back after a restart mid-print.
  6063. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  6064. both die with the process. The print keeps running, so at completion the
  6065. tracker would fall back to whatever the printer reports *now* — and AMS
  6066. filament backup makes "now" the substitute tray, charging the whole print
  6067. to the spool that only finished it.
  6068. The persisted row is only trusted when its print name still matches what
  6069. the printer says it is running: a row left behind by a completion we never
  6070. saw must not attach itself to the next print.
  6071. """
  6072. try:
  6073. from backend.app.api.routes.settings import get_setting
  6074. from backend.app.services.usage_tracker import (
  6075. clear_persisted_session,
  6076. get_persisted_print_name,
  6077. restore_session,
  6078. )
  6079. persisted_name = await get_persisted_print_name(db, printer_id)
  6080. current_name = (state.subtask_name or "").strip()
  6081. if persisted_name and current_name and persisted_name.strip() != current_name:
  6082. logger.info(
  6083. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  6084. printer_id,
  6085. persisted_name,
  6086. current_name,
  6087. )
  6088. await clear_persisted_session(db, printer_id)
  6089. # Fall through to seeding: the print on the printer is real, it just
  6090. # isn't the one the row described.
  6091. persisted_log = None
  6092. else:
  6093. # Spoolman users get the tray-change log back but no in-memory
  6094. # session — see ``on_print_start`` on why that dict is load-bearing
  6095. # for the remain%-sync guard.
  6096. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6097. persisted_log = await restore_session(
  6098. db,
  6099. printer_id,
  6100. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  6101. )
  6102. if persisted_log:
  6103. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  6104. # Anything this process already observed goes after the persisted
  6105. # history — the log is ordered by layer, and a fresh process can
  6106. # only have seen changes from later in the print.
  6107. for entry in state.tray_change_log or []:
  6108. if tuple(entry) not in restored:
  6109. restored.append(tuple(entry))
  6110. state.tray_change_log = restored
  6111. tray_now = state.tray_now
  6112. if 0 <= tray_now <= 254:
  6113. if not state.tray_change_log:
  6114. # No persisted history — a print that started before this build,
  6115. # or before the row existed. Seed with the tray feeding right
  6116. # now so the remainder of the print is at least attributable to
  6117. # the right spool.
  6118. state.tray_change_log = [(tray_now, state.layer_num)]
  6119. logger.info(
  6120. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  6121. printer_id,
  6122. tray_now,
  6123. state.layer_num,
  6124. )
  6125. # The tray handler updates ``last_loaded_tray`` on every push
  6126. # regardless of whether it logged a change, so re-align it to avoid
  6127. # a duplicate entry on the next push. Only ever with a real tray:
  6128. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  6129. # 255" fallback, and writing 255 into it would defeat that.
  6130. state.last_loaded_tray = tray_now
  6131. except Exception:
  6132. # Never let attribution recovery cost the caller its timelapse
  6133. # baseline — that capture has to happen before the printer uploads
  6134. # the in-flight MP4 and there is no second chance at it.
  6135. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  6136. async def on_print_running_observed(printer_id: int, data: dict):
  6137. """Restart-recovery for a print that started before Bambuddy came up.
  6138. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  6139. after Bambuddy startup (#1304 guard, prevents duplicate archive
  6140. creation). This hook restores the persisted archive into ``_active_prints``
  6141. and captures the timelapse baseline that normally hangs off print start.
  6142. Fires once per session, in lieu of on_print_start when restart-recovery
  6143. kicks in. The printer doesn't upload the timelapse until after PRINT
  6144. COMPLETE, so a baseline captured any time during the print is still
  6145. pre-upload.
  6146. """
  6147. logger = logging.getLogger(__name__)
  6148. async with async_session() as db:
  6149. from backend.app.models.printer import Printer
  6150. state = printer_manager.get_status(printer_id)
  6151. if state is not None:
  6152. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  6153. if authorization is True:
  6154. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  6155. await _restore_usage_tracking_session(printer_id, state, db, logger)
  6156. await _restore_printable_objects(printer_id, state, db, logger)
  6157. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6158. printer = result.scalar_one_or_none()
  6159. if not printer:
  6160. logger.warning(
  6161. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  6162. printer_id,
  6163. )
  6164. return
  6165. # Avoid double-capture: ownership reconciliation above must still run when
  6166. # a baseline already exists, but the camera work itself is one-shot.
  6167. if printer_id in _timelapse_baselines:
  6168. logger.debug(
  6169. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  6170. printer_id,
  6171. )
  6172. return
  6173. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  6174. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  6175. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  6176. against the printer's current MQTT state.
  6177. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  6178. COMPLETE events, typically a print finishing during an MQTT disconnect
  6179. window followed by a smart-plug power cycle):
  6180. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  6181. provably not running anymore — only branch that should fire under
  6182. normal disconnect-then-reconnect timing.
  6183. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  6184. firmware mints a fresh ``subtask_id`` for each print, including the
  6185. ghost replay it runs after a power cycle from a leftover SD file —
  6186. so a mismatch unambiguously means the in-DB archive is no longer
  6187. the print on the printer.
  6188. 3. Printer is running but ``subtask_name`` is empty. The printer
  6189. doesn't know what it's running; the archive's reference to it is
  6190. already broken.
  6191. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  6192. with matching subtask_id+subtask_name is left alone. The cost of a false
  6193. positive is a duplicate archive on the next real PRINT COMPLETE — the
  6194. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  6195. clears on synthesis, so the real completion creates a fresh row instead
  6196. of overwriting the synthesised one (#1679). The cost of a false negative
  6197. is the ghost-print loop in #1542.
  6198. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  6199. MQTT has connected but the first ``push_status`` response hasn't been
  6200. applied yet — ``PrinterState`` is sitting on its construction defaults.
  6201. The reconcile caller in ``on_printer_status_change`` is already gated
  6202. on a real ``state.state``, so in normal operation this branch is
  6203. unreachable; it's kept as belt-and-braces for future callers and for
  6204. the narrow window where a partial state update could arrive
  6205. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  6206. ``not stale`` on degenerate input is strictly conservative: a real
  6207. stale archive will still be caught by the next push_status arriving
  6208. with terminal state.
  6209. """
  6210. current_state = (state.state or "").upper()
  6211. if current_state in ("", "UNKNOWN"):
  6212. # No real push_status yet — PrinterState defaults are not evidence.
  6213. return False, ""
  6214. if current_state in ("IDLE", "FINISH", "FAILED"):
  6215. return True, f"printer state {current_state}"
  6216. # Below here the printer is in a running / pre-running state (RUNNING /
  6217. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  6218. current_subtask_id = (state.subtask_id or "").strip()
  6219. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  6220. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  6221. current_subtask_name = (state.subtask_name or "").strip()
  6222. if not current_subtask_name:
  6223. return True, "printer subtask_name empty"
  6224. return False, ""
  6225. async def prime_kprofile_table(printer_id: int) -> int:
  6226. """Read the printer's calibration table once per connection.
  6227. The AMS slot card shows a K value per slot (#2854). On the printers whose
  6228. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  6229. report ``cali_idx`` and nothing else -- that number can only come from
  6230. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  6231. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  6232. backup, or the printer answering a query BambuStudio made on the report
  6233. topic we share. A Bambuddy that nobody visited showed a card with no K
  6234. values at all.
  6235. Only the diameters actually fitted are asked for, which is one request on a
  6236. single-nozzle printer and two on a dual. Probing the four sizes blind is
  6237. what the backup does, and it is both wasteful and the thing that used to
  6238. blank the table.
  6239. Returns the number of nozzles whose table was read.
  6240. """
  6241. client = printer_manager.get_client(printer_id)
  6242. state = printer_manager.get_status(printer_id)
  6243. if client is None or state is None or not state.connected:
  6244. return 0
  6245. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  6246. # ask once, and both entries are empty until the first push_status lands.
  6247. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  6248. if not diameters:
  6249. logging.getLogger(__name__).debug(
  6250. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  6251. printer_id,
  6252. )
  6253. return 0
  6254. primed = 0
  6255. for diameter in diameters:
  6256. try:
  6257. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  6258. except Exception as exc: # noqa: BLE001
  6259. # A printer that won't answer costs the card its K values, nothing
  6260. # more — never the connection this runs on the back of.
  6261. logging.getLogger(__name__).warning(
  6262. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  6263. )
  6264. continue
  6265. primed += 1
  6266. logging.getLogger(__name__).info(
  6267. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  6268. )
  6269. return primed
  6270. def _sd_files_in_use(state) -> set[str]:
  6271. """Names of the SD-card files the printer may be printing right now (#3009).
  6272. The post-print cleanup works out what to delete from the finished archive,
  6273. not from the printer. When reconciliation closes an old archive because the
  6274. printer has moved on to a new job, and that job is the same file reprinted
  6275. from the printer's screen, the cleanup would delete the file mid-print.
  6276. Empty unless the printer is busy: on an ordinary completion the state is
  6277. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  6278. name, a path or a URL depending on firmware, and some report only the
  6279. plate's G-code, so the job name is matched as well, in the same spellings
  6280. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  6281. ignores case.
  6282. """
  6283. def _text(value) -> str:
  6284. return value.strip() if isinstance(value, str) else ""
  6285. if state is None:
  6286. return set()
  6287. current_state = _text(getattr(state, "state", None)).upper()
  6288. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  6289. return set()
  6290. in_use: set[str] = set()
  6291. gcode_file = _text(getattr(state, "gcode_file", None))
  6292. if gcode_file:
  6293. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  6294. # both legal in a file name, and raises on some inputs.
  6295. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  6296. if name:
  6297. in_use.add(name.lower())
  6298. subtask_name = _text(getattr(state, "subtask_name", None))
  6299. if subtask_name:
  6300. for name in (subtask_name, subtask_name.replace(" ", "_")):
  6301. for ext in (".3mf", ".gcode"):
  6302. in_use.add(f"{name}{ext}".lower())
  6303. return in_use
  6304. async def reconcile_stale_active_prints(printer_id: int) -> int:
  6305. """Synthesise ``on_print_complete`` for archives whose print can't be
  6306. running on the printer anymore.
  6307. Called once per MQTT (re)connection (from on_printer_status_change when
  6308. the connected edge flips False → True) and at Bambuddy startup (from
  6309. the FastAPI lifespan). Without this, a print that completes during a
  6310. disconnect window — followed by a smart-plug-driven power cycle — leaves
  6311. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  6312. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  6313. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  6314. power cycle until the operator notices (#1542 follow-up). Reconciliation
  6315. closes the loop by faking the missed PRINT COMPLETE — the existing
  6316. cleanup chain handles SD-file deletion, status updates, usage tracking,
  6317. and notifications.
  6318. Synthesised ``status="aborted"`` is the conservative label: we have no
  6319. proof the print finished successfully (and no progress evidence to
  6320. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  6321. fires later, overwrites the status with the correct value.
  6322. Returns the number of archives reconciled.
  6323. """
  6324. state = printer_manager.get_status(printer_id)
  6325. if not state:
  6326. return 0
  6327. # Don't reconcile while disconnected — we'd be making a decision against
  6328. # stale cached state. The connected → reconcile edge handles this.
  6329. if not state.connected:
  6330. return 0
  6331. from backend.app.models.archive import PrintArchive
  6332. reconciled = 0
  6333. async with async_session() as db:
  6334. result = await db.execute(
  6335. select(PrintArchive).where(
  6336. PrintArchive.printer_id == printer_id,
  6337. PrintArchive.status == "printing",
  6338. )
  6339. )
  6340. active = list(result.scalars().all())
  6341. if not active:
  6342. return 0
  6343. logger = logging.getLogger(__name__)
  6344. for archive in active:
  6345. is_stale, reason = _is_active_archive_stale(archive, state)
  6346. if not is_stale:
  6347. continue
  6348. logger.info(
  6349. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  6350. printer_id,
  6351. archive.id,
  6352. archive.filename,
  6353. reason,
  6354. )
  6355. # Synthesised payload: minimal fields the on_print_complete chain
  6356. # needs. `_reconciled` marker lets downstream code distinguish this
  6357. # from a real MQTT-driven completion if it ever needs to (e.g. for
  6358. # metrics / debug logging). raw_data is the live printer state so
  6359. # the usage tracker can compare end-of-print remain% against the
  6360. # captured start values.
  6361. try:
  6362. await on_print_complete(
  6363. printer_id,
  6364. {
  6365. "status": "aborted",
  6366. "filename": archive.filename,
  6367. "subtask_name": archive.print_name or "",
  6368. "subtask_id": archive.subtask_id or "",
  6369. "raw_data": state.raw_data or {},
  6370. "_reconciled": True,
  6371. },
  6372. )
  6373. reconciled += 1
  6374. except Exception as e:
  6375. # Catch-all: a reconciliation failure must not block the
  6376. # printer's normal status flow. The archive stays in
  6377. # ``status="printing"`` and the next reconnect retries.
  6378. logger.warning(
  6379. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  6380. archive.id,
  6381. e,
  6382. )
  6383. return reconciled
  6384. # #2547: clearance left between the nozzle and the top of the print when the
  6385. # plate is commanded back into camera framing. The nozzle is parked away from
  6386. # the part by then, so this is belt-and-braces against a max_z_height that
  6387. # under-reports (e.g. a slicer that excludes a final Z hop).
  6388. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  6389. # How far below the restored position to drop the plate again afterwards, so
  6390. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  6391. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  6392. # on machines with less headroom.
  6393. _PLATE_PARK_DROP_MM = 100.0
  6394. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  6395. # this axis, so it is a proven-safe speed for the full travel.
  6396. _PLATE_RESTORE_FEEDRATE = 600
  6397. # Time allowed for the plate to reach the restored position before the camera
  6398. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  6399. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  6400. # How long `_background_finish_photo` waits for this producer. Must cover the
  6401. # settle window plus a worst-case RTSP grab (15s), and stay below the
  6402. # notification path's own photo wait so a slow producer degrades to a
  6403. # photo-less notification rather than a missed one. The chamber light's
  6404. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  6405. # camera_light.MAX_DELAY_SECONDS stays below it.
  6406. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  6407. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  6408. """The ``_active_prints`` keys a finished print may be registered under.
  6409. Matching how they were registered in on_print_start. Shared by
  6410. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  6411. to find the same binding.
  6412. """
  6413. possible_keys = []
  6414. # Try subtask_name variations first (most reliable for matching)
  6415. if subtask_name:
  6416. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  6417. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  6418. possible_keys.append((printer_id, subtask_name))
  6419. # Try filename variations
  6420. if filename:
  6421. # Extract just the filename if it's a path
  6422. fname = filename.split("/")[-1] if "/" in filename else filename
  6423. if fname.endswith(".3mf"):
  6424. possible_keys.append((printer_id, fname))
  6425. elif fname.endswith(".gcode"):
  6426. base_name = fname.rsplit(".", 1)[0]
  6427. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  6428. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6429. possible_keys.append((printer_id, fname))
  6430. else:
  6431. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  6432. possible_keys.append((printer_id, f"{fname}.3mf"))
  6433. possible_keys.append((printer_id, fname))
  6434. # Also try full path versions
  6435. if filename.endswith(".3mf"):
  6436. possible_keys.append((printer_id, filename))
  6437. elif filename.endswith(".gcode"):
  6438. base_name = filename.rsplit(".", 1)[0]
  6439. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6440. possible_keys.append((printer_id, filename))
  6441. else:
  6442. possible_keys.append((printer_id, f"{filename}.3mf"))
  6443. possible_keys.append((printer_id, filename))
  6444. return possible_keys
  6445. def _archive_name_forms(archive) -> set[str]:
  6446. """The names an archive could be echoed back as, in normalised form (#3240).
  6447. Its print name, and its filename with and without the 3MF extension.
  6448. """
  6449. forms = set()
  6450. if archive.print_name:
  6451. forms.add(_normalise_subtask_name(archive.print_name))
  6452. if archive.filename:
  6453. forms.add(_normalise_subtask_name(archive.filename))
  6454. for suffix in (".gcode.3mf", ".3mf"):
  6455. if archive.filename.lower().endswith(suffix):
  6456. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  6457. forms.discard("")
  6458. return forms
  6459. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  6460. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  6461. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  6462. from the plate recorded when the job was dispatched. Neither is touched:
  6463. ``on_print_complete`` pops both, which is why the finish-photo producer
  6464. calls this before its first await, while they are still there.
  6465. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  6466. archive, or that it only knows by a name -- and on any error: the producer
  6467. calls this before the ``try`` that always releases the photo consumer, so
  6468. it must not raise.
  6469. """
  6470. try:
  6471. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  6472. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  6473. if archive_id is None:
  6474. return None, None
  6475. return archive_id, _print_plate_ids.get(archive_id)
  6476. except Exception:
  6477. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  6478. return None, None
  6479. async def _max_z_for_current_print(
  6480. printer_id: int,
  6481. data: dict,
  6482. logger,
  6483. archive_id: int | None,
  6484. plate_id: int | None = None,
  6485. ) -> float | None:
  6486. """Height of the print that just finished on ``printer_id``, or None (#2547).
  6487. This number becomes the target of a real Z move, so every step here refuses
  6488. rather than guesses. A height belonging to some *other* print is the one
  6489. failure that could drive the nozzle into the model: 20 mm carried onto a
  6490. 200 mm print would command the plate up through the part.
  6491. Three independent things therefore have to agree before a height is
  6492. returned:
  6493. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  6494. when it started (see ``_bound_print``), never one found by name. A name
  6495. is not an identity: every plate of a multi-plate file shares one, and a
  6496. reprint reuses its archive row, so the newest archive with the right
  6497. name can be another plate of the same file. Support bundles show the
  6498. old name lookup doing exactly that (archive 288 for a print bound to
  6499. 169, 313 layers against 125), stopped only by the layer check below.
  6500. No binding, no move.
  6501. 2. **Identity.** The bound archive's name still has to be the finished
  6502. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  6503. because the printer echoes spaces as underscores (#3240). Exact: not a
  6504. substring, and not the completion check's tolerance for a truncated
  6505. echo.
  6506. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  6507. match the layer count the printer itself reported over MQTT for the print
  6508. that just ended. These come from genuinely different sources, so a
  6509. mismatch means the row is not this print, whatever its name says.
  6510. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  6511. plate of a multi-plate file reuses the archive row without updating its
  6512. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  6513. ``on_print_complete`` may already have flipped the status by the time we
  6514. run.
  6515. """
  6516. subtask_name = (data.get("subtask_name") or "").strip()
  6517. if not subtask_name:
  6518. # Nothing to identify the print by — refuse rather than fall back to
  6519. # "whatever ran last on this printer".
  6520. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  6521. return None
  6522. if archive_id is None:
  6523. logger.info(
  6524. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  6525. printer_id,
  6526. subtask_name,
  6527. )
  6528. return None
  6529. try:
  6530. from backend.app.models.archive import PrintArchive
  6531. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  6532. async with async_session() as db:
  6533. result = await db.execute(
  6534. select(PrintArchive).where(
  6535. PrintArchive.id == archive_id,
  6536. PrintArchive.printer_id == printer_id,
  6537. PrintArchive.status.in_(("printing", "completed")),
  6538. PrintArchive.deleted_at.is_(None),
  6539. )
  6540. )
  6541. archive = result.scalar_one_or_none()
  6542. if archive is None or not archive.file_path:
  6543. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  6544. return None
  6545. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  6546. logger.warning(
  6547. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  6548. printer_id,
  6549. archive_id,
  6550. subtask_name,
  6551. )
  6552. return None
  6553. client = printer_manager.get_client(printer_id)
  6554. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  6555. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  6556. logger.warning(
  6557. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  6558. "— refusing to move the plate on a height that may not be this print's",
  6559. printer_id,
  6560. archive.id,
  6561. archive.total_layers,
  6562. reported_layers,
  6563. )
  6564. return None
  6565. # Stored relative to the data directory, like every other archive path
  6566. # (#3240: this read a `data_dir` setting that does not exist).
  6567. path = app_settings.base_dir / archive.file_path
  6568. plate = plate_id or archive.plate_id or 1
  6569. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  6570. except Exception as e:
  6571. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  6572. return None
  6573. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  6574. """Raise the plate back into camera framing before the finish photo (#2547).
  6575. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  6576. the time ``gcode_state`` reaches FINISH the finished print sits far below
  6577. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  6578. This commands an absolute ``G1 Z`` back to just above the last printed
  6579. layer.
  6580. Absolute, not relative, is the whole safety argument. ``max_z_height +
  6581. clearance`` is a height the toolhead was physically at seconds earlier, so
  6582. it is inside the travel limits by construction and leaves the nozzle above
  6583. the part. It is also unambiguous across model families: Z is the
  6584. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  6585. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  6586. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  6587. (#2579).
  6588. Returns True if the move was sent and waited out, False if it was skipped.
  6589. """
  6590. client = printer_manager.get_client(printer_id)
  6591. if client is None:
  6592. return False
  6593. # Re-read state immediately before commanding motion. If the queue has
  6594. # already started the next print, the printer is no longer ours to move.
  6595. state = getattr(client, "state", None)
  6596. if state is None or state.state != "FINISH":
  6597. logger.info(
  6598. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  6599. printer_id,
  6600. getattr(state, "state", "unknown"),
  6601. )
  6602. return False
  6603. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  6604. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  6605. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  6606. return False
  6607. logger.info(
  6608. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  6609. printer_id,
  6610. target_z,
  6611. max_z_height,
  6612. _PLATE_RESTORE_CLEARANCE_MM,
  6613. _PLATE_RESTORE_SETTLE_SECONDS,
  6614. )
  6615. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  6616. return True
  6617. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  6618. """Drop the plate again after the finish photo (#2547).
  6619. Without this the user walks up to a finished print sitting just under the
  6620. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  6621. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  6622. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  6623. print homes anyway.
  6624. """
  6625. client = printer_manager.get_client(printer_id)
  6626. state = getattr(client, "state", None) if client else None
  6627. if client is None or state is None or state.state != "FINISH":
  6628. return
  6629. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  6630. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  6631. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  6632. """True if a queue item is about to take this printer (#2547).
  6633. The scheduler dispatches the next job the moment a print completes, and a
  6634. plate move interleaved with a print start is not a race worth having. The
  6635. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  6636. this window; this closes the head of it.
  6637. """
  6638. try:
  6639. from backend.app.models.print_queue import PrintQueueItem
  6640. async with async_session() as db:
  6641. result = await db.execute(
  6642. select(PrintQueueItem.id)
  6643. .where(
  6644. PrintQueueItem.printer_id == printer_id,
  6645. PrintQueueItem.status.in_(("pending", "printing")),
  6646. )
  6647. .limit(1)
  6648. )
  6649. return result.scalar_one_or_none() is not None
  6650. except Exception as e:
  6651. # Fail closed: if we can't tell, don't move the plate.
  6652. logging.getLogger(__name__).debug(
  6653. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  6654. )
  6655. return True
  6656. async def on_finish_photo_moment(printer_id: int, data: dict):
  6657. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  6658. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  6659. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  6660. fallback for prints that skip stage 22 (cancel, external-spool-only,
  6661. HMS halt, firmware variants). Grabs one frame via the same
  6662. external-camera / RTSP path the post-completion fallback uses, stores
  6663. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  6664. ``_background_finish_photo`` consume the cached bytes when it runs.
  6665. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  6666. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  6667. set to Smooth (#1721). No force-on now means the user's explicit
  6668. timelapse=off in the slicer send dialog is respected.
  6669. """
  6670. logger = logging.getLogger(__name__)
  6671. trigger = data.get("trigger", "unknown")
  6672. timelapse_was_active = bool(data.get("timelapse_was_active"))
  6673. logger.info(
  6674. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  6675. printer_id,
  6676. trigger,
  6677. timelapse_was_active,
  6678. )
  6679. # If a timelapse is actively recording, skip the pre-capture — the
  6680. # post-completion path will extract the last frame from the recorded
  6681. # video, which still provides the best framing (toolhead parked,
  6682. # before bed drop) without the per-layer parking side effects.
  6683. if timelapse_was_active:
  6684. logger.info(
  6685. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  6686. printer_id,
  6687. )
  6688. return
  6689. # #1790: register the producer-done event BEFORE the first await so the
  6690. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  6691. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  6692. # The `finally` below guarantees `set()` runs on every exit, including
  6693. # early returns and exceptions, so the consumer's bounded wait can't hang.
  6694. producer_done = asyncio.Event()
  6695. _stage22_finish_in_flight[printer_id] = producer_done
  6696. # #3240: also before the first await. On the FINISH-state path
  6697. # `on_print_complete` is dispatched right behind us and pops both the
  6698. # print's archive binding and its plate; read here, they are still there.
  6699. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  6700. # #2547: set once the plate has actually been raised, and read by the
  6701. # `finally` below. Declared out here so a failure anywhere after the move —
  6702. # a camera timeout, a DB error — still lowers the plate again.
  6703. restore_max_z: float | None = None
  6704. try:
  6705. async with async_session() as db:
  6706. from backend.app.api.routes.settings import get_setting
  6707. from backend.app.models.printer import Printer
  6708. capture_setting = await get_setting(db, "capture_finish_photo")
  6709. if capture_setting is not None and capture_setting.lower() != "true":
  6710. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  6711. return
  6712. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6713. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  6714. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6715. printer = result.scalar_one_or_none()
  6716. if printer is None:
  6717. logger.warning(
  6718. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  6719. printer_id,
  6720. )
  6721. return
  6722. frame_bytes: bytes | None = None
  6723. # #2708: the banked frame arrives already rotated — it comes from
  6724. # `_capture_snapshot_for_notification`, which rotates before returning.
  6725. # Every other source below is a raw grab. Tracking which lets us store
  6726. # exactly one rotation in `_stage22_finish_frames` either way.
  6727. frame_already_rotated = False
  6728. # On the FINISH-state path the End G-code has already run, and two very
  6729. # different situations arrive here needing opposite answers.
  6730. #
  6731. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  6732. # snippet may have ejected the plate — the scene in front of the camera
  6733. # is no longer the finished print, and no amount of moving the plate
  6734. # brings it back. Use the banked in-print frame instead.
  6735. #
  6736. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  6737. # than the camera frames well, and the toolhead is parked out of the
  6738. # way. That is the *best* moment available on firmware that never emits
  6739. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  6740. # back. Preferring the bank here unconditionally, as this code used to,
  6741. # is what shipped a mid-print photo with the toolhead over the part.
  6742. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  6743. banked = _inprint_frame_bank.get(printer_id)
  6744. if banked:
  6745. frame_bytes = banked
  6746. frame_already_rotated = True
  6747. logger.info(
  6748. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  6749. "frame (%d bytes) instead of a post-swap live grab",
  6750. len(banked),
  6751. )
  6752. else:
  6753. logger.warning(
  6754. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  6755. "in-print bank is empty — falling back to a live grab, which may show a "
  6756. "swapped or empty plate",
  6757. printer_id,
  6758. )
  6759. # `restore_max_z` is set only once the plate is actually up, because the
  6760. # `finally` reads it to decide whether it owes a move back down.
  6761. #
  6762. # Never on a print whose End G-code Bambuddy injected, even when the bank
  6763. # came up empty above: that machine may have just ejected its plate, and
  6764. # driving Z into whatever a swap mechanism is doing is not a risk worth
  6765. # taking for a photo of a bed we already know may be bare.
  6766. if (
  6767. frame_bytes is None
  6768. and trigger == "finish_state"
  6769. and restore_plate_enabled
  6770. and not print_dispatch_context.end_gcode_injected(printer_id)
  6771. ):
  6772. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  6773. if wants_restore is None:
  6774. logger.info(
  6775. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  6776. printer_id,
  6777. )
  6778. elif await _plate_restore_is_blocked_by_queue(printer_id):
  6779. logger.info(
  6780. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  6781. printer_id,
  6782. )
  6783. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  6784. restore_max_z = wants_restore
  6785. # Chamber light for the live capture below (#1655). The banked frame
  6786. # above was taken without it, like every in-print bank.
  6787. async with camera_light(printer if frame_bytes is None else None):
  6788. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  6789. from backend.app.api.routes.camera import live_frame_for_capture
  6790. from backend.app.services.external_camera import capture_frame
  6791. # #2707: this used to collide with the live view and fail, which is
  6792. # how finish-photo notifications went out with no image attached.
  6793. # Leaving frame_bytes None keeps the rest of the fallback chain.
  6794. defer, buffered = live_frame_for_capture(printer_id)
  6795. if defer:
  6796. frame_bytes = buffered
  6797. else:
  6798. frame_bytes = await capture_frame(
  6799. printer.external_camera_url,
  6800. printer.external_camera_type or "mjpeg",
  6801. snapshot_url=printer.external_camera_snapshot_url,
  6802. )
  6803. if frame_bytes:
  6804. logger.info(
  6805. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  6806. len(frame_bytes),
  6807. )
  6808. elif frame_bytes is None:
  6809. from backend.app.api.routes.camera import get_buffered_frame
  6810. buffered = get_buffered_frame(printer_id)
  6811. if buffered:
  6812. frame_bytes = buffered
  6813. logger.info(
  6814. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  6815. len(frame_bytes),
  6816. )
  6817. else:
  6818. from backend.app.services.camera import capture_camera_frame_bytes
  6819. frame_bytes = await capture_camera_frame_bytes(
  6820. ip_address=printer.ip_address,
  6821. access_code=printer.access_code,
  6822. model=printer.model,
  6823. timeout=15,
  6824. )
  6825. if frame_bytes:
  6826. logger.info(
  6827. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  6828. len(frame_bytes),
  6829. )
  6830. if frame_bytes:
  6831. if not frame_already_rotated:
  6832. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  6833. _stage22_finish_frames[printer_id] = frame_bytes
  6834. else:
  6835. logger.warning(
  6836. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  6837. printer_id,
  6838. )
  6839. except Exception as e:
  6840. logger.warning(
  6841. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  6842. printer_id,
  6843. e,
  6844. )
  6845. finally:
  6846. # #2547: we raised the plate, so we own lowering it — including when the
  6847. # capture above failed or threw partway through.
  6848. if restore_max_z is not None:
  6849. try:
  6850. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  6851. except Exception as e:
  6852. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6853. # #1790: always unblock the consumer's bounded wait — whether we stored
  6854. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  6855. # dict entry by the consumer doesn't affect signalling.
  6856. producer_done.set()
  6857. def _subtask_name_from_filename(filename: str) -> str:
  6858. """Recover the subtask name a print command would have carried for *filename*.
  6859. The dispatcher derives the printer-facing subtask name from the archive's
  6860. file name, so stripping the extensions back off gives the value MQTT echoes
  6861. on completion. Only the two extensions Bambuddy actually stores are removed,
  6862. and in the order they nest (``.gcode.3mf``), so a model whose own name
  6863. contains a dot -- ``My.Model.3mf`` -- keeps it.
  6864. """
  6865. name = PurePosixPath(filename).name
  6866. for suffix in (".3mf", ".gcode"):
  6867. if name.lower().endswith(suffix):
  6868. name = name[: -len(suffix)]
  6869. return name
  6870. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  6871. """Whether the subtask name is the printed 3MF's own file name.
  6872. A print started from the printer's screen reports the same full name, with
  6873. its extension, as both subtask and file (#3009). A dispatched print reports
  6874. a bare subtask name; one that merely ends in ".3mf" can be a model named
  6875. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  6876. """
  6877. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  6878. return False
  6879. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  6880. # How the printer marks a subtask name it had to cut short. Observed on real
  6881. # hardware at ~100 characters, but the cut-off is not a fixed character count
  6882. # (a name with multibyte characters came back at 98), so match the marker
  6883. # rather than a length.
  6884. _SUBTASK_TRUNCATION_MARKER = "..."
  6885. def _normalise_subtask_name(name: str) -> str:
  6886. """Canonical form for comparing a dispatched name against MQTT's echo.
  6887. The printer does not echo the name back verbatim: it substitutes
  6888. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  6889. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  6890. The 3MF lookup in this module has always known that -- it builds
  6891. space-to-underscore variants of every candidate filename, and its
  6892. directory search normalises both sides before comparing. This exists so
  6893. the completion check reads the same rule from the same place instead of
  6894. growing its own, which is exactly how it came to disagree (#2829).
  6895. A space at either end is substituted too: ``Part .gcode.3mf`` is
  6896. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  6897. are dropped after the substitution so both sides agree (#3241).
  6898. """
  6899. return name.strip().replace(" ", "_").strip("_").casefold()
  6900. def _3mf_files_for_print(paths: list[str], search_term: str) -> list[str]:
  6901. """The 3MF files of the printer's folder listings that are this print's.
  6902. A file of the print's own name wins, in whichever folder. Only without one
  6903. is a file that merely contains the name taken, and then only when it is
  6904. the one such file: "Cube_large.3mf" is not "Cube"'s file, and of several
  6905. candidates none can be told apart. Paths keep the listings' order.
  6906. """
  6907. threemf = [path for path in paths if path.lower().endswith(".3mf")]
  6908. exact = [path for path in threemf if _subtask_names_match(_subtask_name_from_filename(path), search_term)]
  6909. if exact:
  6910. return exact
  6911. term = _normalise_subtask_name(search_term)
  6912. partial = [path for path in threemf if term in _normalise_subtask_name(PurePosixPath(path).name)]
  6913. if len(partial) > 1:
  6914. logging.getLogger(__name__).info(
  6915. "Several 3MF files contain %r and none is named for it: %s", search_term, partial
  6916. )
  6917. return []
  6918. return partial
  6919. def _subtask_names_match(expected: str, observed: str) -> bool:
  6920. """Whether two subtask names describe the same print.
  6921. Beyond the space/underscore substitution, the printer truncates long names
  6922. and marks the cut with ``...``. A truncated echo has to count as a match or
  6923. every print with a long name strands its queue item the same way.
  6924. """
  6925. expected_n = _normalise_subtask_name(expected)
  6926. observed_n = _normalise_subtask_name(observed)
  6927. if expected_n == observed_n:
  6928. return True
  6929. # Either side can be the truncated one: the printer truncates what it
  6930. # echoes, and an archive whose own filename was recorded from a previous
  6931. # truncated echo carries the marker too.
  6932. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  6933. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  6934. continue
  6935. # The full side has lost its edge underscores; a cut that lands right
  6936. # after one keeps it, so drop it here too (#3241). Nothing left before
  6937. # the marker is no evidence of anything, and must not match every name.
  6938. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  6939. if kept and full.startswith(kept):
  6940. return True
  6941. return False
  6942. async def _queue_item_dispatched_name(db, item) -> str:
  6943. """The subtask name *item* was dispatched under, or "" when unknowable.
  6944. A row with no archive, or an archive with no file name, is unverifiable
  6945. rather than wrong; every caller answers that with its permissive branch.
  6946. """
  6947. if item.archive_id is None:
  6948. return ""
  6949. from backend.app.models.archive import PrintArchive
  6950. archive = await db.get(PrintArchive, item.archive_id)
  6951. if archive is None or not archive.filename:
  6952. return ""
  6953. return _subtask_name_from_filename(archive.filename)
  6954. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  6955. """Whether this completion event is plausibly about *item*'s print.
  6956. The caller finds its queue row by printer and ``status='printing'`` alone,
  6957. which is all a completion event gives it -- there is no run identifier in
  6958. the MQTT payload to match on. That makes the lookup indiscriminate: any
  6959. completion delivered for this printer closes whichever row happens to be
  6960. printing, however unrelated. Comparing the subtask name against the archive
  6961. the row was dispatched with costs one primary-key load and rules that out.
  6962. Deliberately permissive: it answers False only on a positive disagreement
  6963. between two names we actually have. A row with no archive, an archive with
  6964. no file name, or an event with no subtask name is unverifiable rather than
  6965. wrong, and refusing those would strand the item in ``printing`` and wedge
  6966. the printer's queue -- a worse failure than the one being prevented.
  6967. """
  6968. observed = (data.get("subtask_name") or "").strip()
  6969. if not observed or item.archive_id is None:
  6970. return True
  6971. from backend.app.models.archive import PrintArchive
  6972. archive = await db.get(PrintArchive, item.archive_id)
  6973. if archive is None or not archive.filename:
  6974. return True
  6975. expected = _subtask_name_from_filename(archive.filename)
  6976. if not expected or _subtask_names_match(expected, observed):
  6977. return True
  6978. logging.getLogger(__name__).warning(
  6979. "Ignoring print completion for queue item %s: it was dispatched as %r "
  6980. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  6981. "printing rather than closing a run this event is not about.",
  6982. item.id,
  6983. expected,
  6984. archive.id,
  6985. archive.filename,
  6986. observed,
  6987. )
  6988. return False
  6989. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  6990. """Spend the 3MF download cache on a still-empty fallback archive.
  6991. ``on_print_complete`` drops the cache as its first act, which deletes the
  6992. file. If the cover endpoint (or anything else) pulled the 3MF while the
  6993. print ran and the archive never got one, this is the last moment those bytes
  6994. exist (#2957).
  6995. """
  6996. logger = logging.getLogger(__name__)
  6997. names = [
  6998. n
  6999. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  7000. if n
  7001. ]
  7002. for name in names:
  7003. try:
  7004. cached = get_cached_3mf(printer_id, name)
  7005. # The print has ended: its completion prices the archive, so no
  7006. # print-start estimate is scheduled to race it.
  7007. if cached and await try_recover_fallback_archive(printer_id, name, cached, price=False):
  7008. return
  7009. except Exception as e:
  7010. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  7011. # Longest the print's end waits for its file to be deleted from the SD card
  7012. _SD_CLEANUP_BUDGET_SECONDS = 45.0
  7013. async def _cleanup_sd_card_after_print(
  7014. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  7015. ) -> None:
  7016. """Delete a finished print's file from the printer's SD card."""
  7017. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  7018. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  7019. # auto-start files found in root on power cycle, causing ghost prints.
  7020. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  7021. try:
  7022. if subtask_name:
  7023. archive_filename: str | None = None
  7024. async with async_session() as db:
  7025. from backend.app.models.archive import PrintArchive
  7026. from backend.app.models.printer import Printer
  7027. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7028. printer = result.scalar_one_or_none()
  7029. if archive_id:
  7030. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  7031. archive_filename = archive_row.scalar_one_or_none()
  7032. if printer:
  7033. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  7034. from backend.app.utils.filename import derive_remote_filename
  7035. # Primary candidate: the exact path the dispatcher uploaded to
  7036. # (derived from archive.filename via the same rule as upload).
  7037. # Without it, a library row that ended up with a doubled
  7038. # .gcode.3mf (#1542) leaves the real file behind because the
  7039. # subtask_name + ext fallbacks below don't match what's on the
  7040. # SD card. Fallbacks remain for archive-less prints (subtask
  7041. # never resolved to an archive) and for older naming variants.
  7042. candidate_paths: list[str] = []
  7043. if archive_filename:
  7044. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  7045. for ext in (".3mf", ".gcode"):
  7046. fallback = f"/{subtask_name}{ext}"
  7047. if fallback not in candidate_paths:
  7048. candidate_paths.append(fallback)
  7049. # Three outcomes track across all candidates so the final log
  7050. # line reflects what actually happened. The A1 in #1721 always
  7051. # ends here with ``any_not_found=True`` and the others False
  7052. # — its firmware auto-cleans the SD card before our cleanup
  7053. # runs, every candidate FTP-DELE returns 550, and the old
  7054. # code burned 3 retries × 2 s × 3 candidates per print
  7055. # logging a misleading "may linger" WARNING on a successful
  7056. # print.
  7057. any_deleted = False
  7058. any_real_failure = False
  7059. any_not_found = False
  7060. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  7061. for remote_path in candidate_paths:
  7062. if PurePosixPath(remote_path).name.lower() in files_in_use:
  7063. logger.info(
  7064. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  7065. remote_path,
  7066. printer.name,
  7067. )
  7068. continue
  7069. # Retry only the FAILED case — 550 NOT_FOUND will never
  7070. # recover by waiting, so a "file isn't here" answer
  7071. # advances immediately to the next candidate without
  7072. # consuming the retry budget.
  7073. for attempt in range(1, 4):
  7074. try:
  7075. delete_result = await delete_file_async(
  7076. printer.ip_address,
  7077. printer.access_code,
  7078. remote_path,
  7079. printer_model=printer.model,
  7080. )
  7081. except Exception as e:
  7082. delete_result = DeleteResult.FAILED
  7083. logger.warning(
  7084. "SD card cleanup attempt %d/3 raised for %s: %s",
  7085. attempt,
  7086. remote_path,
  7087. e,
  7088. )
  7089. if delete_result == DeleteResult.DELETED:
  7090. any_deleted = True
  7091. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  7092. break
  7093. if delete_result == DeleteResult.NOT_FOUND:
  7094. any_not_found = True
  7095. break # 550 will not recover; try next candidate
  7096. # FAILED: real error — retry with backoff, then give up
  7097. if attempt < 3:
  7098. await asyncio.sleep(2)
  7099. else:
  7100. any_real_failure = True
  7101. logger.warning(
  7102. "SD card cleanup failed after 3 attempts for %s "
  7103. "(network/auth/transient error — file may linger on SD card)",
  7104. remote_path,
  7105. )
  7106. if not any_deleted and not any_real_failure and any_not_found:
  7107. # Every candidate said "not here." Either the printer
  7108. # firmware swept the SD card itself (common on A1) or the
  7109. # dispatcher's upload path doesn't match our candidate
  7110. # rule. Either way: nothing to clean up, no warning.
  7111. logger.debug(
  7112. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  7113. "(printer likely self-cleaned)",
  7114. printer.name,
  7115. )
  7116. except Exception as e:
  7117. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  7118. async def on_print_complete(printer_id: int, data: dict):
  7119. """Handle print completion - update the archive status.
  7120. The printer counts as printing until the print's usage is booked (or this
  7121. ends), so the AMS remain% weight sync can't charge it a second time while
  7122. the usage tracker works (WU-3). Marked before the first await.
  7123. """
  7124. from backend.app.services.usage_tracker import done_completing, mark_completing
  7125. mark_completing(printer_id)
  7126. try:
  7127. await _close_out_print(printer_id, data)
  7128. finally:
  7129. done_completing(printer_id)
  7130. async def _close_out_print(printer_id: int, data: dict):
  7131. import time
  7132. logger = logging.getLogger(__name__)
  7133. start_time = time.time()
  7134. def log_timing(section: str):
  7135. elapsed = time.time() - start_time
  7136. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  7137. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  7138. # A kill-switch stop sends its provider notification immediately. Keep the
  7139. # task so the later notification path can await it and avoid a duplicate;
  7140. # if that immediate attempt failed, the regular completion path retries.
  7141. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  7142. # Last chance before the bytes go: if this print's archive is still an empty
  7143. # fallback and something downloaded the 3MF while it ran, fill the archive in
  7144. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  7145. # below deletes the file (#2957).
  7146. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  7147. # A pending cool-off retry has nothing left to recover for — the cache is
  7148. # about to be dropped and the print is over.
  7149. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  7150. if retry_task and not retry_task.done():
  7151. retry_task.cancel()
  7152. # Drop the 3MF download cache for this printer (#972). The print is over,
  7153. # nothing else legitimately needs the bytes; keeping them would only risk
  7154. # handing a stale file to the next print if it reuses the same name.
  7155. clear_3mf_cache(printer_id)
  7156. try:
  7157. ws_data = {
  7158. "status": data.get("status"),
  7159. "filename": data.get("filename"),
  7160. "subtask_name": data.get("subtask_name"),
  7161. "timelapse_was_active": data.get("timelapse_was_active"),
  7162. }
  7163. await ws_manager.send_print_complete(printer_id, ws_data)
  7164. log_timing("WebSocket send_print_complete")
  7165. except Exception as e:
  7166. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  7167. # Capture user info before clearing (needed for print log entry)
  7168. _print_user_info = printer_manager.get_current_print_user(printer_id)
  7169. # Clear current print user tracking (Issue #206)
  7170. printer_manager.clear_current_print_user(printer_id)
  7171. # If the user explicitly stopped this print from the queue UI the printer will
  7172. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  7173. # correct "print stopped" notification/email is sent instead of a failure alert.
  7174. _raw_status = data.get("status", "completed")
  7175. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  7176. logger.info(
  7177. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  7178. _raw_status,
  7179. printer_id,
  7180. )
  7181. data = {**data, "status": "cancelled"}
  7182. elif printer_id in _kill_switch_stopped and _raw_status in ("failed", "aborted"):
  7183. logger.info(
  7184. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (stopped by the printer kill switch)",
  7185. _raw_status,
  7186. printer_id,
  7187. )
  7188. data = {**data, "status": "cancelled", "_kill_switch": True}
  7189. _user_stopped_printers.discard(printer_id)
  7190. _kill_switch_stopped.discard(printer_id)
  7191. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  7192. # may have left material on the bed: a user can cancel ten hours into a
  7193. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  7194. # touchscreen-stop reports `aborted` rather than `cancelled` because
  7195. # `_user_stopped_printers` is only populated when the user stops via the
  7196. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  7197. # which auto-dispatched the next queued print onto a fouled bed two seconds
  7198. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  7199. # Auto Off power cycles and Bambuddy restarts.
  7200. try:
  7201. notify_live_activities.print_finished(printer_id, data)
  7202. except Exception:
  7203. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  7204. _final_status = data.get("status", "completed")
  7205. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  7206. printer_manager.set_awaiting_plate_clear(printer_id, True)
  7207. # MQTT relay - publish print complete
  7208. try:
  7209. printer_info = printer_manager.get_printer(printer_id)
  7210. if printer_info:
  7211. await mqtt_relay.on_print_complete(
  7212. printer_id,
  7213. printer_info.name,
  7214. printer_info.serial_number,
  7215. data.get("filename", ""),
  7216. data.get("subtask_name", ""),
  7217. data.get("status", "completed"),
  7218. )
  7219. except Exception:
  7220. pass # Don't fail print complete callback if MQTT fails
  7221. filename = data.get("filename", "")
  7222. subtask_name = data.get("subtask_name", "")
  7223. if not filename and not subtask_name:
  7224. # Which print ended can't be told: the printer reported no name since
  7225. # Bambuddy started (a print that failed while preparing, a calibration).
  7226. # Charge nothing, but close the print session, which otherwise kept the
  7227. # AMS weight sync off until the next print (AS-5). A print archived as
  7228. # running is closed and charged by the reconnect reconcile.
  7229. logger.warning("Print complete without filename or subtask_name")
  7230. try:
  7231. from backend.app.services.usage_tracker import discard_session
  7232. async with async_session() as db:
  7233. await discard_session(db, printer_id)
  7234. except Exception as e:
  7235. logger.warning("Failed to clear print session for printer %s: %s", printer_id, e)
  7236. return
  7237. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  7238. # Build list of possible keys to try (matching how they were registered in on_print_start)
  7239. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  7240. # Find the archive for this print
  7241. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  7242. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  7243. archive_id = None
  7244. for key in possible_keys:
  7245. archive_id = _active_prints.pop(key, None)
  7246. if archive_id:
  7247. _owned_print_archive_ids.discard(archive_id)
  7248. logger.info("Found archive %s with key %s", archive_id, key)
  7249. # Also clean up any other keys pointing to this archive
  7250. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  7251. for k in keys_to_remove:
  7252. _active_prints.pop(k, None)
  7253. break
  7254. # The archive bound when the print started, before the name search below.
  7255. # Only this one may give the finish-photo plate restore a height (#3240):
  7256. # the search matches names by substring.
  7257. bound_archive_id = archive_id
  7258. if not archive_id:
  7259. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  7260. async with async_session() as db:
  7261. from backend.app.models.archive import PrintArchive
  7262. # Try matching by subtask_name (stored as print_name) first. The
  7263. # same name rule as the queue's completion check: a name inside
  7264. # another ("Clip" in "Cable Clip") is a different print, and the
  7265. # printer's underscores for spaces and truncation still match.
  7266. if subtask_name:
  7267. printing = await db.scalars(
  7268. select(PrintArchive)
  7269. .where(PrintArchive.printer_id == printer_id)
  7270. .where(PrintArchive.status == "printing")
  7271. .order_by(PrintArchive.created_at.desc())
  7272. )
  7273. # A print started from the printer's screen reports its file
  7274. # name, extensions included, as the subtask (#3009).
  7275. reported = {subtask_name, _subtask_name_from_filename(subtask_name)}
  7276. archive = next(
  7277. (
  7278. candidate
  7279. for candidate in printing
  7280. if any(
  7281. (candidate.print_name and _subtask_names_match(candidate.print_name, name))
  7282. or (
  7283. candidate.filename
  7284. and _subtask_names_match(_subtask_name_from_filename(candidate.filename), name)
  7285. )
  7286. for name in reported
  7287. )
  7288. ),
  7289. None,
  7290. )
  7291. if archive:
  7292. archive_id = archive.id
  7293. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  7294. # Also try by filename
  7295. if not archive_id and filename:
  7296. result = await db.execute(
  7297. select(PrintArchive)
  7298. .where(PrintArchive.printer_id == printer_id)
  7299. .where(PrintArchive.filename == filename)
  7300. .where(PrintArchive.status == "printing")
  7301. .order_by(PrintArchive.created_at.desc())
  7302. .limit(1)
  7303. )
  7304. archive = result.scalar_one_or_none()
  7305. if archive:
  7306. archive_id = archive.id
  7307. # Bounded: a printer whose FTP hangs on DELE took up to 3 candidates x 3
  7308. # attempts x a 60 s timeout, about nine minutes, before the queue item was
  7309. # closed below. The stranded-job closer gives up after five and closed it
  7310. # first, so the job's auto-off and its billing never ran. Inline rather
  7311. # than in the background, so the next job of the same file isn't released
  7312. # (and uploaded under the name being deleted) while the cleanup still
  7313. # works on it. A delete already sent may still finish in its FTP thread
  7314. # after the cutoff, as one past delete_file_async's own timeout always did.
  7315. try:
  7316. await asyncio.wait_for(
  7317. _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger),
  7318. timeout=_SD_CLEANUP_BUDGET_SECONDS,
  7319. )
  7320. except TimeoutError:
  7321. logger.warning(
  7322. "SD card cleanup on printer %s took over %ss; leaving the file there and closing the print",
  7323. printer_id,
  7324. _SD_CLEANUP_BUDGET_SECONDS,
  7325. )
  7326. log_timing("SD card cleanup")
  7327. # Update queue item status early — must run before the archive_id early-return
  7328. # so queue items don't get stuck in "printing" when archive lookup fails.
  7329. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  7330. queue_item_id = None
  7331. billing_run_id: str | None = None
  7332. billing_user_id: int | None = None
  7333. billing_cost_center_id: int | None = None
  7334. billing_plate_id: int | None = None
  7335. queue_status = None
  7336. queue_auto_off = False
  7337. try:
  7338. from backend.app.core.database import run_with_retry
  7339. from backend.app.models.print_queue import PrintQueueItem
  7340. async def _update_queue_status(db):
  7341. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  7342. nonlocal queue_item_id, queue_status, queue_auto_off
  7343. result = await db.execute(
  7344. select(PrintQueueItem)
  7345. .where(PrintQueueItem.printer_id == printer_id)
  7346. .where(PrintQueueItem.status == "printing")
  7347. )
  7348. printing_items = list(result.scalars().all())
  7349. if len(printing_items) > 1:
  7350. logger.warning(
  7351. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  7352. printer_id,
  7353. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  7354. )
  7355. item = printing_items[0] if printing_items else None
  7356. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  7357. return
  7358. if item:
  7359. queue_status = data.get("status", "completed")
  7360. # MQTT sends "aborted" for cancelled prints; normalise to
  7361. # "cancelled" so it matches the queue schema Literal.
  7362. if queue_status == "aborted":
  7363. queue_status = "cancelled"
  7364. item.status = queue_status
  7365. item.completed_at = datetime.now(timezone.utc)
  7366. if queue_status == "failed" and not item.error_message:
  7367. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  7368. # Bump usage counters on the source library file so admins can
  7369. # sort by "last printed" and (eventually) auto-purge stale
  7370. # files — #1008.
  7371. await _bump_library_file_usage_if_completed(db, item, queue_status)
  7372. await db.commit()
  7373. queue_item_id = item.id
  7374. billing_run_id = item.billing_run_id
  7375. billing_user_id = item.created_by_id
  7376. billing_cost_center_id = item.cost_center_id
  7377. billing_plate_id = item.plate_id
  7378. queue_auto_off = item.auto_off_after
  7379. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  7380. await run_with_retry(_update_queue_status, label="queue status update")
  7381. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  7382. # their own sessions and have their own error handling — no retry needed.
  7383. if queue_item_id is not None:
  7384. # Batch orders (#342): this run may have been the last one an order
  7385. # owed. Re-evaluate here rather than lazily on read, so a finished
  7386. # order reports itself complete without someone opening the page.
  7387. try:
  7388. from backend.app.services.print_batch import refresh_batch_status_for_item
  7389. async with async_session() as db:
  7390. await refresh_batch_status_for_item(db, queue_item_id)
  7391. await db.commit()
  7392. except Exception as e:
  7393. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  7394. # MQTT relay - publish queue job completed
  7395. try:
  7396. printer_info = printer_manager.get_printer(printer_id)
  7397. await mqtt_relay.on_queue_job_completed(
  7398. job_id=queue_item_id,
  7399. filename=filename or subtask_name,
  7400. printer_id=printer_id,
  7401. printer_name=printer_info.name if printer_info else "Unknown",
  7402. status=queue_status,
  7403. )
  7404. except Exception:
  7405. pass # Don't fail if MQTT fails
  7406. # Check if queue is now empty and send notification
  7407. try:
  7408. from sqlalchemy import func as sa_func
  7409. async with async_session() as db:
  7410. count_result = await db.execute(
  7411. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  7412. )
  7413. pending_count = count_result.scalar() or 0
  7414. if pending_count == 0:
  7415. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  7416. completed_result = await db.execute(
  7417. select(sa_func.count(PrintQueueItem.id)).where(
  7418. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  7419. PrintQueueItem.completed_at >= today_start,
  7420. )
  7421. )
  7422. completed_count = completed_result.scalar() or 1
  7423. await notification_service.on_queue_completed(
  7424. completed_count=completed_count,
  7425. db=db,
  7426. )
  7427. except Exception:
  7428. pass # Don't fail if notification fails
  7429. # Handle auto_off_after - power off printer if the queue item opted
  7430. # in. Delegates to the smart-plug manager so the off honours each
  7431. # plug's configured strategy (time delay or temperature threshold),
  7432. # is cancelled if the printer starts printing again, and never cuts
  7433. # power on a loaded print (#1890). Previously an inline block here
  7434. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  7435. # timeout regardless of print state — cutting a touchscreen reprint.
  7436. if queue_auto_off:
  7437. try:
  7438. async with async_session() as db:
  7439. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  7440. except Exception as e:
  7441. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  7442. except Exception as e:
  7443. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  7444. log_timing("Queue item update")
  7445. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  7446. # Must run before archive_id early-return so it fires for all prints (including
  7447. # prints started from BambuStudio/touchscreen that have no archive).
  7448. if data.get("status") == "completed":
  7449. try:
  7450. from backend.app.api.routes.settings import get_setting
  7451. async with async_session() as db:
  7452. threshold_str = await get_setting(db, "bed_cooled_threshold")
  7453. threshold = float(threshold_str) if threshold_str else 35.0
  7454. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  7455. async with async_session() as db:
  7456. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  7457. if providers:
  7458. _bed_cool_waiters[printer_id] = {
  7459. "threshold": threshold,
  7460. "filename": filename or subtask_name or "",
  7461. "registered_at": time.time(),
  7462. }
  7463. logger.info(
  7464. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  7465. printer_id,
  7466. threshold,
  7467. )
  7468. else:
  7469. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  7470. except Exception as e:
  7471. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  7472. # Capture the slicer estimate before usage tracking runs. The tracker may
  7473. # update archive.cost with this run's measured cost; billing partial runs
  7474. # against that already-partial value would discount the charge twice.
  7475. billing_planned_grams: float | None = None
  7476. billing_base_cost: float | None = None
  7477. if archive_id:
  7478. try:
  7479. async with async_session() as db:
  7480. from backend.app.models.archive import PrintArchive
  7481. billing_archive = await db.get(PrintArchive, archive_id)
  7482. if billing_archive:
  7483. billing_path = (
  7484. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  7485. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7486. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  7487. billing_archive,
  7488. billing_path,
  7489. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  7490. )
  7491. except Exception as e:
  7492. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  7493. # --- Track filament consumption (must run before archive_id early-return so usage
  7494. # is recorded even when auto-archive is disabled) ---
  7495. usage_results: list[dict] = []
  7496. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  7497. stored_ams_mapping = data.get("ams_mapping")
  7498. # Fallback to _print_ams_mappings for queue/reprint (set before print starts).
  7499. # Drained either way, like the plate below: left over, it would be read by
  7500. # the archive's next run, dispatched without a mapping.
  7501. registered_ams_mapping = _print_ams_mappings.pop(archive_id, None) if archive_id else None
  7502. if not stored_ams_mapping:
  7503. stored_ams_mapping = registered_ams_mapping
  7504. # Always drain the plate_id register on completion — the session already
  7505. # consumed it at print-start injection; leaving it would leak into the next
  7506. # print on the same archive_id (rare but possible with reprints) (#1697).
  7507. # Capture the popped value so the completion notification can scope the
  7508. # archive-level (summed-across-plates per #1593) filament + time totals
  7509. # down to the single plate that was actually printed (#1785).
  7510. notify_plate_id: int | None = None
  7511. if archive_id:
  7512. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  7513. # The start estimate must not outlive the real cost written below (COST-4).
  7514. if archive_id:
  7515. await _settle_archive_cost_estimate(archive_id)
  7516. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  7517. try:
  7518. async with async_session() as db:
  7519. from backend.app.api.routes.settings import get_setting
  7520. _spoolman_on = await get_setting(db, "spoolman_enabled")
  7521. if not _spoolman_on or _spoolman_on.lower() != "true":
  7522. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  7523. async with async_session() as db:
  7524. usage_results = await usage_on_print_complete(
  7525. printer_id,
  7526. data,
  7527. printer_manager,
  7528. db,
  7529. archive_id=archive_id,
  7530. ams_mapping=stored_ams_mapping,
  7531. )
  7532. if usage_results:
  7533. await ws_manager.broadcast(
  7534. {
  7535. "type": "spool_usage_logged",
  7536. "printer_id": printer_id,
  7537. "usage": usage_results,
  7538. }
  7539. )
  7540. log_timing("Usage tracker")
  7541. except Exception as e:
  7542. logger.warning("Usage tracker on_print_complete failed: %s", e)
  7543. # Drop the print-start context unconditionally — the Spoolman branch above
  7544. # skips the internal tracker entirely, so nothing else would clear what
  7545. # print start captured, and a row surviving its print would be restored
  7546. # onto the next one after a restart.
  7547. try:
  7548. from backend.app.services.usage_tracker import discard_session
  7549. async with async_session() as db:
  7550. await discard_session(db, printer_id)
  7551. except Exception as e:
  7552. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  7553. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  7554. # A partial run's cost from the Spoolman spools it was charged to; the
  7555. # built-in inventory's comes in usage_results.
  7556. spoolman_run_cost: float | None = None
  7557. if archive_id:
  7558. if data.get("status") == "completed":
  7559. try:
  7560. await _report_spoolman_usage(printer_id, archive_id)
  7561. log_timing("Spoolman usage report")
  7562. except Exception as e:
  7563. logger.warning("Spoolman usage reporting failed: %s", e)
  7564. else:
  7565. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  7566. try:
  7567. async with async_session() as db:
  7568. spoolman_run_cost = await _cleanup_spoolman_tracking(
  7569. printer_id,
  7570. archive_id,
  7571. db,
  7572. last_layer_num=data.get("last_layer_num"),
  7573. last_progress=data.get("last_progress"),
  7574. )
  7575. except Exception as e:
  7576. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  7577. await _release_archived_spoolman_slots(printer_id)
  7578. log_timing("Filament usage tracking")
  7579. if not archive_id:
  7580. # The printer's own calibration run has no archive by design, so this
  7581. # arrives here every time one finishes. Returning before the no-archive
  7582. # notification keeps a calibration from being announced as a finished
  7583. # print. Everything above this point has already run — the plate-clear
  7584. # gate, the queue reconciliation, the SD-card cleanup — so only the
  7585. # notification is skipped.
  7586. if is_internal_printer_job(filename, subtask_name):
  7587. logger.info(
  7588. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  7589. filename,
  7590. subtask_name,
  7591. )
  7592. return
  7593. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  7594. # Still send print-complete/failed/stopped notifications even without an archive.
  7595. # Try to enrich with queue/library-file data so user-specific emails work too.
  7596. async def _notify_no_archive():
  7597. try:
  7598. async with async_session() as db:
  7599. from backend.app.models.library import LibraryFile
  7600. from backend.app.models.print_queue import PrintQueueItem
  7601. from backend.app.models.printer import Printer
  7602. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7603. printer_obj = result.scalar_one_or_none()
  7604. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  7605. # Only the queue item this completion itself closed (the
  7606. # reconciliation above, which checks the run belongs to it).
  7607. # A print started outside Bambuddy closed none, and must not
  7608. # borrow an earlier job's owner, email or times.
  7609. no_archive_data: dict | None = None
  7610. try:
  7611. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  7612. if queue_item:
  7613. no_archive_data = {"created_by_id": queue_item.created_by_id}
  7614. # How long it really ran, as the archive path reports it (#1198).
  7615. started = to_naive_utc(queue_item.started_at)
  7616. ended = to_naive_utc(queue_item.completed_at)
  7617. # Not for a completion reconciled at reconnect: it
  7618. # ended at an unknown time while the printer was
  7619. # offline, and "now" is the reconnect (DB-C9).
  7620. if (
  7621. not data.get("_reconciled")
  7622. and started
  7623. and ended
  7624. and (ended - started).total_seconds() > 0
  7625. ):
  7626. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  7627. # Estimated time: the queue item caches it from its
  7628. # archive or library file; otherwise read the library
  7629. # file's metadata (LibraryFile has no column for it).
  7630. if queue_item.print_time_seconds:
  7631. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  7632. elif queue_item.library_file_id:
  7633. lib_result = await db.execute(
  7634. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  7635. )
  7636. lib_file = lib_result.scalar_one_or_none()
  7637. estimate = (
  7638. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  7639. )
  7640. if estimate:
  7641. no_archive_data["print_time_seconds"] = estimate
  7642. except Exception as lookup_err:
  7643. logger.debug(
  7644. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  7645. )
  7646. # Enrich with usage tracker results (captured in enclosing scope)
  7647. if usage_results:
  7648. if no_archive_data is None:
  7649. no_archive_data = {}
  7650. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7651. if total_from_usage > 0:
  7652. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7653. no_archive_data["usage_results"] = usage_results
  7654. # Try MQTT remaining_time for print duration when no queue/library data
  7655. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  7656. mqtt_remaining = data.get("remaining_time")
  7657. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  7658. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  7659. ps = data.get("status", "completed")
  7660. logger.info(
  7661. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  7662. )
  7663. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7664. await notification_service.on_print_complete(
  7665. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  7666. )
  7667. else:
  7668. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7669. # Send user-specific email if we have a created_by_id
  7670. if no_archive_data and no_archive_data.get("created_by_id"):
  7671. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7672. await _dispatch_user_print_email(
  7673. ps,
  7674. no_archive_data["created_by_id"],
  7675. p_name,
  7676. raw_filename,
  7677. db,
  7678. )
  7679. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  7680. except Exception as e:
  7681. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  7682. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  7683. return
  7684. log_timing("Archive lookup")
  7685. # Update archive status
  7686. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  7687. try:
  7688. async with async_session() as db:
  7689. service = ArchiveService(db)
  7690. status = data.get("status", "completed")
  7691. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  7692. if hms_errors:
  7693. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  7694. failure_reason = derive_failure_reason(status, hms_errors)
  7695. if data.get("_reconciled"):
  7696. # A reconciled completion closes out a stale archive at
  7697. # reconnect — it is not a user action, so don't mislabel it
  7698. # "userCancelled". It shares the stale-cleanup path's key
  7699. # (issue #2974) and records that the real end time is unknown,
  7700. # which is also why its logged duration is 0 (#2592).
  7701. failure_reason = "noStatusUpdate"
  7702. elif data.get("_kill_switch"):
  7703. # Not the user's cancel: the kill switch stopped a print that did
  7704. # not come from Bambuddy.
  7705. failure_reason = "killSwitch"
  7706. if failure_reason:
  7707. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  7708. elif status == "failed" and hms_errors:
  7709. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  7710. await service.update_archive_status(
  7711. archive_id,
  7712. status=status,
  7713. completed_at=(
  7714. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  7715. ),
  7716. failure_reason=failure_reason,
  7717. )
  7718. logger.info(
  7719. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  7720. )
  7721. await ws_manager.send_archive_updated(
  7722. {
  7723. "id": archive_id,
  7724. "status": status,
  7725. }
  7726. )
  7727. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  7728. # MQTT relay - publish archive updated
  7729. try:
  7730. await mqtt_relay.on_archive_updated(
  7731. archive_id=archive_id,
  7732. print_name=filename or subtask_name,
  7733. status=status,
  7734. )
  7735. except Exception:
  7736. pass # Don't fail if MQTT fails
  7737. except Exception as e:
  7738. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  7739. # Continue with other operations even if archive update fails
  7740. log_timing("Archive status update")
  7741. # Apply finance wallet charge or release reservations once. For all partial
  7742. # terminal states (failed, aborted at the printer display, or cancelled via
  7743. # Bambuddy) use this run's measured spool delta, falling back to the last
  7744. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  7745. # estimate and therefore cannot represent an interrupted run.
  7746. try:
  7747. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  7748. async with async_session() as db:
  7749. from backend.app.models.archive import PrintArchive
  7750. from backend.app.services.finance_billing import apply_print_charge_for_archive
  7751. archive = await db.get(PrintArchive, archive_id)
  7752. if archive and billing_run_id is None:
  7753. billing_run_id = getattr(archive, "billing_run_id", None)
  7754. if archive and archive.created_by_id is None and _print_user_info:
  7755. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  7756. await db.flush()
  7757. run_status = data.get("status", "completed")
  7758. last_progress = data.get("last_progress")
  7759. if last_progress is None:
  7760. last_progress = data.get("progress")
  7761. actual_run_grams = _compute_run_filament_grams(
  7762. run_status,
  7763. billing_planned_grams,
  7764. last_progress,
  7765. usage_results,
  7766. )
  7767. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  7768. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  7769. charged = await apply_print_charge_for_archive(
  7770. db,
  7771. archive_id,
  7772. charged_user_id=billing_user_id,
  7773. cost_center_id=(
  7774. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  7775. ),
  7776. print_queue_id=queue_item_id,
  7777. print_run_id=billing_run_id,
  7778. base_cost_override=billing_base_cost,
  7779. filament_usage=filament_usage,
  7780. )
  7781. await db.commit()
  7782. if charged:
  7783. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  7784. except Exception as e:
  7785. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  7786. printer_info = printer_manager.get_printer(printer_id)
  7787. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7788. billing_filename = filename or subtask_name or "Unknown"
  7789. billing_error = str(e)
  7790. try:
  7791. await ws_manager.broadcast(
  7792. {
  7793. "type": "billing_charge_failed",
  7794. "printer_id": printer_id,
  7795. "printer_name": billing_printer_name,
  7796. "filename": billing_filename,
  7797. "archive_id": archive_id,
  7798. }
  7799. )
  7800. except Exception as notification_error:
  7801. logger.error(
  7802. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  7803. archive_id,
  7804. notification_error,
  7805. )
  7806. async def _notify_billing_charge_failed() -> None:
  7807. try:
  7808. async with async_session() as notification_db:
  7809. await notification_service.on_billing_charge_failed(
  7810. printer_id,
  7811. billing_printer_name,
  7812. billing_filename,
  7813. archive_id,
  7814. billing_error,
  7815. notification_db,
  7816. )
  7817. except Exception as provider_error:
  7818. logger.error(
  7819. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  7820. archive_id,
  7821. provider_error,
  7822. exc_info=True,
  7823. )
  7824. spawn_background_task(
  7825. _notify_billing_charge_failed(),
  7826. name=f"billing-charge-failed-{archive_id}",
  7827. )
  7828. log_timing("Finance charge update")
  7829. # Write independent print log entry (separate table, never touches archives)
  7830. try:
  7831. async with async_session() as db:
  7832. from backend.app.models.archive import PrintArchive
  7833. from backend.app.services.print_log import record_archive_wear, write_log_entry
  7834. archive = await db.get(PrintArchive, archive_id)
  7835. if archive:
  7836. # Back-fill created_by_id on reprint (#730): reprint reuses the
  7837. # source archive row rather than creating a new one, so an
  7838. # archive that was auto-created from a printer-initiated
  7839. # print (created_by_id=NULL) would otherwise stay unattributed
  7840. # forever. When we have a print-session user AND the archive
  7841. # has no attribution yet, credit the current user. Never
  7842. # overwrite an existing attribution — the original uploader
  7843. # keeps ownership.
  7844. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  7845. if archive.created_by_id is None and _print_user_id is not None:
  7846. archive.created_by_id = _print_user_id
  7847. p_info = printer_manager.get_printer(printer_id)
  7848. # Per-run actuals — written to PrintLogEntry so stats reflect
  7849. # what THIS print actually used, not the source archive's
  7850. # first-run values (#1378). Helper handles the partial-print
  7851. # math (failed / cancelled / stopped get scaled to progress
  7852. # or to tracked spool deltas).
  7853. _run_status = data.get("status", "completed")
  7854. # #2614: scope the per-run estimate to the printed plate. For a
  7855. # multi-plate 3MF dispatched one plate at a time, the archive's
  7856. # filament/cost are the whole-file totals; the PrintLogEntry must
  7857. # reflect only this plate. No effect on single-plate archives (the
  7858. # plate estimate equals the whole-file value) or on the tracker
  7859. # path (measured spool deltas win in _compute_run_filament_grams).
  7860. _est_full_path = (
  7861. app_settings.base_dir / archive.file_path if archive.file_path else None
  7862. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7863. # The plate that printed, as billing reads it: a reprint of
  7864. # another plate must not log the archive's first plate.
  7865. _est_grams, _est_cost = _plate_scoped_run_estimate(
  7866. archive,
  7867. _est_full_path,
  7868. billing_plate_id if billing_plate_id is not None else notify_plate_id,
  7869. )
  7870. _run_grams = _compute_run_filament_grams(
  7871. _run_status,
  7872. _est_grams,
  7873. data.get("last_progress", data.get("progress")),
  7874. usage_results,
  7875. )
  7876. # Per-run cost — prefer usage_results sum. For partial prints
  7877. # we deliberately skip the topup-to-estimate logic in
  7878. # usage_tracker (which assumes the print completed); the raw
  7879. # tracked-spool sum is closer to what THIS run actually cost.
  7880. _run_cost: float | None = None
  7881. if usage_results:
  7882. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  7883. if _run_cost is None and _run_status != "completed":
  7884. _run_cost = spoolman_run_cost
  7885. if _run_cost is None and _run_status == "completed":
  7886. _run_cost = _est_cost
  7887. from backend.app.models.printer import Printer as _Printer
  7888. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  7889. run_entry = await write_log_entry(
  7890. db,
  7891. archive_id=archive.id,
  7892. # Captured by _update_queue_status above; None for
  7893. # printer-initiated prints with no queue row. Batch
  7894. # cost/energy roll-up joins on it (#342).
  7895. queue_item_id=queue_item_id,
  7896. status=_run_status,
  7897. print_name=archive.print_name,
  7898. printer_name=p_info.name if p_info else None,
  7899. printer_id=printer_id,
  7900. started_at=archive.started_at,
  7901. completed_at=archive.completed_at,
  7902. filament_type=archive.filament_type,
  7903. filament_color=archive.filament_color,
  7904. filament_used_grams=_run_grams,
  7905. cost=_run_cost,
  7906. wear_cost_per_hour=_wear_rate,
  7907. failure_reason=archive.failure_reason,
  7908. thumbnail_path=archive.thumbnail_path,
  7909. created_by_id=archive.created_by_id,
  7910. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  7911. # Reconciled completions have an unknown real end time —
  7912. # log 0 duration instead of the whole disconnect gap (#2592).
  7913. reconciled=bool(data.get("_reconciled")),
  7914. )
  7915. await record_archive_wear(db, archive, run_entry)
  7916. await db.commit()
  7917. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  7918. except Exception as e:
  7919. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  7920. log_timing("Print log entry")
  7921. # Run slow operations as background tasks to avoid blocking the event loop
  7922. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  7923. async def _background_energy_calculation():
  7924. """Calculate and save energy usage in background.
  7925. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  7926. backend restart no longer loses per-print energy data).
  7927. """
  7928. try:
  7929. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  7930. async with async_session() as db:
  7931. from backend.app.models.archive import PrintArchive
  7932. archive = await db.get(PrintArchive, archive_id)
  7933. if archive is None:
  7934. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  7935. return
  7936. starting_kwh = archive.energy_start_kwh
  7937. if starting_kwh is None:
  7938. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  7939. return
  7940. candidates = await energy_plug_candidates(db, printer_id)
  7941. if not candidates:
  7942. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  7943. return
  7944. # Same ordering as the start reading, so the delta below is
  7945. # against the counter that produced `starting_kwh` (#2859).
  7946. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  7947. if selected is None:
  7948. logger.warning(
  7949. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  7950. printer_id,
  7951. ", ".join(plug.name for plug in candidates),
  7952. )
  7953. return
  7954. plug, energy = selected
  7955. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  7956. energy_used = round(energy["total"] - starting_kwh, 4)
  7957. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  7958. if energy_used < 0:
  7959. logger.warning(
  7960. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  7961. archive_id,
  7962. starting_kwh,
  7963. energy["total"],
  7964. )
  7965. return
  7966. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  7967. # Each hour of the print at the price of that hour (#1251). If
  7968. # that fails, the last price known, as before, rather than no
  7969. # energy at all. Read first: the session may be unusable after.
  7970. last_price = await stored_price(db)
  7971. try:
  7972. energy_cost_value = round(
  7973. await print_energy_cost(
  7974. db,
  7975. plug_id=archive.energy_start_plug_id,
  7976. start_at=archive.energy_start_at,
  7977. start_kwh=starting_kwh,
  7978. start_price=archive.energy_start_price,
  7979. end_kwh=energy["total"],
  7980. end_plug_id=plug.id,
  7981. price_now=await current_price(db),
  7982. ),
  7983. 3,
  7984. )
  7985. except Exception as e:
  7986. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  7987. energy_cost_value = round(energy_used * last_price, 3)
  7988. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  7989. # reprint doesn't visually clobber the source archive's energy data
  7990. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  7991. from sqlalchemy import func
  7992. from backend.app.models.print_log import PrintLogEntry
  7993. existing_runs = await db.scalar(
  7994. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  7995. )
  7996. if (existing_runs or 0) <= 1:
  7997. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  7998. # we just wrote for THIS print. Either way it's the first run.
  7999. archive.energy_kwh = energy_used
  8000. archive.energy_cost = energy_cost_value
  8001. # Backfill the latest PrintLogEntry for this archive with energy
  8002. # (write_log_entry above ran before this background task completed,
  8003. # so energy fields are still NULL on that row).
  8004. latest_run = await db.execute(
  8005. select(PrintLogEntry)
  8006. .where(PrintLogEntry.archive_id == archive_id)
  8007. .order_by(PrintLogEntry.id.desc())
  8008. .limit(1)
  8009. )
  8010. run_row = latest_run.scalar_one_or_none()
  8011. if run_row is not None:
  8012. run_row.energy_kwh = energy_used
  8013. run_row.energy_cost = energy_cost_value
  8014. await db.commit()
  8015. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  8016. except Exception as e:
  8017. logger.warning("[ENERGY-BG] Failed: %s", e)
  8018. async def _background_finish_photo() -> str | None:
  8019. """Capture finish photo in background. Returns photo filename if captured."""
  8020. # #2547: set once this function has raised the plate itself (the
  8021. # timelapse path, where the moment producer returned without doing it).
  8022. # Declared out here so the `finally` can lower it again no matter where
  8023. # the capture below fails.
  8024. plate_restored_z: float | None = None
  8025. try:
  8026. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  8027. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  8028. # Read phase: settings + printer + archive in a short session, released
  8029. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  8030. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  8031. # tens of seconds; holding this session across it pinned one pooled
  8032. # connection idle-in-transaction per finishing print (issue #2572).
  8033. async with async_session() as db:
  8034. from backend.app.api.routes.settings import get_setting
  8035. from backend.app.models.archive import PrintArchive
  8036. from backend.app.models.printer import Printer
  8037. capture_enabled = await get_setting(db, "capture_finish_photo")
  8038. if capture_enabled is not None and capture_enabled.lower() != "true":
  8039. return None
  8040. if not archive_id:
  8041. return None
  8042. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  8043. archive = (
  8044. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8045. ).scalar_one_or_none()
  8046. if not printer or not archive:
  8047. return None
  8048. import uuid
  8049. from datetime import datetime
  8050. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  8051. if not archive.file_path:
  8052. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  8053. archive_dir = resolve_archive_dir(archive)
  8054. photo_filename = None
  8055. # Prefer the timelapse last-frame source when a timelapse was
  8056. # recording — it captures the moment after the toolhead parks
  8057. # but before the bed drops, which the live-camera grab below
  8058. # would miss (#1397). Skipped for external cameras (those have
  8059. # their own framing and don't see a Bambu timelapse). Only
  8060. # runs when the USER explicitly enabled timelapse for this
  8061. # print — #1721 removed Bambuddy's force-on at dispatch
  8062. # because it caused per-layer nozzle parking on Smooth-mode
  8063. # slicer profiles.
  8064. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  8065. printer.external_camera_enabled and printer.external_camera_url
  8066. )
  8067. timelapse_still_pending = False
  8068. if prefer_timelapse_source:
  8069. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  8070. archive_id=archive_id,
  8071. archive_dir=archive_dir,
  8072. rotation=getattr(printer, "camera_rotation", 0),
  8073. )
  8074. # #1721: replacement framing path — on_finish_photo_moment
  8075. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  8076. # parked, bed not yet dropped) and cached the JPEG bytes in
  8077. # _stage22_finish_frames. Consume them now so the saved photo
  8078. # has the better framing instead of the post-bed-drop angle
  8079. # the live-camera fallback below would give.
  8080. if not photo_filename:
  8081. # #1790: on the FINISH-state fallback path the producer
  8082. # task is dispatched back-to-back with this consumer, so
  8083. # a bare pop would race past with an empty result and
  8084. # the RTSP fallback below would collide with the
  8085. # producer's still-in-flight grab (single-client RTSP
  8086. # on Bambu printers). Wait for the producer to finish
  8087. # or give up before touching the cache.
  8088. #
  8089. # #2547: 20s was enough when the producer only ever grabbed a
  8090. # frame. It now also raises the plate first, which costs the
  8091. # settle window before the grab even starts — so the budget has
  8092. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  8093. # under the notification's own photo wait below.
  8094. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  8095. if in_flight is not None:
  8096. try:
  8097. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  8098. except TimeoutError:
  8099. logger.warning(
  8100. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  8101. printer_id,
  8102. )
  8103. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  8104. if cached_frame:
  8105. # Already rotated by the producer (#2708) — rotating again
  8106. # here would undo the fix on the banked-frame path, whose
  8107. # bytes reach the cache having been rotated once already.
  8108. photos_dir = archive_dir / "photos"
  8109. photos_dir.mkdir(parents=True, exist_ok=True)
  8110. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8111. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8112. photo_path = photos_dir / photo_filename
  8113. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  8114. logger.info(
  8115. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  8116. photo_filename,
  8117. len(cached_frame),
  8118. )
  8119. # #2547: the timelapse path reaches the live grab below whenever the
  8120. # video hasn't landed in time — the documented usual outcome on
  8121. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  8122. # returned early for those prints without raising the plate, so
  8123. # without this the photo that actually ships in the notification is
  8124. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  8125. # asked us to fix. The archive still gets the better video frame
  8126. # later; this is about the image the user is sent.
  8127. #
  8128. # Gated on `timelapse_was_active` precisely because that is the
  8129. # condition under which the producer skipped. On every other path it
  8130. # has already raised and lowered the plate, and repeating that here
  8131. # would be a second pointless round trip.
  8132. if (
  8133. not photo_filename
  8134. and data.get("timelapse_was_active")
  8135. and not print_dispatch_context.end_gcode_injected(printer_id)
  8136. ):
  8137. try:
  8138. async with async_session() as db:
  8139. from backend.app.api.routes.settings import get_setting
  8140. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  8141. if restore_setting is None or restore_setting.lower() == "true":
  8142. max_z = await _max_z_for_current_print(
  8143. printer_id, data, logger, bound_archive_id, notify_plate_id
  8144. )
  8145. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  8146. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  8147. plate_restored_z = max_z
  8148. except Exception as e:
  8149. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  8150. # Fallback chain: external camera → buffered live frame →
  8151. # fresh RTSP capture. Only runs if the timelapse path above
  8152. # didn't already produce a photo.
  8153. # Chamber light for the live capture below (#1655).
  8154. async with camera_light(printer if not photo_filename else None):
  8155. if not photo_filename:
  8156. if printer.external_camera_enabled and printer.external_camera_url:
  8157. logger.info("[PHOTO-BG] Using external camera")
  8158. from backend.app.api.routes.camera import live_frame_for_capture
  8159. from backend.app.services.external_camera import capture_frame
  8160. # #2707: the second half of the finish-photo failure — the
  8161. # pre-capture and this fallback both collided with the live
  8162. # view. None here continues down the fallback chain.
  8163. defer, buffered = live_frame_for_capture(printer_id)
  8164. if defer:
  8165. frame_data = buffered
  8166. else:
  8167. frame_data = await capture_frame(
  8168. printer.external_camera_url,
  8169. printer.external_camera_type or "mjpeg",
  8170. snapshot_url=printer.external_camera_snapshot_url,
  8171. )
  8172. if frame_data:
  8173. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  8174. photos_dir = archive_dir / "photos"
  8175. photos_dir.mkdir(parents=True, exist_ok=True)
  8176. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8177. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8178. photo_path = photos_dir / photo_filename
  8179. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  8180. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  8181. else:
  8182. # Check if camera stream is active - use buffered frame to avoid freeze
  8183. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  8184. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  8185. active_chamber_for_printer = [
  8186. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  8187. ]
  8188. buffered_frame = get_buffered_frame(printer_id)
  8189. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  8190. # Use frame from active stream
  8191. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  8192. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  8193. photos_dir = archive_dir / "photos"
  8194. photos_dir.mkdir(parents=True, exist_ok=True)
  8195. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8196. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8197. photo_path = photos_dir / photo_filename
  8198. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  8199. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  8200. else:
  8201. # No active stream - capture new frame
  8202. from backend.app.services.camera import capture_finish_photo
  8203. photo_filename = await capture_finish_photo(
  8204. printer_id=printer_id,
  8205. ip_address=printer.ip_address,
  8206. access_code=printer.access_code,
  8207. model=printer.model,
  8208. archive_dir=archive_dir,
  8209. rotation=getattr(printer, "camera_rotation", 0),
  8210. )
  8211. # Write phase: attach the photo in a fresh short-lived session.
  8212. if photo_filename:
  8213. async with async_session() as db:
  8214. from backend.app.models.archive import PrintArchive
  8215. arch = await db.get(PrintArchive, archive_id)
  8216. if arch is not None:
  8217. photos = arch.photos or []
  8218. photos.append(photo_filename)
  8219. arch.photos = photos
  8220. await db.commit()
  8221. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  8222. # The short wait above is bounded so a slow printer can't hold up
  8223. # the print-complete notification, which is what the caller is
  8224. # blocking on. When it ran out with the video still on its way,
  8225. # keep waiting off to the side and add the better frame to the
  8226. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  8227. # users, whose videos routinely take minutes to transfer, never get
  8228. # the pre-bed-drop framing this path exists to provide.
  8229. #
  8230. # Spawned here rather than at the point the wait gave up: both this
  8231. # function and the upgrade do a read-modify-write on `photos`, and
  8232. # the live-camera fallback above can take tens of seconds. Starting
  8233. # the upgrade before that write means the two can interleave and one
  8234. # silently drops the other's entry, leaving a JPEG on disk that the
  8235. # gallery never lists.
  8236. if timelapse_still_pending:
  8237. spawn_background_task(
  8238. _upgrade_finish_photo_from_timelapse(
  8239. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  8240. ),
  8241. name=f"finish-photo-upgrade-{archive_id}",
  8242. )
  8243. return photo_filename
  8244. except Exception as e:
  8245. logger.warning("[PHOTO-BG] Failed: %s", e)
  8246. return None
  8247. finally:
  8248. # #2547: we raised the plate, so we owe the move back down — even if
  8249. # the capture in between threw. Otherwise the user finds the print
  8250. # pinned under the nozzle.
  8251. if plate_restored_z is not None:
  8252. try:
  8253. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  8254. except Exception as e:
  8255. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  8256. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  8257. # Photo capture task - result will be used by notifications
  8258. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  8259. log_timing("Background tasks scheduled (energy, photo)")
  8260. # Also run smart plug, notifications, and maintenance as background tasks
  8261. print_status = data.get("status", "completed")
  8262. async def _background_smart_plug():
  8263. """Handle smart plug automation in background."""
  8264. try:
  8265. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  8266. async with async_session() as db:
  8267. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  8268. logger.info("[AUTO-OFF-BG] Completed")
  8269. except Exception as e:
  8270. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  8271. async def _background_notifications(finish_photo_filename: str | None = None):
  8272. """Send print complete notifications in background."""
  8273. try:
  8274. logger.info(
  8275. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  8276. )
  8277. async with async_session() as db:
  8278. from backend.app.models.archive import PrintArchive
  8279. from backend.app.models.printer import Printer
  8280. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8281. printer = result.scalar_one_or_none()
  8282. printer_name = printer.name if printer else f"Printer {printer_id}"
  8283. archive_data = None
  8284. if archive_id:
  8285. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8286. archive = archive_result.scalar_one_or_none()
  8287. if archive:
  8288. # Actual elapsed time from started_at/completed_at when both are
  8289. # populated (every terminal status sets completed_at after #1198).
  8290. # Falls back to None so the notification path can decide whether to
  8291. # render the slicer estimate as a last resort.
  8292. actual_time_seconds = None
  8293. # Unknown for a completion reconciled at reconnect: the
  8294. # print ended while the printer was offline and
  8295. # completed_at is the reconnect, so the gap would read
  8296. # as the duration -- 14 h for a night offline (DB-C9).
  8297. if archive.started_at and archive.completed_at and not data.get("_reconciled"):
  8298. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  8299. if elapsed > 0:
  8300. actual_time_seconds = int(elapsed)
  8301. archive_data = {
  8302. "print_time_seconds": archive.print_time_seconds,
  8303. "actual_time_seconds": actual_time_seconds,
  8304. "actual_filament_grams": archive.filament_used_grams,
  8305. "failure_reason": archive.failure_reason,
  8306. "created_by_id": archive.created_by_id,
  8307. }
  8308. # Scale filament usage for partial prints
  8309. if print_status != "completed" and archive.filament_used_grams:
  8310. progress = data.get("progress") or 0
  8311. scale = _partial_progress_scale(progress)
  8312. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  8313. archive_data["progress"] = progress
  8314. # Pass per-slot data from archive.extra_data
  8315. if archive.extra_data and archive.extra_data.get("filament_slots"):
  8316. slots = archive.extra_data["filament_slots"]
  8317. if print_status != "completed":
  8318. scale = _partial_progress_scale(data.get("progress"))
  8319. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  8320. archive_data["filament_slots"] = slots
  8321. # Scope project-summed totals down to the plate that was
  8322. # actually printed — see _scope_notification_archive_data_to_plate
  8323. # for the why (#1785).
  8324. archive_data = _scope_notification_archive_data_to_plate(
  8325. archive_data,
  8326. archive.file_path,
  8327. notify_plate_id,
  8328. print_status,
  8329. data.get("progress"),
  8330. app_settings.base_dir,
  8331. )
  8332. # Enrich filament_grams from usage_results when archive has no 3MF data
  8333. if not archive_data.get("actual_filament_grams") and usage_results:
  8334. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8335. if total_from_usage > 0:
  8336. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8337. # Pass usage tracker results for AMS slot info in notifications
  8338. if usage_results:
  8339. archive_data["usage_results"] = usage_results
  8340. # Add finish photo URL and image bytes if available
  8341. if finish_photo_filename:
  8342. photo_url, photo_bytes = await _finish_photo_for_notification(
  8343. db, archive, archive_id, finish_photo_filename
  8344. )
  8345. if photo_url:
  8346. archive_data["finish_photo_url"] = photo_url
  8347. if photo_bytes:
  8348. archive_data["image_data"] = photo_bytes
  8349. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8350. await notification_service.on_print_complete(
  8351. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  8352. )
  8353. else:
  8354. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8355. # Post-print outcome confirmation (#1898). Runs in this
  8356. # background task so the finish photo fetched above rides
  8357. # along with the prompt.
  8358. if print_status == "completed" and archive_id:
  8359. await _dispatch_outcome_confirmation_safely(
  8360. db, printer_id, printer_name, data, archive_id, archive_data
  8361. )
  8362. # Send user-specific email notification
  8363. if archive_data:
  8364. created_by_id = archive_data.get("created_by_id")
  8365. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8366. await _dispatch_user_print_email(
  8367. print_status,
  8368. created_by_id,
  8369. printer_name,
  8370. raw_filename,
  8371. db,
  8372. image_data=archive_data.get("image_data"),
  8373. finish_photo_url=archive_data.get("finish_photo_url"),
  8374. )
  8375. logger.info("[NOTIFY-BG] Completed")
  8376. except Exception as e:
  8377. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  8378. async def _background_maintenance_check():
  8379. """Check for maintenance due in background."""
  8380. if print_status != "completed":
  8381. return
  8382. try:
  8383. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  8384. async with async_session() as db:
  8385. from backend.app.models.printer import Printer
  8386. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8387. printer = result.scalar_one_or_none()
  8388. printer_name = printer.name if printer else f"Printer {printer_id}"
  8389. await ensure_default_types(db)
  8390. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  8391. attention = [
  8392. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  8393. ]
  8394. items_needing_attention = [
  8395. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  8396. for item in attention
  8397. ]
  8398. if items_needing_attention:
  8399. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  8400. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  8401. # MQTT relay - publish maintenance alerts
  8402. for item in attention:
  8403. current_value, threshold, unit = maintenance_alert_values(item)
  8404. try:
  8405. await mqtt_relay.on_maintenance_alert(
  8406. printer_id=printer_id,
  8407. printer_name=printer_name,
  8408. maintenance_type=item.maintenance_type_name,
  8409. current_value=current_value,
  8410. threshold=threshold,
  8411. unit=unit,
  8412. )
  8413. except Exception:
  8414. pass # Don't fail if MQTT fails
  8415. else:
  8416. logger.info("[MAINT-BG] Completed (no items need attention)")
  8417. except Exception as e:
  8418. logger.warning("[MAINT-BG] Failed: %s", e)
  8419. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  8420. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  8421. # Notification task waits for photo capture to complete first (with timeout).
  8422. # When a timelapse was recording, photo sourcing polls the per-print
  8423. # timelapse for up to 60s (#1397) — extend the budget so the notification
  8424. # carries the correct bed-up photo instead of falling through to the
  8425. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  8426. #
  8427. # #2547: both budgets now have to cover a plate restore as well.
  8428. #
  8429. # Without timelapse, the wait is on the moment producer, which raises the
  8430. # plate before its grab — so this has to outlast that producer's own budget.
  8431. #
  8432. # With timelapse, the capture polls up to
  8433. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  8434. # falls back to a live grab, which is the case that raises the plate. At the
  8435. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  8436. # restore would have moved the plate for a photo nobody waited for.
  8437. photo_wait_timeout = (
  8438. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  8439. if data.get("timelapse_was_active")
  8440. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  8441. )
  8442. async def _photo_then_notify():
  8443. """Wait for photo capture, then send notification with photo URL."""
  8444. finish_photo = None
  8445. try:
  8446. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  8447. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  8448. except TimeoutError:
  8449. logger.warning(
  8450. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  8451. photo_wait_timeout,
  8452. )
  8453. except Exception as e:
  8454. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  8455. try:
  8456. await _background_notifications(finish_photo)
  8457. except Exception as e:
  8458. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  8459. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  8460. # Stitch external camera layer timelapse if session was active
  8461. print_status = data.get("status", "completed")
  8462. async def _background_layer_timelapse():
  8463. """Stitch layer timelapse and attach to archive."""
  8464. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  8465. try:
  8466. if print_status == "completed":
  8467. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  8468. # The run the frames belong to, read before the stitch: it can
  8469. # take long enough for the archive to start printing again.
  8470. run_started_at = None
  8471. if archive_id:
  8472. async with async_session() as db:
  8473. run_archive = await ArchiveService(db).get_archive(archive_id)
  8474. run_started_at = run_archive.started_at if run_archive else None
  8475. timelapse_path = await tl_complete(printer_id)
  8476. if timelapse_path and archive_id:
  8477. await _attach_layer_timelapse(archive_id, timelapse_path, notify_plate_id, run_started_at)
  8478. elif timelapse_path:
  8479. # Timelapse created but no archive - just clean up
  8480. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  8481. else:
  8482. # Print failed or cancelled - cancel timelapse session
  8483. cancel_session(printer_id)
  8484. logger.info(
  8485. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  8486. )
  8487. except Exception as e:
  8488. logger.warning("[LAYER-TL] Failed: %s", e)
  8489. # A completed print's session left _active_sessions when its stitch
  8490. # began: the one there now belongs to the next print, which may have
  8491. # started during the stitch, and must not lose its frames.
  8492. if print_status != "completed":
  8493. try:
  8494. cancel_session(printer_id)
  8495. except Exception:
  8496. pass # Best-effort timelapse session cancellation on error
  8497. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  8498. log_timing("All background tasks scheduled")
  8499. # Auto-scan for timelapse if recording was active during the print
  8500. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  8501. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  8502. # Schedule timelapse scan as background task with retries
  8503. # The printer needs time to encode the video after print completion
  8504. baseline = _timelapse_baselines.pop(printer_id, None)
  8505. spawn_background_task(
  8506. _scan_for_timelapse_with_retries(archive_id, baseline, plate_id=notify_plate_id),
  8507. name=f"scan-timelapse-{archive_id}",
  8508. )
  8509. log_timing("Timelapse scan scheduled")
  8510. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  8511. # AMS sensor history recording
  8512. _ams_history_task: asyncio.Task | None = None
  8513. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  8514. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  8515. def _retention_days(stored: str | None, default: int) -> int:
  8516. """A history retention setting as days to keep: at least 1, the default
  8517. when unset or unreadable. A stored 0 or less (the API took one before it
  8518. had a minimum) would put the cutoff at now and delete all history."""
  8519. try:
  8520. return max(1, int(stored)) if stored is not None else default
  8521. except (TypeError, ValueError):
  8522. return default
  8523. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  8524. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  8525. _ams_alarm_cooldown: dict[str, datetime] = {}
  8526. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  8527. # (printer_id, ams_id) already reported as sending the drop index and no
  8528. # percentage. Logged once each so a supported printer that turns out to do this
  8529. # shows up in a support bundle rather than as a user wondering where the
  8530. # humidity reading went -- see the note at the read site below (#3140).
  8531. _ams_index_only_logged: set[tuple[int, int]] = set()
  8532. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  8533. """Temperature at which the AMS alarm fires, falling back to the display band.
  8534. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  8535. when a notification was sent as well, which is why a room above it made the
  8536. alarm fire once an hour for as long as the weather lasted -- and the only way
  8537. to stop that was to raise the display band and lose the colour that says the
  8538. unit is warm (#2905).
  8539. Unset resolves to the fair threshold, so an install that never sets one is
  8540. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  8541. so that arrives here as a string and is handled by the same branch as any
  8542. other unparseable value -- there is no separate sentinel to keep in sync.
  8543. A non-positive value is refused rather than honoured: zero would alarm
  8544. permanently, and it is far more likely to be a cleared field than a
  8545. deliberate choice.
  8546. """
  8547. if raw_alarm_value is None:
  8548. return fair_threshold
  8549. try:
  8550. value = float(raw_alarm_value)
  8551. except (TypeError, ValueError):
  8552. return fair_threshold
  8553. if not math.isfinite(value) or value <= 0:
  8554. return fair_threshold
  8555. return value
  8556. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  8557. # through a cycle and the cool-down after it (#1802). Stored in the settings
  8558. # table rather than alongside _ams_alarm_cooldown above, because a restart
  8559. # partway through a cool-down would otherwise resume alarming about heat the
  8560. # user asked for — the same internal-timestamp-row pattern as
  8561. # support.py's debug_logging_enabled_at.
  8562. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  8563. # Upper bound on that suppression. The latch normally clears as soon as the unit
  8564. # reads at or below the threshold; see utils.ams_drying for why this cap only
  8565. # matters when it never does.
  8566. AMS_DRYING_GRACE_MINUTES = 120
  8567. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  8568. """Read the persisted per-AMS drying latch, dropping entries out of window.
  8569. Anything older than the grace cap would expire on its next visit anyway, so
  8570. discarding it here costs nothing and stops rows for deleted printers from
  8571. accumulating.
  8572. Stamps ahead of now get two defences, because a box whose clock jumps
  8573. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  8574. ones are discarded outright, and the rest are clamped to now. Without the
  8575. clamp the cap would measure from a moment that has not happened yet and hold
  8576. the alarm quiet for the skew on top of the cap. One unnecessary notification
  8577. after a clock jump is a far better failure than an alarm silently disabled
  8578. for hours.
  8579. """
  8580. from backend.app.models.settings import Settings
  8581. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8582. setting = result.scalar_one_or_none()
  8583. if not setting or not setting.value:
  8584. return {}
  8585. try:
  8586. raw = json.loads(setting.value)
  8587. except (ValueError, TypeError):
  8588. return {} # Corrupted row → no latch, alarms behave as they did before
  8589. if not isinstance(raw, dict):
  8590. return {}
  8591. now = datetime.now(timezone.utc)
  8592. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  8593. latch: dict[str, datetime] = {}
  8594. for key, value in raw.items():
  8595. try:
  8596. stamp = datetime.fromisoformat(str(value))
  8597. except (ValueError, TypeError):
  8598. continue
  8599. if stamp.tzinfo is None:
  8600. stamp = stamp.replace(tzinfo=timezone.utc)
  8601. if not (now - window <= stamp <= now + window):
  8602. continue
  8603. # Nothing may sit in the future: suppression is measured as now minus
  8604. # the stamp, so a stamp ahead of now would extend it by the skew on top
  8605. # of the cap. Clamping the survivors keeps the cap an actual cap.
  8606. latch[str(key)] = min(stamp, now)
  8607. return latch
  8608. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  8609. """Persist the latch, writing only when it actually changed.
  8610. Adds the session change but does not commit — the caller's own commit
  8611. carries it, so the latch lands in the same transaction as the sensor rows
  8612. that produced it.
  8613. """
  8614. from backend.app.models.settings import Settings
  8615. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  8616. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8617. setting = result.scalar_one_or_none()
  8618. if setting is None:
  8619. # Don't create the row on installs that never dry anything.
  8620. if payload != "{}":
  8621. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  8622. elif setting.value != payload:
  8623. setting.value = payload
  8624. def _ams_has_filament(ams_data: dict) -> bool:
  8625. """True if this AMS unit has at least one tray slot holding filament.
  8626. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  8627. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  8628. still report sensor readings, but those readings are ambient and not
  8629. actionable: no filament to dry, no humidity to push down. #1619 — gate
  8630. humidity/temperature alarms on this check so empty units don't generate
  8631. hourly noise. Sensor history still records regardless so the UI charts
  8632. stay continuous.
  8633. Fallback path inspects the `tray` array's `tray_type` fields for setups
  8634. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  8635. """
  8636. bits = ams_data.get("tray_exist_bits")
  8637. if isinstance(bits, str) and bits.strip():
  8638. try:
  8639. return int(bits, 16) > 0
  8640. except ValueError:
  8641. pass
  8642. trays = ams_data.get("tray")
  8643. if isinstance(trays, list):
  8644. return any(
  8645. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  8646. )
  8647. return False
  8648. async def record_ams_history():
  8649. """Background task to record AMS humidity and temperature data."""
  8650. logger = logging.getLogger(__name__)
  8651. # Wait a short time for MQTT connections to establish on startup
  8652. await asyncio.sleep(10)
  8653. while True:
  8654. try:
  8655. from backend.app.models.ams_history import AMSSensorHistory
  8656. from backend.app.models.printer import Printer
  8657. from backend.app.models.settings import Settings
  8658. async with async_session() as db:
  8659. # Get all active printers
  8660. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8661. printers = result.scalars().all()
  8662. # Get alarm thresholds from settings
  8663. humidity_threshold = 60.0 # Default: fair threshold
  8664. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  8665. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  8666. setting = result.scalar_one_or_none()
  8667. if setting:
  8668. try:
  8669. humidity_threshold = float(setting.value)
  8670. except (ValueError, TypeError):
  8671. pass # Keep default threshold if stored value is invalid
  8672. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  8673. setting = result.scalar_one_or_none()
  8674. if setting:
  8675. try:
  8676. temp_fair_threshold = float(setting.value)
  8677. except (ValueError, TypeError):
  8678. pass # Keep default threshold if stored value is invalid
  8679. # The alarm gets its own threshold, seeded from the resolved fair
  8680. # value so an install that has never set one behaves exactly as
  8681. # it did before (#2905). ams_temp_fair decides when the card turns
  8682. # amber; 35 C is a reasonable place to change a colour and not a
  8683. # reasonable place to page someone. A room above it makes the
  8684. # alarm fire once an hour for as long as the weather lasts, and
  8685. # the only way to stop it was to raise the display band and lose
  8686. # the colour that says the unit is warm.
  8687. #
  8688. # An unset value is stored as the literal "None", which the except
  8689. # below swallows the same way it swallows garbage -- so the
  8690. # fallback costs nothing and needs no sentinel of its own.
  8691. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  8692. setting = result.scalar_one_or_none()
  8693. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  8694. temp_fair_threshold, setting.value if setting else None
  8695. )
  8696. # Per-filament humidity threshold overrides (#1605) — resolved
  8697. # per-AMS below from the loaded tray types. Reuses the same
  8698. # resolver as the auto-drying scheduler so behavior stays in
  8699. # lockstep across both consumers.
  8700. from backend.app.services.print_scheduler import PrintScheduler
  8701. per_type_humidity_thresholds: dict[str, int] = {}
  8702. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  8703. setting = result.scalar_one_or_none()
  8704. if setting and setting.value:
  8705. try:
  8706. raw = json.loads(setting.value)
  8707. if isinstance(raw, dict):
  8708. for k, v in raw.items():
  8709. try:
  8710. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  8711. v
  8712. )
  8713. except (TypeError, ValueError):
  8714. continue
  8715. except (ValueError, TypeError):
  8716. pass # Invalid JSON → no overrides, fall through to global threshold
  8717. # Per-AMS drying latch (#1802), loaded once per pass and written
  8718. # back below only if a unit changed it.
  8719. drying_latch = await _load_ams_drying_latch(db)
  8720. drying_latch_before = dict(drying_latch)
  8721. recorded_count = 0
  8722. for printer in printers:
  8723. # Get current state from printer manager
  8724. state = printer_manager.get_status(printer.id)
  8725. if not state or not state.connected or not state.raw_data:
  8726. continue # Skip disconnected printers - don't use stale data
  8727. raw_data = state.raw_data
  8728. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  8729. continue
  8730. # Record data for each AMS unit
  8731. for ams_data in raw_data["ams"]:
  8732. ams_id = int(ams_data.get("id", 0))
  8733. # Percentage only. The 1-5 index is inverted, so
  8734. # charting it as a percentage drew the wettest units as
  8735. # the driest (#3140); a unit that reports no percentage
  8736. # leaves a gap in the chart instead. See
  8737. # utils/ams_humidity.
  8738. humidity = ams_humidity_percent(ams_data)
  8739. # No supported printer is known to send the index
  8740. # alone -- the report came from unsupported firmware,
  8741. # and no install has been seen using the old fallback.
  8742. # "Known" is doing work there, so say so once per unit:
  8743. # the alternative is a silent blank card.
  8744. if humidity is None and ams_data.get("humidity") is not None:
  8745. unit_key = (printer.id, ams_id)
  8746. if unit_key not in _ams_index_only_logged:
  8747. _ams_index_only_logged.add(unit_key)
  8748. logger.info(
  8749. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  8750. "percentage. The index is inverted and is not shown as a percentage "
  8751. "(#3140), so this unit has no humidity reading, chart or alarm. "
  8752. "Please report this with the printer and AMS firmware versions.",
  8753. printer.name,
  8754. ams_id,
  8755. )
  8756. # Get temperature
  8757. temperature = None
  8758. temp_str = ams_data.get("temp")
  8759. if temp_str is not None:
  8760. try:
  8761. temperature = float(temp_str)
  8762. except (ValueError, TypeError):
  8763. pass # Skip unparseable temperature value
  8764. # Skip if no data
  8765. if humidity is None and temperature is None:
  8766. continue
  8767. # Record the data point
  8768. history = AMSSensorHistory(
  8769. printer_id=printer.id,
  8770. ams_id=ams_id,
  8771. humidity=humidity,
  8772. # Both columns hold the same reading now that the
  8773. # index can no longer reach ``humidity``. Writing it
  8774. # through the same value also stops a genuine 0%
  8775. # from being stored as NULL, which the old truthiness
  8776. # test did.
  8777. humidity_raw=humidity,
  8778. temperature=temperature,
  8779. )
  8780. db.add(history)
  8781. recorded_count += 1
  8782. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  8783. is_ams_ht = ams_id >= 128
  8784. if is_ams_ht:
  8785. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  8786. else:
  8787. ams_label = f"AMS-{chr(65 + ams_id)}"
  8788. # Skip alarm dispatch for empty AMS units — humidity /
  8789. # temperature readings are ambient with no filament to
  8790. # protect, and the hourly notification just becomes
  8791. # noise. Sensor history was already recorded above so
  8792. # the UI charts stay continuous (#1619). Per-AMS check
  8793. # so a multi-AMS setup with one loaded + one empty
  8794. # still alarms on the loaded unit.
  8795. if not _ams_has_filament(ams_data):
  8796. continue
  8797. # Resolve per-filament humidity threshold for this AMS
  8798. # unit (#1605). Falls back to the global ams_humidity_fair
  8799. # when no per-type overrides are configured.
  8800. trays = ams_data.get("tray", []) or []
  8801. effective_humidity_threshold = float(
  8802. PrintScheduler.resolve_humidity_threshold(
  8803. trays, per_type_humidity_thresholds, int(humidity_threshold)
  8804. )
  8805. )
  8806. # Check humidity alarm (only if above threshold)
  8807. if humidity is not None and humidity > effective_humidity_threshold:
  8808. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  8809. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8810. now = datetime.now(timezone.utc)
  8811. if (
  8812. last_alarm is None
  8813. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8814. ):
  8815. _ams_alarm_cooldown[cooldown_key] = now
  8816. logger.info(
  8817. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  8818. )
  8819. try:
  8820. # Call different notification method based on AMS type
  8821. if is_ams_ht:
  8822. await notification_service.on_ams_ht_humidity_high(
  8823. printer.id,
  8824. printer.name,
  8825. ams_label,
  8826. humidity,
  8827. effective_humidity_threshold,
  8828. db,
  8829. )
  8830. else:
  8831. await notification_service.on_ams_humidity_high(
  8832. printer.id,
  8833. printer.name,
  8834. ams_label,
  8835. humidity,
  8836. effective_humidity_threshold,
  8837. db,
  8838. )
  8839. except Exception as e:
  8840. logger.warning("Failed to send humidity alarm: %s", e)
  8841. # A drying cycle heats the unit far past ams_temp_fair on
  8842. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  8843. # AMS-HT, against a 35 C default — so the alarm fired
  8844. # once an hour for the whole cycle and kept firing while
  8845. # the unit cooled back down (#1802). Latch on the
  8846. # firmware's own drying state and hold until the reading
  8847. # returns to normal. Humidity is deliberately left alone:
  8848. # it falls during drying, which is the whole point.
  8849. latch_key = f"{printer.id}:{ams_id}"
  8850. # The latch releases at `threshold`, so it takes the alarm
  8851. # number too. Handing it the display band would strand the
  8852. # latch on any unit that settles back above it -- a room
  8853. # where the AMS rests at 37.7 C never returns under a 35 C
  8854. # band, so the latch could only expire on the grace cap
  8855. # rather than releasing when the unit had actually cooled.
  8856. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  8857. drying_active=is_drying_active(ams_data),
  8858. temperature=temperature,
  8859. threshold=temp_alarm_threshold,
  8860. latched_at=drying_latch.get(latch_key),
  8861. now=datetime.now(timezone.utc),
  8862. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  8863. )
  8864. if new_latch is None:
  8865. drying_latch.pop(latch_key, None)
  8866. else:
  8867. drying_latch[latch_key] = new_latch
  8868. # Check temperature alarm (only if above threshold)
  8869. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  8870. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  8871. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8872. now = datetime.now(timezone.utc)
  8873. if (
  8874. last_alarm is None
  8875. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8876. ):
  8877. _ams_alarm_cooldown[cooldown_key] = now
  8878. logger.info(
  8879. f"Sending temperature alarm for {printer.name} {ams_label}: "
  8880. f"{temperature}°C > {temp_alarm_threshold}°C"
  8881. )
  8882. try:
  8883. # Call different notification method based on AMS type
  8884. if is_ams_ht:
  8885. # The reported threshold has to be the one
  8886. # that fired, or the message says "> 35 °C"
  8887. # while firing at 45.
  8888. await notification_service.on_ams_ht_temperature_high(
  8889. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8890. )
  8891. else:
  8892. await notification_service.on_ams_temperature_high(
  8893. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8894. )
  8895. except Exception as e:
  8896. logger.warning("Failed to send temperature alarm: %s", e)
  8897. if drying_latch != drying_latch_before:
  8898. await _save_ams_drying_latch(db, drying_latch)
  8899. await db.commit()
  8900. if recorded_count > 0:
  8901. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  8902. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  8903. global _ams_cleanup_counter
  8904. _ams_cleanup_counter += 1
  8905. if _ams_cleanup_counter >= 288:
  8906. _ams_cleanup_counter = 0
  8907. # Get retention days from settings
  8908. from backend.app.models.settings import Settings
  8909. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  8910. setting = result.scalar_one_or_none()
  8911. retention_days = _retention_days(setting.value if setting else None, AMS_HISTORY_RETENTION_DAYS)
  8912. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8913. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  8914. await db.commit()
  8915. if result.rowcount > 0:
  8916. logger.info(
  8917. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  8918. )
  8919. # Wait until next recording interval
  8920. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  8921. except asyncio.CancelledError:
  8922. break
  8923. except Exception as e:
  8924. logger.warning("AMS history recording failed: %s", e)
  8925. await asyncio.sleep(60) # Wait a bit before retrying
  8926. def start_ams_history_recording():
  8927. """Start the AMS history recording background task."""
  8928. global _ams_history_task
  8929. if _ams_history_task is None:
  8930. _ams_history_task = asyncio.create_task(record_ams_history())
  8931. logging.getLogger(__name__).info("AMS history recording started")
  8932. def stop_ams_history_recording():
  8933. """Stop the AMS history recording background task."""
  8934. global _ams_history_task
  8935. if _ams_history_task:
  8936. _ams_history_task.cancel()
  8937. _ams_history_task = None
  8938. logging.getLogger(__name__).info("AMS history recording stopped")
  8939. # Printer sensor history recording (nozzle / bed / chamber)
  8940. _printer_sensor_history_task: asyncio.Task | None = None
  8941. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  8942. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  8943. _printer_sensor_cleanup_counter = 0
  8944. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  8945. # MQTT parser writes, so we don't need to handle per-model field aliases here
  8946. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  8947. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  8948. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  8949. _SENSOR_TARGET_KEYS = {
  8950. "nozzle": "nozzle_target",
  8951. "nozzle_2": "nozzle_2_target",
  8952. "bed": "bed_target",
  8953. "chamber": "chamber_target",
  8954. }
  8955. async def record_printer_sensor_history():
  8956. """Background task to record nozzle / bed / chamber readings.
  8957. Pulls from `state.temperatures` (already normalised across all printer
  8958. models by the MQTT parser) rather than re-parsing raw_data, so we get
  8959. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  8960. """
  8961. logger = logging.getLogger(__name__)
  8962. await asyncio.sleep(10)
  8963. while True:
  8964. try:
  8965. from backend.app.models.printer import Printer
  8966. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  8967. from backend.app.models.settings import Settings
  8968. async with async_session() as db:
  8969. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8970. printers = result.scalars().all()
  8971. recorded_count = 0
  8972. for printer in printers:
  8973. state = printer_manager.get_status(printer.id)
  8974. if not state or not state.connected:
  8975. continue
  8976. temps = getattr(state, "temperatures", None) or {}
  8977. if not isinstance(temps, dict):
  8978. continue
  8979. for kind in _SENSOR_KINDS:
  8980. if kind not in temps:
  8981. continue
  8982. try:
  8983. value = float(temps[kind])
  8984. except (ValueError, TypeError):
  8985. continue
  8986. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  8987. target_val: float | None = None
  8988. if target_raw is not None:
  8989. try:
  8990. target_val = float(target_raw)
  8991. except (ValueError, TypeError):
  8992. target_val = None
  8993. db.add(
  8994. PrinterSensorHistory(
  8995. printer_id=printer.id,
  8996. sensor_kind=kind,
  8997. value=value,
  8998. target=target_val,
  8999. )
  9000. )
  9001. recorded_count += 1
  9002. await db.commit()
  9003. if recorded_count > 0:
  9004. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  9005. # Periodic cleanup — once every ~24h at this interval.
  9006. global _printer_sensor_cleanup_counter
  9007. _printer_sensor_cleanup_counter += 1
  9008. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  9009. if _printer_sensor_cleanup_counter >= cleanup_every:
  9010. _printer_sensor_cleanup_counter = 0
  9011. result = await db.execute(
  9012. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  9013. )
  9014. setting = result.scalar_one_or_none()
  9015. retention_days = _retention_days(
  9016. setting.value if setting else None, PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  9017. )
  9018. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9019. cleanup = await db.execute(
  9020. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  9021. )
  9022. await db.commit()
  9023. if cleanup.rowcount > 0:
  9024. logger.info(
  9025. "Cleaned up %s old printer sensor history entries (older than %s days)",
  9026. cleanup.rowcount,
  9027. retention_days,
  9028. )
  9029. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  9030. except asyncio.CancelledError:
  9031. break
  9032. except Exception as e:
  9033. logger.warning("Printer sensor history recording failed: %s", e)
  9034. await asyncio.sleep(60)
  9035. def start_printer_sensor_history_recording():
  9036. global _printer_sensor_history_task
  9037. if _printer_sensor_history_task is None:
  9038. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  9039. logging.getLogger(__name__).info("Printer sensor history recording started")
  9040. def stop_printer_sensor_history_recording():
  9041. global _printer_sensor_history_task
  9042. if _printer_sensor_history_task:
  9043. _printer_sensor_history_task.cancel()
  9044. _printer_sensor_history_task = None
  9045. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  9046. # Printer runtime tracking
  9047. _runtime_tracking_task: asyncio.Task | None = None
  9048. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  9049. # Printers the runtime tracker has seen connected since startup. One of them
  9050. # going offline clears its timestamp, so the time it was away is not counted
  9051. # when it comes back printing (DB-C5). A printer not yet seen -- still
  9052. # connecting after a restart -- keeps it for a grace period: a print that ran
  9053. # on through a Bambuddy restart is counted from the stored timestamp, as before.
  9054. _runtime_seen_connected: set[int] = set()
  9055. # A printer never seen connected this long after the tracker started is
  9056. # offline, not still connecting: its stored timestamp predates a gap too.
  9057. RUNTIME_STARTUP_GRACE_SECONDS = 120
  9058. async def track_printer_runtime():
  9059. """Background task to track printer active runtime (RUNNING state only).
  9060. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  9061. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  9062. which track mechanical wear. Pause time has no motion and no wear, so
  9063. counting it inflates maintenance warnings (#1521).
  9064. """
  9065. logger = logging.getLogger(__name__)
  9066. # Wait for MQTT connections to establish on startup
  9067. await asyncio.sleep(15)
  9068. started = time.monotonic()
  9069. while True:
  9070. try:
  9071. from backend.app.models.printer import Printer
  9072. # Fetch printer IDs in a short-lived read-only session
  9073. async with async_session() as db:
  9074. result = await db.execute(
  9075. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  9076. Printer.is_active.is_(True)
  9077. )
  9078. )
  9079. printer_rows = result.all()
  9080. now = datetime.now(timezone.utc)
  9081. updated_count = 0
  9082. # Update each printer in its own short session to minimise write-lock
  9083. # hold time and avoid blocking critical commits like queue status
  9084. # updates (#897).
  9085. for pid, pname, runtime_secs, last_update in printer_rows:
  9086. state = printer_manager.get_status(pid)
  9087. if not state:
  9088. logger.debug("[%s] Runtime tracking: no state available", pname)
  9089. continue
  9090. if not state.connected:
  9091. logger.debug("[%s] Runtime tracking: not connected", pname)
  9092. offline = pid in _runtime_seen_connected or (
  9093. time.monotonic() - started > RUNTIME_STARTUP_GRACE_SECONDS
  9094. )
  9095. if offline and last_update is not None:
  9096. try:
  9097. async with async_session() as db:
  9098. printer = await db.get(Printer, pid)
  9099. if printer:
  9100. printer.last_runtime_update = None
  9101. await db.commit()
  9102. except Exception as e:
  9103. # Still marked: the next offline tick tries again.
  9104. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  9105. continue
  9106. _runtime_seen_connected.discard(pid)
  9107. continue
  9108. _runtime_seen_connected.add(pid)
  9109. needs_commit = False
  9110. new_runtime = runtime_secs
  9111. new_last_update = last_update
  9112. if state.state == "RUNNING":
  9113. if last_update:
  9114. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  9115. elapsed = (now - lu).total_seconds()
  9116. if elapsed > 0:
  9117. new_runtime = runtime_secs + int(elapsed)
  9118. updated_count += 1
  9119. needs_commit = True
  9120. logger.debug(
  9121. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  9122. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  9123. )
  9124. else:
  9125. needs_commit = True
  9126. logger.debug("[%s] Runtime tracking: first active detection", pname)
  9127. new_last_update = now
  9128. else:
  9129. if last_update is not None:
  9130. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  9131. new_last_update = None
  9132. needs_commit = True
  9133. if needs_commit:
  9134. try:
  9135. async with async_session() as db:
  9136. result = await db.execute(select(Printer).where(Printer.id == pid))
  9137. printer = result.scalar_one_or_none()
  9138. if printer:
  9139. printer.runtime_seconds = new_runtime
  9140. printer.last_runtime_update = new_last_update
  9141. await db.commit()
  9142. except Exception as e:
  9143. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  9144. if updated_count > 0:
  9145. logger.debug("Updated runtime for %s printer(s)", updated_count)
  9146. except asyncio.CancelledError:
  9147. logger.info("Runtime tracking cancelled")
  9148. break
  9149. except Exception as e:
  9150. logger.warning("Runtime tracking failed: %s", e)
  9151. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  9152. def start_runtime_tracking():
  9153. """Start the printer runtime tracking background task."""
  9154. global _runtime_tracking_task
  9155. if _runtime_tracking_task is None:
  9156. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  9157. logging.getLogger(__name__).info("Printer runtime tracking started")
  9158. def stop_runtime_tracking():
  9159. """Stop the printer runtime tracking background task."""
  9160. global _runtime_tracking_task
  9161. if _runtime_tracking_task:
  9162. _runtime_tracking_task.cancel()
  9163. _runtime_tracking_task = None
  9164. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  9165. # SpoolBuddy device watchdog
  9166. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  9167. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  9168. async def _spoolbuddy_watchdog_loop():
  9169. """Periodic check for SpoolBuddy devices that have gone offline."""
  9170. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  9171. while True:
  9172. try:
  9173. await spoolbuddy_watchdog()
  9174. except asyncio.CancelledError:
  9175. break
  9176. except Exception as e:
  9177. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  9178. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  9179. def start_spoolbuddy_watchdog():
  9180. global _spoolbuddy_watchdog_task
  9181. if _spoolbuddy_watchdog_task is None:
  9182. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  9183. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  9184. def stop_spoolbuddy_watchdog():
  9185. global _spoolbuddy_watchdog_task
  9186. if _spoolbuddy_watchdog_task:
  9187. _spoolbuddy_watchdog_task.cancel()
  9188. _spoolbuddy_watchdog_task = None
  9189. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  9190. # Dead-MQTT-session recovery
  9191. #
  9192. # check_staleness() covers the "connected but silent" half-broken session. It
  9193. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  9194. # is the only thing left watching at that point. When paho stops making
  9195. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  9196. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  9197. # offline with the UI open the whole time, recovered only when something
  9198. # happened to nudge it.
  9199. #
  9200. # This loop is that backstop. It only touches printers that had a working
  9201. # session and lost it, and only when the MQTT port still answers — a printer
  9202. # that is simply switched off is left to paho, since rebuilding a client
  9203. # against an unreachable host achieves nothing and would fill the log every
  9204. # night.
  9205. _connection_watchdog_task: asyncio.Task | None = None
  9206. CONNECTION_WATCHDOG_INTERVAL = 60
  9207. # How long a printer must have been silent before we stop trusting paho.
  9208. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  9209. # so a session that is recovering on its own is never interrupted.
  9210. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  9211. # Per-printer floor between rebuild attempts.
  9212. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  9213. _connection_watchdog_last_attempt: dict[int, float] = {}
  9214. async def _recover_dead_printer_sessions() -> int:
  9215. """Rebuild MQTT clients that have been offline too long to still be trying.
  9216. Returns the number of printers a rebuild was attempted for (for tests and
  9217. for the caller's logging). Never raises: one unreachable printer must not
  9218. stop the sweep for the rest of the farm.
  9219. """
  9220. logger = logging.getLogger(__name__)
  9221. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  9222. now = time.monotonic()
  9223. recovered = 0
  9224. for printer_id, client in list(printer_manager._clients.items()):
  9225. try:
  9226. if client.state.connected:
  9227. _connection_watchdog_last_attempt.pop(printer_id, None)
  9228. continue
  9229. # Time since the last inbound message is the age of the last known
  9230. # good session — no extra bookkeeping needed, and it is the same
  9231. # clock is_stale() reads. 0 means this client has never had one:
  9232. # that is the initial-connect path, where paho retrying is the
  9233. # correct and only behaviour, so leave it be.
  9234. last_msg = client._last_message_time
  9235. if not last_msg:
  9236. continue
  9237. offline_for = time.time() - last_msg
  9238. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  9239. continue
  9240. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  9241. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  9242. continue
  9243. if not await check_port(client.ip_address, PORT_MQTT):
  9244. # Switched off, unplugged, or off the network. Paho's retry is
  9245. # the right handler; say so at debug level and move on.
  9246. logger.debug(
  9247. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  9248. "— leaving the reconnect to paho",
  9249. printer_id,
  9250. offline_for,
  9251. )
  9252. _connection_watchdog_last_attempt[printer_id] = now
  9253. continue
  9254. _connection_watchdog_last_attempt[printer_id] = now
  9255. recovered += 1
  9256. logger.warning(
  9257. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  9258. "rebuilding the client with a fresh session (last connect error: %s)",
  9259. printer_id,
  9260. offline_for,
  9261. PORT_MQTT,
  9262. client.last_connect_error or "none recorded",
  9263. )
  9264. # Async context, so this takes the hard-reset path: fresh client_id,
  9265. # paho's QoS 1 queue dropped. That matters — a project_file left
  9266. # unacked on the dead session would otherwise replay into the new
  9267. # one and trip 0500_4003 on the printer (#1136).
  9268. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  9269. except Exception as e:
  9270. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  9271. return recovered
  9272. async def _connection_watchdog_loop():
  9273. logger = logging.getLogger(__name__)
  9274. # Let the initial connects settle before judging anyone offline.
  9275. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  9276. while True:
  9277. try:
  9278. await _recover_dead_printer_sessions()
  9279. except asyncio.CancelledError:
  9280. break
  9281. except Exception as e:
  9282. logger.warning("Connection watchdog sweep failed: %s", e)
  9283. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  9284. def start_connection_watchdog():
  9285. global _connection_watchdog_task
  9286. if _connection_watchdog_task is None:
  9287. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  9288. logging.getLogger(__name__).info("Printer connection watchdog started")
  9289. def stop_connection_watchdog():
  9290. global _connection_watchdog_task
  9291. if _connection_watchdog_task:
  9292. _connection_watchdog_task.cancel()
  9293. _connection_watchdog_task = None
  9294. _connection_watchdog_last_attempt.clear()
  9295. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  9296. # Camera stream orphan cleanup
  9297. _camera_cleanup_task: asyncio.Task | None = None
  9298. CAMERA_CLEANUP_INTERVAL = 60
  9299. # Every this many camera cleanups (about an hour), the timelapse janitor too:
  9300. # kept frames of a failed stitch go after a day, not at the next restart.
  9301. TIMELAPSE_CLEANUP_EVERY = 60
  9302. async def _camera_cleanup_loop():
  9303. """Periodically clean up orphaned ffmpeg processes and timelapse leftovers."""
  9304. from backend.app.api.routes.camera import cleanup_orphaned_streams
  9305. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9306. rounds = 0
  9307. while True:
  9308. try:
  9309. rounds += 1
  9310. await cleanup_orphaned_streams()
  9311. except asyncio.CancelledError:
  9312. break
  9313. except Exception as e:
  9314. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  9315. try:
  9316. if rounds % TIMELAPSE_CLEANUP_EVERY == 0:
  9317. await asyncio.to_thread(cleanup_orphaned_timelapse_sessions)
  9318. except asyncio.CancelledError:
  9319. break
  9320. except Exception as e:
  9321. logging.getLogger(__name__).warning("Timelapse frames cleanup failed: %s", e)
  9322. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  9323. def start_camera_cleanup():
  9324. global _camera_cleanup_task
  9325. if _camera_cleanup_task is None:
  9326. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  9327. logging.getLogger(__name__).info("Camera stream cleanup started")
  9328. def stop_camera_cleanup():
  9329. global _camera_cleanup_task
  9330. if _camera_cleanup_task:
  9331. _camera_cleanup_task.cancel()
  9332. _camera_cleanup_task = None
  9333. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  9334. # ---------------------------------------------------------------------------
  9335. # Expected-print TTL eviction
  9336. # ---------------------------------------------------------------------------
  9337. def _evict_stale_expected_prints() -> None:
  9338. """Remove entries from _expected_prints / _expected_print_creators that are
  9339. older than _EXPECTED_PRINT_TTL_SECONDS.
  9340. This prevents unbounded growth when a print is registered (via
  9341. register_expected_print) but on_print_start never fires — e.g. because the
  9342. printer disconnects, the app restarts, or the print is started directly from
  9343. the printer panel without going through the queue.
  9344. """
  9345. # Use monotonic time so the TTL is unaffected by system clock adjustments
  9346. # (e.g. NTP sync, DST changes).
  9347. # A print that ended without its archive being found at completion leaves
  9348. # its id here; only running prints are owned.
  9349. _owned_print_archive_ids.intersection_update(_active_prints.values())
  9350. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  9351. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  9352. if not stale_keys:
  9353. return
  9354. evicted_archive_ids: set[int] = set()
  9355. for key in stale_keys:
  9356. archive_id = _expected_prints.pop(key, None)
  9357. if archive_id is not None:
  9358. evicted_archive_ids.add(archive_id)
  9359. _expected_print_creators.pop(key, None)
  9360. _expected_print_registered_at.pop(key, None)
  9361. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  9362. # that have no remaining live keys in _expected_prints (all variants
  9363. # were just evicted) and are not printing right now. Print start pops
  9364. # only the names the printer reported, so the "<base>.gcode" variant
  9365. # outlives it; without the printing check its eviction two hours after
  9366. # dispatch threw away a running print's plate, AMS mapping and cost
  9367. # centre, which completion still reads (#3275).
  9368. live_archive_ids = set(_expected_prints.values()) | set(_active_prints.values())
  9369. for archive_id in evicted_archive_ids:
  9370. if archive_id not in live_archive_ids:
  9371. _print_ams_mappings.pop(archive_id, None)
  9372. _print_cost_center_ids.pop(archive_id, None)
  9373. _print_plate_ids.pop(archive_id, None)
  9374. logging.getLogger(__name__).info(
  9375. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  9376. )
  9377. async def _expected_prints_cleanup_loop() -> None:
  9378. """Background task: periodically evict stale expected-print entries."""
  9379. while True:
  9380. try:
  9381. _evict_stale_expected_prints()
  9382. except asyncio.CancelledError:
  9383. raise
  9384. except Exception as e:
  9385. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  9386. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  9387. def start_expected_prints_cleanup() -> None:
  9388. global _expected_prints_cleanup_task
  9389. if _expected_prints_cleanup_task is None:
  9390. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  9391. logging.getLogger(__name__).info("Expected prints cleanup started")
  9392. def stop_expected_prints_cleanup() -> None:
  9393. global _expected_prints_cleanup_task
  9394. if _expected_prints_cleanup_task:
  9395. _expected_prints_cleanup_task.cancel()
  9396. _expected_prints_cleanup_task = None
  9397. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  9398. # ---------------------------------------------------------------------------
  9399. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  9400. # ---------------------------------------------------------------------------
  9401. _auth_cleanup_task: asyncio.Task | None = None
  9402. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  9403. async def _run_auth_cleanup() -> None:
  9404. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  9405. from backend.app.core.database import async_session
  9406. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  9407. from backend.app.models.user_totp import UserTOTP
  9408. now = datetime.now(timezone.utc)
  9409. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  9410. try:
  9411. async with async_session() as db:
  9412. stale_cutoff = now - timedelta(hours=1)
  9413. result = await db.execute(
  9414. select(UserTOTP).where(
  9415. UserTOTP.is_enabled.is_(False),
  9416. UserTOTP.created_at < stale_cutoff,
  9417. )
  9418. )
  9419. stale_records = result.scalars().all()
  9420. if stale_records:
  9421. for rec in stale_records:
  9422. await db.delete(rec)
  9423. await db.commit()
  9424. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  9425. except Exception as e:
  9426. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  9427. # Remove expired revoked-JTI entries (they are no longer needed once the
  9428. # original token's exp has passed — the token would be rejected by JWT
  9429. # signature verification regardless).
  9430. try:
  9431. async with async_session() as db:
  9432. await db.execute(
  9433. delete(AuthEphemeralToken).where(
  9434. AuthEphemeralToken.token_type == "revoked_jti",
  9435. AuthEphemeralToken.expires_at < now,
  9436. )
  9437. )
  9438. await db.commit()
  9439. except Exception as e:
  9440. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  9441. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  9442. # Events outside this window can never affect rate-limit decisions — they only
  9443. # consume DB space. Use the same window constant as the rate limiter so the
  9444. # two are always in sync.
  9445. try:
  9446. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  9447. async with async_session() as db:
  9448. await db.execute(
  9449. delete(AuthRateLimitEvent).where(
  9450. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  9451. )
  9452. )
  9453. await db.commit()
  9454. except Exception as e:
  9455. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  9456. async def _auth_cleanup_loop() -> None:
  9457. """Periodic background task: run auth cleanup every hour."""
  9458. while True:
  9459. try:
  9460. await _run_auth_cleanup()
  9461. except asyncio.CancelledError:
  9462. break
  9463. except Exception as e:
  9464. logging.warning("Auth cleanup loop error: %s", e)
  9465. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  9466. def start_auth_cleanup() -> None:
  9467. global _auth_cleanup_task
  9468. if _auth_cleanup_task is None:
  9469. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  9470. logging.getLogger(__name__).info("Auth periodic cleanup started")
  9471. def stop_auth_cleanup() -> None:
  9472. global _auth_cleanup_task
  9473. if _auth_cleanup_task:
  9474. _auth_cleanup_task.cancel()
  9475. _auth_cleanup_task = None
  9476. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  9477. @asynccontextmanager
  9478. async def lifespan(app: FastAPI):
  9479. # Startup
  9480. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  9481. # anything else can spawn tasks that might trip it.
  9482. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  9483. install_proactor_reset_filter()
  9484. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  9485. # what turned descriptor exhaustion into a corrupted database (#2883).
  9486. from backend.app.core.fd_limit import raise_open_file_limit
  9487. raise_open_file_limit()
  9488. # Before init_db, so the warning is near the top of the log rather than
  9489. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  9490. warn_if_running_on_uvloop()
  9491. await init_db()
  9492. # Browser download tokens expire after five minutes. Remove abandoned
  9493. # prepared ZIPs at startup as well as before each new preparation so a
  9494. # quiet appliance cannot retain an unusable bundle indefinitely.
  9495. try:
  9496. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  9497. await prune_stale_printer_file_bundles()
  9498. except Exception as exc:
  9499. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  9500. # After migrations, so the is_env_managed column exists. Never raises --
  9501. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  9502. # startup (see apply_env_oidc_provider).
  9503. from backend.app.core.oidc_env import apply_env_oidc_provider
  9504. async with async_session() as oidc_db:
  9505. await apply_env_oidc_provider(oidc_db)
  9506. # Close out batches that finished before `completed` was a reachable status
  9507. # (#342). Without this the Batches tab opens on every batch created since
  9508. # the feature shipped, all still marked active. Never blocks startup.
  9509. try:
  9510. from backend.app.services.print_batch import backfill_batch_statuses
  9511. async with async_session() as batch_db:
  9512. await backfill_batch_statuses(batch_db)
  9513. except Exception as exc:
  9514. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  9515. # Register an app-scoped httpx client for Bambu Cloud services so
  9516. # per-request BambuCloudService instances reuse the same connection pool
  9517. # (important for routes like /cloud/filament-info that chain many
  9518. # get_setting_detail calls). The shared client stores no region/token
  9519. # state, so the per-request ownership pattern that fixed the region-bleed
  9520. # bug is preserved.
  9521. import httpx as _httpx
  9522. from backend.app.services.bambu_cloud import set_shared_http_client
  9523. from backend.app.services.model_providers.makerworld.service import (
  9524. set_shared_http_client as set_shared_makerworld_http_client,
  9525. )
  9526. from backend.app.services.orca_cloud import (
  9527. set_shared_http_client as set_shared_orca_http_client,
  9528. )
  9529. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  9530. set_shared_http_client(_shared_cloud_http_client)
  9531. # Reuse the same connection pool for MakerWorld — different host, same
  9532. # keep-alive pool saves a TLS handshake per request.
  9533. set_shared_makerworld_http_client(_shared_cloud_http_client)
  9534. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  9535. # each spun up (and never closed) its own client, leaking sockets.
  9536. set_shared_orca_http_client(_shared_cloud_http_client)
  9537. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  9538. # This can happen when a print was cancelled mid-print on versions before this fix.
  9539. try:
  9540. async with async_session() as db:
  9541. from backend.app.models.print_queue import PrintQueueItem
  9542. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  9543. aborted_items = result.scalars().all()
  9544. if aborted_items:
  9545. for item in aborted_items:
  9546. item.status = "cancelled"
  9547. await db.commit()
  9548. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  9549. except Exception as e:
  9550. logging.warning("Failed to fix aborted queue items: %s", e)
  9551. # Restore debug logging state from previous session
  9552. await init_debug_logging()
  9553. # Set up printer manager callbacks
  9554. loop = asyncio.get_event_loop()
  9555. printer_manager.set_event_loop(loop)
  9556. printer_manager.set_status_change_callback(on_printer_status_change)
  9557. printer_manager.set_print_start_callback(on_print_start)
  9558. printer_manager.set_print_complete_callback(on_print_complete)
  9559. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  9560. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  9561. printer_manager.set_ams_change_callback(on_ams_change)
  9562. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  9563. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  9564. await printer_manager.load_awaiting_plate_clear_from_db()
  9565. # Layer change callback for external camera timelapse
  9566. async def on_layer_change(printer_id: int, layer_num: int):
  9567. """Capture timelapse frame on layer change + first layer notification."""
  9568. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  9569. await tl_layer_change(printer_id, layer_num)
  9570. # #1867: bank a recent in-print frame so the finish-photo path has a
  9571. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  9572. # #2547 added `on_print_progress` as a second driver — this one alone
  9573. # stops firing once the final layer begins.
  9574. await _maybe_bank_inprint_frame(printer_id, layer_num)
  9575. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  9576. # Gate on actual printing state — Bambu firmware ticks layer_num during
  9577. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  9578. # nozzle clean), so a bare layer_num check can fire minutes before the
  9579. # first real extrusion. We require gcode_state == RUNNING and
  9580. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  9581. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  9582. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  9583. # edge fires later; _first_layer_notified stays clear until we actually send
  9584. # so a deferred re-evaluation can win. See issue #1837.
  9585. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  9586. client = printer_manager.get_client(printer_id)
  9587. state = client.state if client else None
  9588. if not state or state.state != "RUNNING":
  9589. return
  9590. if state.mc_print_sub_stage not in (None, 0):
  9591. return
  9592. _first_layer_notified[printer_id] = True
  9593. try:
  9594. async with async_session() as db:
  9595. from backend.app.models.printer import Printer
  9596. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9597. printer = result.scalar_one_or_none()
  9598. if not printer:
  9599. return
  9600. printer_name = printer.name
  9601. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  9602. total_layers = state.total_layers if state else 0
  9603. image_data = await _capture_snapshot_for_notification(
  9604. printer_id, printer, logging.getLogger(__name__)
  9605. )
  9606. await notification_service.on_first_layer_complete(
  9607. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  9608. )
  9609. except Exception as e:
  9610. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  9611. printer_manager.set_layer_change_callback(on_layer_change)
  9612. async def on_print_progress(printer_id: int, percent: int):
  9613. """#2547: keep the in-print frame bank fresh through the final layer.
  9614. `on_layer_change` stops the moment the last layer starts, which on the
  9615. H2C capture that closed #2547 left the bank stale for the three minutes
  9616. that layer took. Progress is the only field that keeps advancing there,
  9617. and it freezes before the End G-code runs — so banking on it stays
  9618. inside the print and never sees a swapped plate.
  9619. """
  9620. client = printer_manager.get_client(printer_id)
  9621. state = client.state if client else None
  9622. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  9623. printer_manager.set_print_progress_callback(on_print_progress)
  9624. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  9625. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  9626. waiter = _bed_cool_waiters.get(printer_id)
  9627. if not waiter:
  9628. return
  9629. threshold = waiter["threshold"]
  9630. if bed_temp > threshold:
  9631. return
  9632. # Bed is at or below threshold — fire notification and remove waiter
  9633. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  9634. if not waiter_info:
  9635. return # Another callback already handled it
  9636. bed_cool_logger = logging.getLogger(__name__)
  9637. bed_cool_logger.info(
  9638. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  9639. bed_temp,
  9640. printer_id,
  9641. threshold,
  9642. )
  9643. try:
  9644. printer_info = printer_manager.get_printer(printer_id)
  9645. p_name = printer_info.name if printer_info else "Unknown"
  9646. async with async_session() as db:
  9647. await notification_service.on_bed_cooled(
  9648. printer_id=printer_id,
  9649. printer_name=p_name,
  9650. bed_temp=bed_temp,
  9651. threshold=threshold,
  9652. filename=waiter_info["filename"],
  9653. db=db,
  9654. )
  9655. except Exception as e:
  9656. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  9657. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  9658. async def on_drying_complete(printer_id: int, ams_id: int):
  9659. """Smart-plug auto-off-after-drying trigger (#1349).
  9660. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  9661. manager walks all plugs linked to this printer and turns off only
  9662. the ones with ``auto_off_after_drying`` enabled, after their
  9663. per-plug delay. Multiple AMS units finishing close together (e.g. a
  9664. dual-AMS dry that ends within the same MQTT push) call this once
  9665. per unit — the manager's ``_cancel_pending_off`` collapses
  9666. repeated scheduling on the same plug to one timer, so duplicate
  9667. fires are safe.
  9668. """
  9669. try:
  9670. async with async_session() as db:
  9671. await smart_plug_manager.on_drying_complete(printer_id, db)
  9672. except Exception as e:
  9673. logging.getLogger(__name__).warning(
  9674. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  9675. printer_id,
  9676. ams_id,
  9677. e,
  9678. )
  9679. printer_manager.set_drying_complete_callback(on_drying_complete)
  9680. async def on_drying_cycle_end(printer_id: int, cycle):
  9681. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  9682. from backend.app.services.spool_drying import record_drying_cycle
  9683. try:
  9684. async with async_session() as db:
  9685. await record_drying_cycle(db, printer_id, cycle)
  9686. except Exception as e:
  9687. logging.getLogger(__name__).warning(
  9688. "Failed to record drying for printer %d (AMS %d): %s",
  9689. printer_id,
  9690. cycle.ams_id,
  9691. e,
  9692. )
  9693. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  9694. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  9695. """Surface the read-back result of a spool assignment to the UI (#2582).
  9696. The MQTT client confirms (or fails to confirm) that the tray telemetry
  9697. echoed back the filament id we pushed. We relay that as a websocket
  9698. event so the frontend can toast "loaded" / "assignment didn't take"
  9699. instead of the historic silent fire-and-forget, which made the
  9700. AMS→Studio hand-off feel random to users.
  9701. """
  9702. try:
  9703. from backend.app.services.spool_assignment_notifications import (
  9704. _slot_label_from_global_tray,
  9705. )
  9706. if ams_id == 255:
  9707. global_id = 254 + tray_id
  9708. elif ams_id >= 128:
  9709. global_id = ams_id
  9710. else:
  9711. global_id = ams_id * 4 + tray_id
  9712. slot_label = _slot_label_from_global_tray(global_id)
  9713. printer_info = printer_manager.get_printer(printer_id)
  9714. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  9715. await ws_manager.broadcast(
  9716. {
  9717. "type": "spool_assignment_verified",
  9718. "printer_id": printer_id,
  9719. "printer_name": printer_name,
  9720. "ams_id": ams_id,
  9721. "tray_id": tray_id,
  9722. "slot": slot_label,
  9723. "verified": verified,
  9724. # Present on success: False means the filament setting landed
  9725. # but the K-profile (cali_idx) did not — the reporter's exact
  9726. # "loaded but no flow profile" symptom.
  9727. "kprofile_applied": detail.get("kprofile_applied", True),
  9728. # Present on failure: whether any tray telemetry was seen in
  9729. # the window (distinguishes "printer silent" from "printer
  9730. # stored something else").
  9731. "saw_tray": detail.get("saw_tray", False),
  9732. }
  9733. )
  9734. except Exception as e:
  9735. logging.getLogger(__name__).warning(
  9736. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  9737. printer_id,
  9738. ams_id,
  9739. tray_id,
  9740. e,
  9741. )
  9742. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  9743. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  9744. """Persist a mid-print tray change for completion-time attribution.
  9745. AMS filament backup switches trays without telling the slicer, so the
  9746. tray-change log is the only record of which spool fed which layers.
  9747. Keeping it only in memory meant a restart mid-print charged everything
  9748. to the tray that finished the job.
  9749. """
  9750. try:
  9751. from backend.app.services.usage_tracker import record_tray_change
  9752. async with async_session() as db:
  9753. await record_tray_change(db, printer_id, tray_global, layer_num)
  9754. except Exception as e:
  9755. logging.getLogger(__name__).warning(
  9756. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  9757. printer_id,
  9758. tray_global,
  9759. layer_num,
  9760. e,
  9761. )
  9762. printer_manager.set_tray_change_callback(on_tray_change)
  9763. # Initialize MQTT relay from settings
  9764. async with async_session() as db:
  9765. from backend.app.api.routes.settings import get_setting
  9766. mqtt_settings = {
  9767. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  9768. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  9769. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  9770. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  9771. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  9772. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  9773. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  9774. }
  9775. await mqtt_relay.configure(mqtt_settings)
  9776. # Restore MQTT smart plug subscriptions
  9777. if mqtt_settings.get("mqtt_enabled"):
  9778. from backend.app.models.smart_plug import SmartPlug
  9779. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  9780. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  9781. mqtt_plugs = result.scalars().all()
  9782. restored = 0
  9783. for plug in mqtt_plugs:
  9784. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  9785. restored += 1
  9786. if restored:
  9787. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  9788. # Connect to all active printers
  9789. async with async_session() as db:
  9790. await init_printer_connections(db)
  9791. # Auto-connect to Spoolman if enabled
  9792. async with async_session() as db:
  9793. from backend.app.api.routes.settings import get_setting
  9794. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  9795. spoolman_url = await get_setting(db, "spoolman_url")
  9796. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  9797. try:
  9798. client = await init_spoolman_client(spoolman_url)
  9799. if await client.health_check():
  9800. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  9801. # Ensure the 'tag' extra field exists for RFID/UUID storage
  9802. field_ok = await client.ensure_tag_extra_field()
  9803. if not field_ok:
  9804. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  9805. # Register the BambuStudio slicer-preset fields used by the
  9806. # spool-edit / assign flow. Spoolman rejects PATCHes with
  9807. # unknown extra keys, so these must exist before any update
  9808. # that touches them.
  9809. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  9810. if not await client.ensure_extra_field(field_name):
  9811. logging.warning(
  9812. "Spoolman extra field %r registration failed — "
  9813. "spool slicer-preset edits will return 502",
  9814. field_name,
  9815. )
  9816. else:
  9817. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  9818. except Exception as e:
  9819. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  9820. # Start the print scheduler
  9821. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  9822. # Start the smart plug scheduler for time-based on/off
  9823. smart_plug_manager.start_scheduler()
  9824. # Start the Home Assistant sensor poller (#1148)
  9825. ha_sensor_manager.start()
  9826. location_ha_sensor_manager.start()
  9827. # Resume any pending auto-offs that were interrupted by restart
  9828. await smart_plug_manager.resume_pending_auto_offs()
  9829. # Start the notification digest scheduler
  9830. notification_service.start_digest_scheduler()
  9831. notify_live_activities.start()
  9832. notify_widgets.start()
  9833. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  9834. # provider in reactions/both mode; the notification routes resync them.
  9835. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  9836. # until the next provider save, not the whole startup.
  9837. try:
  9838. await telegram_reaction_poller.start()
  9839. except Exception as e:
  9840. logging.warning("Telegram reaction poller did not start: %s", e)
  9841. # Start the GitHub backup scheduler
  9842. await github_backup_service.start_scheduler()
  9843. # Start the local backup scheduler
  9844. await local_backup_service.start_scheduler()
  9845. await obico_detection_service.start()
  9846. # Start the library trash sweeper (#1008)
  9847. await library_trash_service.start_scheduler()
  9848. # Start the archive auto-purge sweeper (#1008 follow-up)
  9849. await archive_purge_service.start_scheduler()
  9850. # Start AMS history recording
  9851. start_ams_history_recording()
  9852. # Start printer sensor (nozzle / bed / chamber) history recording
  9853. start_printer_sensor_history_recording()
  9854. # Start printer runtime tracking
  9855. start_runtime_tracking()
  9856. # Start SpoolBuddy device watchdog
  9857. start_spoolbuddy_watchdog()
  9858. # Start camera stream orphan cleanup
  9859. start_camera_cleanup()
  9860. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  9861. start_connection_watchdog()
  9862. # One-shot sweep for timelapse session directories orphaned by a crash
  9863. # or restart that happened mid-print (in-memory session tracking can't
  9864. # survive that, and nothing else reaps the leftover frames/output file)
  9865. try:
  9866. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9867. removed = cleanup_orphaned_timelapse_sessions()
  9868. if removed:
  9869. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  9870. except Exception as e:
  9871. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  9872. # Start expected-print TTL eviction (prevents memory leak when prints are
  9873. # registered but on_print_start never fires)
  9874. start_expected_prints_cleanup()
  9875. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  9876. start_auth_cleanup()
  9877. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  9878. from backend.app.services import announcements as announcements_service
  9879. announcements_service.start()
  9880. from backend.app.services.printer_media import start_printer_download_cleanup
  9881. start_printer_download_cleanup()
  9882. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  9883. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  9884. from backend.app.services.loop_watchdog import start_loop_watchdog
  9885. start_loop_watchdog()
  9886. # Initialize virtual printer manager and sync from DB
  9887. from backend.app.services.virtual_printer import virtual_printer_manager
  9888. virtual_printer_manager.set_session_factory(async_session)
  9889. virtual_printer_manager.set_printer_manager(printer_manager)
  9890. try:
  9891. await virtual_printer_manager.sync_from_db()
  9892. logging.info("Virtual printer manager synced from database")
  9893. except Exception as e:
  9894. logging.warning("Failed to sync virtual printers: %s", e)
  9895. yield
  9896. # Shutdown
  9897. print_scheduler.stop()
  9898. smart_plug_manager.stop_scheduler()
  9899. ha_sensor_manager.stop()
  9900. location_ha_sensor_manager.stop()
  9901. notification_service.stop_digest_scheduler()
  9902. await notify_live_activities.close()
  9903. await notify_widgets.close()
  9904. await telegram_reaction_poller.aclose()
  9905. github_backup_service.stop_scheduler()
  9906. local_backup_service.stop_scheduler()
  9907. library_trash_service.stop_scheduler()
  9908. archive_purge_service.stop_scheduler()
  9909. obico_detection_service.stop()
  9910. stop_ams_history_recording()
  9911. stop_printer_sensor_history_recording()
  9912. stop_runtime_tracking()
  9913. stop_spoolbuddy_watchdog()
  9914. stop_camera_cleanup()
  9915. stop_connection_watchdog()
  9916. from backend.app.services.loop_watchdog import stop_loop_watchdog
  9917. stop_loop_watchdog()
  9918. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  9919. # cleanly rather than waiting on a queue that nothing will ever fill.
  9920. try:
  9921. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  9922. await shutdown_all_broadcasters()
  9923. except Exception as e:
  9924. logging.warning("Failed to shut down camera broadcasters: %s", e)
  9925. stop_expected_prints_cleanup()
  9926. stop_auth_cleanup()
  9927. from backend.app.services import announcements as announcements_service
  9928. announcements_service.stop()
  9929. from backend.app.services.printer_media import stop_printer_download_cleanup
  9930. await stop_printer_download_cleanup()
  9931. printer_manager.disconnect_all()
  9932. slot_unlink_grace.reset()
  9933. await close_spoolman_client()
  9934. # Stop all virtual printer services
  9935. await virtual_printer_manager.stop_all()
  9936. await mqtt_smart_plug_service.disconnect(timeout=2)
  9937. await mqtt_relay.disconnect(timeout=2)
  9938. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  9939. set_shared_http_client(None)
  9940. set_shared_makerworld_http_client(None)
  9941. set_shared_orca_http_client(None)
  9942. await _shared_cloud_http_client.aclose()
  9943. # Checkpoint WAL (SQLite only) and close all database connections
  9944. from backend.app.core.db_dialect import is_sqlite
  9945. if is_sqlite():
  9946. try:
  9947. async with engine.begin() as conn:
  9948. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  9949. logging.info("WAL checkpoint completed")
  9950. except Exception as e:
  9951. logging.warning("WAL checkpoint failed: %s", e)
  9952. await engine.dispose()
  9953. app = FastAPI(
  9954. title=app_settings.app_name,
  9955. description="Archive and manage Bambu Lab 3MF files",
  9956. version=APP_VERSION,
  9957. lifespan=lifespan,
  9958. )
  9959. # Added first so it sits innermost, next to the routes: a refused header's value
  9960. # (often a stored token) masked in every JSON body. See core.response_redaction.
  9961. app.add_middleware(RefusedHeaderResponseMask)
  9962. def _json_safe(value):
  9963. """The validation errors with every non-finite number written as text."""
  9964. if isinstance(value, float) and not math.isfinite(value):
  9965. return str(value)
  9966. if isinstance(value, dict):
  9967. return {key: _json_safe(item) for key, item in value.items()}
  9968. if isinstance(value, list | tuple):
  9969. return [_json_safe(item) for item in value]
  9970. return value
  9971. @app.exception_handler(RequestValidationError)
  9972. async def _validation_error(_request, exc: RequestValidationError) -> JSONResponse:
  9973. """FastAPI's own 422, except that it survives a non-finite number.
  9974. A body may carry ``Infinity`` or ``NaN`` (Python's JSON reader accepts
  9975. them), and the default handler echoes the input back in its errors,
  9976. which JSON cannot hold: the request ended in an error instead of a 422.
  9977. """
  9978. return JSONResponse(status_code=422, content={"detail": _json_safe(jsonable_encoder(exc.errors()))})
  9979. # =============================================================================
  9980. # Authentication Middleware - Secures ALL API routes by default
  9981. # =============================================================================
  9982. # Public routes that don't require authentication even when auth is enabled
  9983. PUBLIC_API_ROUTES = {
  9984. # Auth routes needed before/during login
  9985. "/api/v1/auth/status",
  9986. "/api/v1/auth/login",
  9987. "/api/v1/auth/setup", # Needed for initial setup and recovery
  9988. # Advanced auth status needed for login page
  9989. "/api/v1/auth/advanced-auth/status",
  9990. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  9991. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  9992. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  9993. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  9994. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  9995. # OIDC routes that must be reachable without a JWT
  9996. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  9997. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  9998. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  9999. # Connected apps: the app's server swaps a code for the user's identity,
  10000. # authenticated by its client secret rather than a login token.
  10001. "/api/v1/connect/token",
  10002. # Version check for updates (no sensitive data)
  10003. "/api/v1/updates/version",
  10004. # Metrics endpoint handles its own prometheus_token authentication
  10005. "/api/v1/metrics",
  10006. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  10007. # this BEFORE a JWT is available to pick up the firstboot wizard's
  10008. # hostname / timezone / locale and the chrony NTP-gate state. The
  10009. # response contains user-set defaults and a public sync flag — no
  10010. # secrets. Without this entry the global auth middleware returns 401
  10011. # before the route handler runs, regardless of the route's own
  10012. # "no auth required" intent.
  10013. "/api/v1/system/appliance",
  10014. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  10015. # authenticates with a long-lived ``camwall``-scoped token in the query
  10016. # string — exactly like the camera streams two lists below, and for the same
  10017. # reason (no header to put a JWT in). "Public" here only means the middleware
  10018. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  10019. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  10020. # plain ``camera_stream`` token does NOT open this door.
  10021. "/api/v1/camwall/printers",
  10022. # Overlay branding: the route enforces overlay-scoped token authentication.
  10023. "/api/v1/overlay-branding/logo",
  10024. }
  10025. # Route prefixes that are public (for routes with dynamic segments)
  10026. PUBLIC_API_PREFIXES = [
  10027. # WebSocket connections handle their own auth
  10028. "/api/v1/ws",
  10029. # OIDC authorize redirects — include provider_id in path
  10030. "/api/v1/auth/oidc/authorize/",
  10031. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  10032. # a phone with no session, so no header can carry a JWT — the single-use
  10033. # capability token in the path IS the credential (same reasoning as the
  10034. # /dl/ slicer downloads below). The route grants nothing beyond writing
  10035. # good/reject on the one archive the token was minted for.
  10036. "/api/v1/archives/confirm/",
  10037. ]
  10038. # Route patterns that are public (read-only display data)
  10039. # These are checked with "in path" - needed because browsers load images/videos
  10040. # via <img src> and <video src> which don't include Authorization headers
  10041. PUBLIC_API_PATTERNS = [
  10042. # Thumbnails
  10043. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  10044. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  10045. # Images and media
  10046. "/photos/", # /archives/{id}/photos/{filename}
  10047. "/project-image/", # /archives/{id}/project-image/{path}
  10048. "/qrcode", # /archives/{id}/qrcode
  10049. "/timelapse", # /archives/{id}/timelapse (video)
  10050. "/cover", # /printers/{id}/cover
  10051. "/icon", # /external-links/{id}/icon
  10052. # Camera (streams loaded via <img> tag)
  10053. "/camera/stream", # /printers/{id}/camera/stream
  10054. "/camera/snapshot", # /printers/{id}/camera/snapshot
  10055. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  10056. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  10057. # string (same reasoning as the camera streams above — no header to carry a
  10058. # JWT). "Public" only means the middleware steps aside; the route still runs
  10059. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  10060. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  10061. "/overlay-status", # /printers/{id}/overlay-status
  10062. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  10063. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  10064. # download token in the URL path instead.
  10065. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  10066. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  10067. # and these patterns match by substring. Without its own entry the middleware
  10068. # 401s the slicer's header-less request before the route's token check runs,
  10069. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  10070. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  10071. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  10072. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  10073. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  10074. ]
  10075. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  10076. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  10077. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  10078. Format: comma-separated list of ``scheme://host[:port]`` origins.
  10079. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  10080. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  10081. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  10082. Invalid entries are dropped with a warning rather than failing startup, so
  10083. a typo in one origin doesn't take the whole deployment down.
  10084. """
  10085. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  10086. if not raw:
  10087. return ()
  10088. valid: list[str] = []
  10089. for item in raw.split(","):
  10090. candidate = item.strip()
  10091. if not candidate:
  10092. continue
  10093. try:
  10094. parsed = urlparse(candidate)
  10095. except ValueError as e:
  10096. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  10097. continue
  10098. if parsed.scheme not in ("http", "https"):
  10099. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  10100. continue
  10101. if not parsed.netloc:
  10102. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  10103. continue
  10104. if parsed.path and parsed.path != "/":
  10105. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  10106. continue
  10107. if parsed.query or parsed.fragment:
  10108. _security_headers_logger.warning(
  10109. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  10110. )
  10111. continue
  10112. if "*" in parsed.netloc:
  10113. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  10114. continue
  10115. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  10116. if valid:
  10117. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  10118. return tuple(valid)
  10119. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  10120. def _frame_ancestors(default_value: str) -> str:
  10121. """Compose the ``frame-ancestors`` CSP directive (#1191).
  10122. ``default_value`` is the strict directive used when the operator has not
  10123. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  10124. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  10125. Settings URL builder's preview). When trusted origins
  10126. are configured, ``'self'`` is always included so same-origin embedding never
  10127. breaks even if an operator forgets to add their own origin to the list.
  10128. """
  10129. if _TRUSTED_FRAME_ORIGINS:
  10130. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  10131. return f"frame-ancestors {default_value};"
  10132. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  10133. # patterns are anchored on the exact emitted name so the relaxed policies
  10134. # below can never apply to any other asset.
  10135. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  10136. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  10137. # -> /assets/pdf.worker.min-<hash>.js
  10138. # Vite also emits a one-line chunk under the second name that only exports the
  10139. # worker's URL. The page imports it as a module, and a module script is run
  10140. # under the importing document's policy, never its own response's, so it
  10141. # matching as well changes nothing.
  10142. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  10143. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  10144. @app.middleware("http")
  10145. async def security_headers_middleware(request, call_next):
  10146. """Add standard HTTP security headers to every response."""
  10147. # Per-request nonce stamped into `script-src` (#1460). On its own this
  10148. # changes nothing for Bambuddy's own pages — index.html has no inline
  10149. # scripts since the SW registration moved to /sw-register.js. The reason
  10150. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  10151. # script injected into the HTML on the edge, with a fresh hash on every
  10152. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  10153. # it clones the same nonce onto its injected <script>, and the inline
  10154. # script passes the policy without us needing 'unsafe-inline'. See
  10155. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  10156. csp_nonce = secrets.token_urlsafe(16)
  10157. # Routes that render their own HTML need it too, or their inline script is
  10158. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  10159. # one that does: it submits its own form so a verdict still costs one tap.
  10160. request.state.csp_nonce = csp_nonce
  10161. response = await call_next(request)
  10162. response.headers["X-Content-Type-Options"] = "nosniff"
  10163. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  10164. # browsers honour CSP frame-ancestors instead, and the legacy
  10165. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  10166. # When operators have explicitly allowlisted trusted frame origins (#1191
  10167. # — typically Home Assistant on a different port), drop X-Frame-Options
  10168. # and let the CSP-side frame-ancestors directive govern embedding.
  10169. if not _TRUSTED_FRAME_ORIGINS:
  10170. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  10171. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  10172. # Content-Security-Policy for the React SPA.
  10173. # Notes:
  10174. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  10175. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  10176. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  10177. # - media-src blob:: timelapse video player uses Blob URLs.
  10178. # - font-src data:: some icon fonts are embedded as data URIs.
  10179. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  10180. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  10181. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  10182. # default CSP would render a blank page.
  10183. response.headers["Content-Security-Policy"] = (
  10184. "default-src 'self'; "
  10185. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  10186. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  10187. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  10188. "connect-src 'self'; "
  10189. "font-src 'self' data: https://fonts.gstatic.com; "
  10190. "worker-src 'self' blob:; "
  10191. "object-src 'none'; "
  10192. "base-uri 'self'; " + _frame_ancestors("'none'")
  10193. )
  10194. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  10195. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  10196. # its emscripten/embind glue generates invoker functions with `new
  10197. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  10198. # worker is governed by the policy delivered with the WORKER SCRIPT's
  10199. # own response — not the document's — so relaxing it here confines
  10200. # eval to that DOM-less worker context. The document policy below
  10201. # stays nonce-strict, and this response header has no effect when the
  10202. # file is merely fetched (a fetch's CSP is enforced against the
  10203. # requesting document, not the resource's own headers).
  10204. response.headers["Content-Security-Policy"] = (
  10205. "default-src 'self'; "
  10206. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  10207. "connect-src 'self'; "
  10208. "object-src 'none'; "
  10209. "base-uri 'self'; " + _frame_ancestors("'none'")
  10210. )
  10211. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  10212. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  10213. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  10214. # rule as the STEP worker above: the policy that governs a dedicated
  10215. # worker is the one delivered with its own script, so the wasm compile
  10216. # has to be permitted here rather than on the document. Unlike the STEP
  10217. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  10218. response.headers["Content-Security-Policy"] = (
  10219. "default-src 'self'; "
  10220. "script-src 'self' 'wasm-unsafe-eval'; "
  10221. "connect-src 'self'; "
  10222. "object-src 'none'; "
  10223. "base-uri 'self'; " + _frame_ancestors("'none'")
  10224. )
  10225. else:
  10226. # The streaming overlay is embedded same-origin by the URL builder's
  10227. # preview in Settings (#1422), so this branch allows 'self'.
  10228. # Embedding from anywhere else is still refused: 'self'
  10229. # only permits a framer on this origin, which is Bambuddy's own UI, so
  10230. # a clickjacking page on another host is blocked exactly as before.
  10231. # (The overlay draws status over a camera feed and its only interactive
  10232. # element is the logo link, so there is nothing to bait a click into
  10233. # even from a same-origin framer.) Cross-origin embedding of the
  10234. # overlay — Home Assistant on another port — remains what
  10235. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  10236. # allowlist in.
  10237. #
  10238. # The connected-app consent page (/connect/authorize) gets the same
  10239. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  10240. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  10241. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  10242. # requires every ancestor to be this origin, so a foreign page -- a
  10243. # sidebar link's site included -- still cannot frame the consent
  10244. # screen to bait a click.
  10245. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  10246. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  10247. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  10248. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  10249. # the policy served with their own script, so each gets it in its own
  10250. # branch above and the document policy stays as strict as it was.
  10251. response.headers["Content-Security-Policy"] = (
  10252. "default-src 'self'; "
  10253. f"script-src 'self' 'nonce-{csp_nonce}'; "
  10254. "style-src 'self' 'unsafe-inline'; "
  10255. "img-src 'self' data: blob:; "
  10256. "media-src 'self' blob:; "
  10257. "connect-src 'self' ws: wss:; "
  10258. "font-src 'self' data:; "
  10259. "object-src 'none'; "
  10260. "base-uri 'self'; "
  10261. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  10262. )
  10263. if request.url.scheme == "https":
  10264. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  10265. return response
  10266. @app.middleware("http")
  10267. async def auth_middleware(request, call_next):
  10268. """Enforce authentication on all API routes when auth is enabled.
  10269. This middleware provides defense-in-depth by checking auth at the API gateway level,
  10270. regardless of whether individual routes have auth dependencies.
  10271. """
  10272. from starlette.responses import JSONResponse
  10273. path = request.url.path
  10274. # Only apply to API routes
  10275. if not path.startswith("/api/"):
  10276. return await call_next(request)
  10277. # Allow public routes
  10278. if path in PUBLIC_API_ROUTES:
  10279. return await call_next(request)
  10280. # Allow public prefixes
  10281. for prefix in PUBLIC_API_PREFIXES:
  10282. if path.startswith(prefix):
  10283. return await call_next(request)
  10284. # Allow public patterns (read-only display data like thumbnails)
  10285. for pattern in PUBLIC_API_PATTERNS:
  10286. if pattern in path:
  10287. return await call_next(request)
  10288. # Check if auth is enabled. Fail CLOSED on any exception during the
  10289. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  10290. # an attacker who could force a DB exception (e.g. file-descriptor
  10291. # exhaustion via login flood) bypass auth on every protected endpoint.
  10292. # Only the probe is guarded: the request itself runs outside the try, so an
  10293. # error in a route surfaces as the 500 it is rather than as an auth outage.
  10294. try:
  10295. async with async_session() as db:
  10296. from backend.app.core.auth import is_auth_enabled
  10297. auth_enabled = await is_auth_enabled(db)
  10298. except Exception:
  10299. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  10300. return JSONResponse(
  10301. status_code=503,
  10302. content={"detail": "Authentication service temporarily unavailable"},
  10303. )
  10304. if not auth_enabled:
  10305. # Auth disabled, allow all requests
  10306. return await call_next(request)
  10307. # Auth is enabled - require valid token
  10308. auth_header = request.headers.get("Authorization")
  10309. x_api_key = request.headers.get("X-API-Key")
  10310. # Check for API key auth first
  10311. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  10312. # API key authentication - let the request through to be validated by route handler
  10313. # API keys are validated per-route since they have different permission levels
  10314. return await call_next(request)
  10315. # Check for JWT auth
  10316. if not auth_header or not auth_header.startswith("Bearer "):
  10317. return JSONResponse(
  10318. status_code=401,
  10319. content={"detail": "Authentication required"},
  10320. headers={"WWW-Authenticate": "Bearer"},
  10321. )
  10322. # Validate JWT token
  10323. import jwt
  10324. try:
  10325. from backend.app.core.auth import (
  10326. ALGORITHM,
  10327. SECRET_KEY,
  10328. _is_token_fresh,
  10329. get_user_by_username,
  10330. is_jti_revoked,
  10331. )
  10332. token = auth_header.replace("Bearer ", "")
  10333. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  10334. username = payload.get("sub")
  10335. if not username:
  10336. raise ValueError("No username in token")
  10337. jti = payload.get("jti")
  10338. if not jti:
  10339. raise ValueError("No jti in token")
  10340. iat = payload.get("iat")
  10341. # Verify user exists, is active, and token is still fresh (L-R8-A).
  10342. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  10343. # this session so the gateway adds a single pooled checkout, not two (#2572).
  10344. async with async_session() as db:
  10345. if await is_jti_revoked(jti, db):
  10346. return JSONResponse(
  10347. status_code=401,
  10348. content={"detail": "Token has been revoked"},
  10349. headers={"WWW-Authenticate": "Bearer"},
  10350. )
  10351. user = await get_user_by_username(db, username)
  10352. if not user or not user.is_active:
  10353. return JSONResponse(
  10354. status_code=401,
  10355. content={"detail": "User not found or inactive"},
  10356. headers={"WWW-Authenticate": "Bearer"},
  10357. )
  10358. if not _is_token_fresh(iat, user):
  10359. return JSONResponse(
  10360. status_code=401,
  10361. content={"detail": "Token no longer valid"},
  10362. headers={"WWW-Authenticate": "Bearer"},
  10363. )
  10364. except jwt.ExpiredSignatureError:
  10365. return JSONResponse(
  10366. status_code=401,
  10367. content={"detail": "Token has expired"},
  10368. headers={"WWW-Authenticate": "Bearer"},
  10369. )
  10370. except (jwt.InvalidTokenError, ValueError):
  10371. return JSONResponse(
  10372. status_code=401,
  10373. content={"detail": "Invalid token"},
  10374. headers={"WWW-Authenticate": "Bearer"},
  10375. )
  10376. except Exception:
  10377. # Not a bad token but a failure checking it (database, pool): refuse,
  10378. # as for the probe above, rather than answer 401 -- the frontend reads
  10379. # a 401 from /auth/me as final and signs the user out.
  10380. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  10381. return JSONResponse(
  10382. status_code=503,
  10383. content={"detail": "Authentication service temporarily unavailable"},
  10384. )
  10385. return await call_next(request)
  10386. @app.middleware("http")
  10387. async def trace_id_middleware(request, call_next):
  10388. """Stamp every HTTP request with a trace ID and echo it back.
  10389. Decorated AFTER auth_middleware on purpose: Starlette stacks
  10390. @app.middleware decorators LIFO, so the last-decorated runs first
  10391. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  10392. which means auth-middleware log lines (and every line emitted on the
  10393. way down to and back from the route handler) all carry the same
  10394. trace ID. If we put it before auth, auth's logs would be stamped
  10395. with the *previous* request's ID — useless for correlation.
  10396. Honours an inbound ``X-Trace-Id`` header so callers running their
  10397. own tracing can correlate their span IDs with our log lines, but
  10398. only if the value passes the whitelist gate in
  10399. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  10400. rejected (too long, contains control chars, etc.) silently triggers
  10401. a freshly minted server-side ID rather than failing the request.
  10402. The minted (or echoed) ID is set on a ContextVar so that every log
  10403. record emitted during the request — application logs *and* uvicorn's
  10404. access log — carries it via TraceIDFilter, and is also written to
  10405. the ``X-Trace-Id`` response header so clients can pin a server-side
  10406. log search to the exact request they made.
  10407. """
  10408. from backend.app.core.trace import (
  10409. generate_trace_id,
  10410. normalise_inbound_trace_id,
  10411. trace_id_var,
  10412. )
  10413. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  10414. trace_id = inbound if inbound is not None else generate_trace_id()
  10415. token = trace_id_var.set(trace_id)
  10416. try:
  10417. response = await call_next(request)
  10418. finally:
  10419. # Reset the ContextVar so a record emitted in a totally
  10420. # unrelated background task that just happens to inherit this
  10421. # context doesn't keep referencing this request's ID forever.
  10422. # In practice ContextVar.reset is best-effort under asyncio
  10423. # task-spawn semantics, but the cost is one attribute write so
  10424. # we may as well do it.
  10425. trace_id_var.reset(token)
  10426. response.headers["X-Trace-Id"] = trace_id
  10427. return response
  10428. # API routes
  10429. app.include_router(auth.router, prefix=app_settings.api_prefix)
  10430. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  10431. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  10432. app.include_router(users.router, prefix=app_settings.api_prefix)
  10433. app.include_router(groups.router, prefix=app_settings.api_prefix)
  10434. app.include_router(printers.router, prefix=app_settings.api_prefix)
  10435. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  10436. app.include_router(archives.router, prefix=app_settings.api_prefix)
  10437. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  10438. app.include_router(finance.router, prefix=app_settings.api_prefix)
  10439. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  10440. app.include_router(labels.router, prefix=app_settings.api_prefix)
  10441. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  10442. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  10443. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  10444. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  10445. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  10446. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  10447. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  10448. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  10449. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  10450. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  10451. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  10452. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  10453. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  10454. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  10455. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  10456. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  10457. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  10458. app.include_router(updates.router, prefix=app_settings.api_prefix)
  10459. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  10460. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  10461. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  10462. app.include_router(camera.router, prefix=app_settings.api_prefix)
  10463. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  10464. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  10465. app.include_router(projects.router, prefix=app_settings.api_prefix)
  10466. app.include_router(library.router, prefix=app_settings.api_prefix)
  10467. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  10468. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  10469. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  10470. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  10471. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  10472. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  10473. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  10474. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  10475. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  10476. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  10477. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  10478. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  10479. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  10480. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  10481. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  10482. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  10483. app.include_router(system.router, prefix=app_settings.api_prefix)
  10484. app.include_router(support.router, prefix=app_settings.api_prefix)
  10485. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  10486. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  10487. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  10488. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  10489. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  10490. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  10491. app.include_router(obico.router, prefix=app_settings.api_prefix)
  10492. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  10493. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  10494. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  10495. # Serve static files (React build)
  10496. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  10497. # Compressed, and cached for good where Vite hashed the name (#3175).
  10498. app.mount(
  10499. "/assets",
  10500. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  10501. name="assets",
  10502. )
  10503. if (app_settings.static_dir / "img").exists():
  10504. app.mount(
  10505. "/img",
  10506. StaticFiles(directory=app_settings.static_dir / "img"),
  10507. name="img",
  10508. )
  10509. if (app_settings.static_dir / "icons").exists():
  10510. app.mount(
  10511. "/icons",
  10512. StaticFiles(directory=app_settings.static_dir / "icons"),
  10513. name="icons",
  10514. )
  10515. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  10516. # falls through to the SPA catch-all and returns index.html, which the
  10517. # browser's font sanitizer rejects ("downloadable font: rejected by
  10518. # sanitizer").
  10519. if (app_settings.static_dir / "fonts").exists():
  10520. app.mount(
  10521. "/fonts",
  10522. StaticFiles(directory=app_settings.static_dir / "fonts"),
  10523. name="fonts",
  10524. )
  10525. @app.get("/")
  10526. async def serve_frontend():
  10527. """Serve the React frontend."""
  10528. index_file = app_settings.static_dir / "index.html"
  10529. if index_file.exists():
  10530. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10531. return {
  10532. "message": "Bambuddy API",
  10533. "docs": "/docs",
  10534. "frontend": "Build and place React app in /static directory",
  10535. }
  10536. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  10537. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  10538. # forever, but the HTML wrapping it is the only file that knows which hash
  10539. # is current. Without explicit cache-control headers Chromium decides
  10540. # heuristically (typically 10% of the time since Last-Modified) and on
  10541. # long-running kiosks happily serves stale HTML across browser restarts.
  10542. # That stale HTML references an old bundle hash, the old bundle is also
  10543. # in the disk cache, and the user ends up running pre-update JS forever
  10544. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  10545. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  10546. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  10547. @app.get("/health")
  10548. async def health_check():
  10549. """Health check endpoint."""
  10550. return {"status": "healthy"}
  10551. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  10552. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  10553. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  10554. # in deployment debugging.
  10555. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  10556. async def serve_manifest():
  10557. """Serve PWA manifest."""
  10558. manifest_file = app_settings.static_dir / "manifest.json"
  10559. if manifest_file.exists():
  10560. return FileResponse(manifest_file, media_type="application/manifest+json")
  10561. return {"error": "Manifest not found"}
  10562. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  10563. async def serve_service_worker():
  10564. """Serve service worker."""
  10565. sw_file = app_settings.static_dir / "sw.js"
  10566. if sw_file.exists():
  10567. return FileResponse(
  10568. sw_file,
  10569. media_type="application/javascript",
  10570. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  10571. )
  10572. return {"error": "Service worker not found"}
  10573. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  10574. async def serve_sw_register():
  10575. """Serve the service-worker registration bootstrap script.
  10576. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  10577. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  10578. """
  10579. reg_file = app_settings.static_dir / "sw-register.js"
  10580. if reg_file.exists():
  10581. return FileResponse(reg_file, media_type="application/javascript")
  10582. return {"error": "sw-register.js not found"}
  10583. # ── GCode viewer static files ────────────────────────────────────────────────
  10584. # Catch-all route for React Router (must be last)
  10585. @app.get("/{full_path:path}")
  10586. async def serve_spa(full_path: str):
  10587. """Serve React app for client-side routing."""
  10588. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  10589. if full_path.startswith("api/"):
  10590. from fastapi import HTTPException
  10591. raise HTTPException(status_code=404, detail="Not found")
  10592. index_file = app_settings.static_dir / "index.html"
  10593. if index_file.exists():
  10594. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10595. return {"error": "Frontend not built"}