main.py 634 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import re
  8. import secrets
  9. import shutil
  10. import time
  11. from contextlib import asynccontextmanager
  12. from datetime import datetime, timedelta, timezone
  13. from logging.handlers import RotatingFileHandler
  14. from pathlib import Path, PurePosixPath
  15. from typing import cast
  16. from urllib.parse import urlparse
  17. from fastapi import FastAPI
  18. from fastapi.encoders import jsonable_encoder
  19. from fastapi.exceptions import RequestValidationError
  20. from fastapi.responses import FileResponse, JSONResponse
  21. from fastapi.staticfiles import StaticFiles
  22. from sqlalchemy import delete, func, inspect as sa_inspect, or_, select, text, update
  23. from sqlalchemy.engine import CursorResult
  24. from sqlalchemy.exc import IntegrityError
  25. from sqlalchemy.orm.exc import StaleDataError
  26. from backend.app.api.routes import (
  27. ams_history,
  28. announcements,
  29. api_keys,
  30. archive_purge,
  31. archives,
  32. auth,
  33. bug_report,
  34. bulk,
  35. camera,
  36. camwall,
  37. cloud,
  38. connected_apps,
  39. discovery,
  40. external_links,
  41. filaments,
  42. finance,
  43. firmware,
  44. github_backup,
  45. groups,
  46. ha_sensors,
  47. inventory,
  48. kprofiles,
  49. labels,
  50. library,
  51. library_tags,
  52. library_trash,
  53. library_variants,
  54. local_backup,
  55. local_presets,
  56. location_ha_sensors,
  57. maintenance,
  58. makerworld,
  59. manyfold,
  60. metrics,
  61. mfa,
  62. notification_templates,
  63. notifications,
  64. obico,
  65. orca_cloud,
  66. overlay_branding,
  67. pending_uploads,
  68. pipeline_runs,
  69. print_log,
  70. print_queue,
  71. printer_locations,
  72. printer_sensor_history,
  73. printers,
  74. projects,
  75. scheduled_dryings,
  76. settings as settings_routes,
  77. slice_jobs,
  78. slicer_pipelines,
  79. slicer_presets,
  80. smart_plugs,
  81. sponsor_prompt,
  82. spoolbuddy,
  83. spoolman,
  84. spoolman_inventory,
  85. support,
  86. system,
  87. updates,
  88. user_notifications,
  89. users,
  90. virtual_printers,
  91. webhook,
  92. websocket,
  93. )
  94. from backend.app.api.routes.maintenance import (
  95. _get_printer_maintenance_internal,
  96. ensure_default_types,
  97. maintenance_alert_values,
  98. )
  99. from backend.app.api.routes.support import init_debug_logging
  100. from backend.app.core.config import APP_VERSION, settings as app_settings
  101. from backend.app.core.database import async_session, engine, init_db
  102. from backend.app.core.static_assets import AssetStaticFiles
  103. from backend.app.core.tasks import spawn_background_task
  104. from backend.app.core.websocket import ws_manager
  105. from backend.app.services import kprofile_drift, pause_eta, print_dispatch_context, slot_unlink_grace
  106. from backend.app.services.ams_assignment_lock import get_ams_assignment_lock
  107. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  108. from backend.app.services.archive_cost_estimate import (
  109. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  110. settle_archive_cost_estimate as _settle_archive_cost_estimate,
  111. )
  112. from backend.app.services.archive_purge import archive_purge_service
  113. from backend.app.services.bambu_ftp import (
  114. RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  115. FileNotOnPrinterError,
  116. cache_3mf_download,
  117. clear_3mf_cache,
  118. download_file_async,
  119. download_file_try_paths_async,
  120. ftps_handshake_blocked,
  121. get_cached_3mf,
  122. get_ftp_retry_settings,
  123. normalize_3mf_name,
  124. with_ftp_retry,
  125. )
  126. from backend.app.services.bambu_mqtt import PrinterState
  127. from backend.app.services.camera_light import camera_light
  128. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  129. from backend.app.services.github_backup import github_backup_service
  130. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  131. from backend.app.services.library_trash import library_trash_service
  132. from backend.app.services.local_backup import local_backup_service
  133. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  134. from backend.app.services.mqtt_relay import mqtt_relay
  135. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  136. from backend.app.services.notification_service import notification_service
  137. from backend.app.services.notify_live_activities import notify_live_activities
  138. from backend.app.services.notify_widgets import notify_widgets
  139. from backend.app.services.obico_detection import obico_detection_service
  140. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  141. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  142. from backend.app.services.print_scheduler import scheduler as print_scheduler
  143. from backend.app.services.print_storage import (
  144. REASON_FTP_TRANSFER_FAILED,
  145. REASON_FTPS_COOLOFF,
  146. external_storage_present,
  147. ftp_probe_paths,
  148. print_file_reachable_over_ftp,
  149. )
  150. from backend.app.services.printer_manager import (
  151. init_printer_connections,
  152. parse_plate_id,
  153. printer_manager,
  154. printer_state_to_dict,
  155. resolve_plate_id,
  156. )
  157. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  158. from backend.app.services.slot_nozzle import (
  159. nozzle_diameter_for_extruder,
  160. nozzle_flow_for_extruder,
  161. )
  162. from backend.app.services.smart_plug_manager import smart_plug_manager
  163. from backend.app.services.spool_assignment_notifications import (
  164. notify_missing_spool_assignments_on_print_start,
  165. )
  166. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  167. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  168. from backend.app.services.spoolman_tracking import (
  169. cleanup_tracking as _cleanup_spoolman_tracking,
  170. release_archived_slot_rows as _release_archived_spoolman_slots,
  171. report_usage as _report_spoolman_usage,
  172. store_print_data as _store_spoolman_print_data,
  173. )
  174. from backend.app.services.telegram_reactions import telegram_reaction_poller
  175. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  176. from backend.app.utils.ams_humidity import ams_humidity_percent
  177. from backend.app.utils.filament_types import printer_filament_type
  178. from backend.app.utils.fts_routing import extruder_for_inlet
  179. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  180. from backend.app.utils.print_jobs import is_internal_printer_job
  181. # =============================================================================
  182. # Dependency Check - runs before other imports to give helpful error messages
  183. # =============================================================================
  184. def _start_error_server(missing_packages: list):
  185. """Start a minimal HTTP server to display dependency errors in browser."""
  186. import os
  187. import signal
  188. from http.server import BaseHTTPRequestHandler, HTTPServer
  189. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  190. html = f"""<!DOCTYPE html>
  191. <html>
  192. <head>
  193. <title>Bambuddy - Setup Required</title>
  194. <style>
  195. body {{
  196. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  197. background: #0f172a; color: #e2e8f0;
  198. display: flex; justify-content: center; align-items: center;
  199. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  200. }}
  201. .container {{
  202. background: #1e293b; border-radius: 12px; padding: 40px;
  203. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  204. }}
  205. h1 {{ color: #f87171; margin-bottom: 10px; }}
  206. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  207. .packages {{
  208. background: #0f172a; border-radius: 8px; padding: 20px;
  209. margin: 20px 0; text-align: left;
  210. }}
  211. .packages ul {{ margin: 0; padding-left: 20px; }}
  212. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  213. .command {{
  214. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  215. margin: 15px 0; font-family: monospace; color: #4ade80;
  216. text-align: left; overflow-x: auto;
  217. }}
  218. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  219. </style>
  220. </head>
  221. <body>
  222. <div class="container">
  223. <h1>Setup Required</h1>
  224. <h2>Missing Python packages</h2>
  225. <div class="packages"><ul>{packages_html}</ul></div>
  226. <p>To fix, run this command on your server:</p>
  227. <div class="command">pip install -r requirements.lock</div>
  228. <p>Or if using a virtual environment:</p>
  229. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  230. <p class="note">After installing, restart Bambuddy:<br>
  231. <code>sudo systemctl restart bambuddy</code></p>
  232. </div>
  233. </body>
  234. </html>"""
  235. class ErrorHandler(BaseHTTPRequestHandler):
  236. def do_GET(self):
  237. self.send_response(503)
  238. self.send_header("Content-type", "text/html")
  239. self.end_headers()
  240. self.wfile.write(html.encode())
  241. def log_message(self, format, *args):
  242. print(f"[Error Server] {args[0]}")
  243. port = int(os.environ.get("PORT", 8000))
  244. print(f"\nStarting error server on http://0.0.0.0:{port}")
  245. print("Visit this URL in your browser to see the error details.\n")
  246. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  247. def shutdown(signum, frame):
  248. print("\nShutting down error server...")
  249. raise SystemExit(0)
  250. signal.signal(signal.SIGTERM, shutdown)
  251. signal.signal(signal.SIGINT, shutdown)
  252. server.serve_forever()
  253. def check_dependencies():
  254. """Check that all required packages are installed."""
  255. missing = []
  256. # Map of import name -> package name (for pip install)
  257. required = {
  258. "jwt": "PyJWT",
  259. "fastapi": "fastapi",
  260. "uvicorn": "uvicorn",
  261. "sqlalchemy": "sqlalchemy",
  262. "aiosqlite": "aiosqlite",
  263. "pydantic": "pydantic",
  264. "paho.mqtt": "paho-mqtt",
  265. }
  266. for module, package in required.items():
  267. try:
  268. __import__(module)
  269. except ImportError:
  270. missing.append(package)
  271. if missing:
  272. print("\n" + "=" * 60)
  273. print("ERROR: Missing required Python packages!")
  274. print("=" * 60)
  275. print(f"\nMissing packages: {', '.join(missing)}")
  276. print("\nTo fix, run:")
  277. print(" pip install -r requirements.lock")
  278. print("\nOr if using a virtual environment:")
  279. print(" ./venv/bin/pip install -r requirements.lock")
  280. print("=" * 60 + "\n")
  281. _start_error_server(missing)
  282. check_dependencies()
  283. # =============================================================================
  284. # Import settings first for logging configuration
  285. # Configure logging based on settings
  286. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  287. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  288. log_level = getattr(logging, log_level_str, logging.INFO)
  289. # Trace ID column ([-] when no request scope is active — startup, MQTT
  290. # callbacks, scheduled tasks not chained from a request — so the column
  291. # stays visually aligned and missing values are obvious in grep). See
  292. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  293. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  294. # Create root logger
  295. root_logger = logging.getLogger()
  296. root_logger.setLevel(log_level)
  297. # Trace-ID injection: this filter populates record.trace_id from the
  298. # per-request ContextVar so the format string above can reference it.
  299. # Attached to each HANDLER (not the root logger) because Python's
  300. # logging semantics only invoke a logger's filters on records that
  301. # *originated* at that logger — records propagated up from child
  302. # loggers (every named logger in the app) never trigger root's filter.
  303. # Putting it on the handlers means every record any handler emits gets
  304. # trace_id injected just before the formatter runs, regardless of which
  305. # logger created the record. Without this, the formatter raises
  306. # KeyError on every child-logger record and the record is silently
  307. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  308. # partially" bug we hit. See backend/app/core/trace.py for the
  309. # ContextVar the filter reads.
  310. from backend.app.core.logging_filters import RefusedHeaderRedactFilter
  311. from backend.app.core.response_redaction import RefusedHeaderResponseMask
  312. from backend.app.core.trace import TraceIDFilter
  313. _trace_id_filter = TraceIDFilter()
  314. # Console handler - always enabled
  315. console_handler = logging.StreamHandler()
  316. console_handler.setLevel(log_level)
  317. console_handler.setFormatter(logging.Formatter(log_format))
  318. console_handler.addFilter(_trace_id_filter)
  319. # A refused header's value (often a token) masked before the line is written.
  320. _refused_header_filter = RefusedHeaderRedactFilter()
  321. console_handler.addFilter(_refused_header_filter)
  322. root_logger.addHandler(console_handler)
  323. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  324. """Send uvicorn's own loggers to bambuddy.log as well.
  325. Neither reaches the root handler: uvicorn.access has propagate=False, and
  326. uvicorn.error propagates only to "uvicorn", which has propagate=False.
  327. uvicorn.access is the record of which endpoint changed server state;
  328. uvicorn.error is where an unhandled route error is logged with its
  329. traceback ("Exception in ASGI application").
  330. """
  331. for name in ("uvicorn.access", "uvicorn.error"):
  332. logging.getLogger(name).addHandler(handler)
  333. # File handler - only in production or if explicitly enabled
  334. if app_settings.log_to_file:
  335. log_file = app_settings.log_dir / "bambuddy.log"
  336. file_handler = RotatingFileHandler(
  337. log_file,
  338. maxBytes=app_settings.log_max_bytes,
  339. backupCount=app_settings.log_backup_count,
  340. encoding="utf-8",
  341. )
  342. file_handler.setLevel(log_level)
  343. file_handler.setFormatter(logging.Formatter(log_format))
  344. file_handler.addFilter(_trace_id_filter)
  345. file_handler.addFilter(_refused_header_filter)
  346. root_logger.addHandler(file_handler)
  347. logging.info("Logging to file: %s", log_file)
  348. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  349. # access logger with propagate=False by default, so without this attach
  350. # there is no on-disk record of which endpoint triggered a server-state
  351. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  352. # for exactly this reason. Filtered to write methods only
  353. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  354. # frontend don't churn the rotation window faster than it's useful.
  355. from backend.app.core.logging_filters import (
  356. CancelledPoolNoiseFilter,
  357. WriteRequestsOnlyFilter,
  358. )
  359. _attach_file_handler_to_uvicorn(file_handler)
  360. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  361. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  362. # Uvicorn's access logger has propagate=False (its own default), so the
  363. # root-attached TraceIDFilter never sees these records. Attach a
  364. # second instance directly so HTTP access lines carry the same trace
  365. # ID column as the application logs they correlate with.
  366. uvicorn_access_logger.addFilter(TraceIDFilter())
  367. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  368. # BaseHTTPMiddleware cancelling the inner task scope on client
  369. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  370. # underlying transaction leak; this filter only suppresses the residual
  371. # log records that pre-existing pools still emit during their cleanup.
  372. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  373. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  374. # handler (console included), whether or not file logging is on.
  375. from backend.app.core.logging_filters import ( # noqa: E402
  376. QueryTokenRedactFilter,
  377. ShutdownCancelledRequestFilter,
  378. )
  379. # First, so the traceback of a stream cancelled at shutdown is dropped before
  380. # the filters below render it.
  381. logging.getLogger("uvicorn.error").addFilter(ShutdownCancelledRequestFilter())
  382. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  383. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  384. logging.getLogger(_uvicorn_logger).addFilter(_refused_header_filter)
  385. # These stay at WARNING even in debug mode: at INFO/DEBUG httpx/httpcore log
  386. # full request URLs, and some carry credentials (bot tokens, webhook URLs, API
  387. # keys in the query). Same as the runtime log-level toggle in support.py.
  388. logging.getLogger("httpcore").setLevel(logging.WARNING)
  389. logging.getLogger("httpx").setLevel(logging.WARNING)
  390. # aiosqlite logs every statement with its parameters at DEBUG.
  391. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  392. # Reduce noise from third-party libraries in production
  393. if not app_settings.debug:
  394. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  395. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  396. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  397. # Track active prints: {(printer_id, filename): archive_id}
  398. _active_prints: dict[tuple[int, str], int] = {}
  399. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  400. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  401. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  402. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  403. # instead of running its own grab-now chain when present, so the finish photo
  404. # captures the better-framed pre-bed-drop moment without us having to force
  405. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  406. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  407. #
  408. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  409. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  410. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  411. # bank and the others are not — so the consumer can't tell them apart and
  412. # must not rotate again.
  413. _stage22_finish_frames: dict[int, bytes] = {}
  414. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  415. # `finally` block (whether it captured a frame or not). The consumer in
  416. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  417. # so the FINISH-state fallback path — where moment and completion are dispatched
  418. # back-to-back — doesn't race past the producer with an empty pop, and the
  419. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  420. # grab (Bambu printers allow only one RTSP client at a time).
  421. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  422. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  423. # layer-change and on print-progress advances (#2547) while the model is still
  424. # printing, then consumed by the FINISH-state finish-photo path when the
  425. # dispatcher recorded that it injected End G-code into this print. Bambu
  426. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  427. # plate-swap) has run, so a live grab there would capture the swapped/empty
  428. # plate.
  429. #
  430. # The load-bearing property: both drivers are print telemetry that stops before
  431. # the End G-code executes — no further layer_num increases, and mc_percent
  432. # freezes — so the last banked frame is always the finished print before the
  433. # swap. Anything added as a third driver must hold that same property.
  434. _inprint_frame_bank: dict[int, bytes] = {}
  435. # Monotonic timestamp of the last banked frame per printer — throttles banking
  436. # so tall prints don't add a camera grab on every layer.
  437. _inprint_frame_bank_ts: dict[int, float] = {}
  438. # Minimum seconds between banked frames, except the final object layer which
  439. # always refreshes for the best framing.
  440. _INPRINT_BANK_MIN_INTERVAL = 25.0
  441. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  442. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  443. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  444. # the first connected status update for that connection; transitions back
  445. # to False whenever we observe `state.connected = False` so the next
  446. # reconnect re-arms reconciliation. Keyed by printer_id.
  447. _printer_reconciled_since_connect: dict[int, bool] = {}
  448. # Same edge, same keying, for priming the printer's calibration table exactly
  449. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  450. # is otherwise filled only when someone opens the Profiles page or Configure
  451. # Slot, when a GitHub backup runs, or when the printer happens to answer
  452. # somebody else's query on the report topic. Until then the AMS slot card has
  453. # no K value to show on the printers whose trays carry none of their own
  454. # (#2854 — H2-series report cali_idx and nothing more).
  455. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  456. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  457. # {(printer_id, filename): archive_id}
  458. _expected_prints: dict[tuple[int, str], int] = {}
  459. # Archives of the running prints Bambuddy dispatched itself: adopted from an
  460. # expected print, or found with Bambuddy's dispatch marker. _active_prints holds
  461. # every print on_print_start archived, those started from Bambu Studio, Handy or
  462. # the printer's screen included, so it is no proof of ownership on its own.
  463. _owned_print_archive_ids: set[int] = set()
  464. # What a dispatch registered for its print, keyed (printer_id, archive_id):
  465. # plates of one archive print on two printers at once, each with its own.
  466. # Track AMS mapping for prints: {(printer_id, archive_id): [global_tray_id_per_slot]}
  467. # Used by usage tracker to map 3MF slots to physical AMS trays
  468. _print_ams_mappings: dict[tuple[int, int], list[int]] = {}
  469. # Track cost center selection for the current print run: {(printer_id, archive_id): cost_center_id}
  470. _print_cost_center_ids: dict[tuple[int, int], int] = {}
  471. # Track plate_id for prints from multi-plate 3MFs: {(printer_id, archive_id): plate_id}
  472. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  473. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  474. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  475. # for the queue path. Cleared on print completion or TTL eviction.
  476. _print_plate_ids: dict[tuple[int, int], int] = {}
  477. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  478. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  479. _last_progress_milestone: dict[int, int] = {}
  480. # Track whether first layer complete notification has been sent for current print
  481. _first_layer_notified: dict[int, bool] = {}
  482. # Track whether we already sent a kill-switch stop for the current unauthorized print
  483. _unauthorized_print_kill_sent: set[int] = set()
  484. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  485. # lookup briefly so an unknown active print does not query the database on
  486. # every status frame. A short TTL keeps settings changes responsive.
  487. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  488. _kill_switch_setting_cache: tuple[bool, float] | None = None
  489. # Provider notification started when the kill switch stops a print. The later
  490. # MQTT print-complete callback awaits this task and only sends its regular
  491. # provider notification when the immediate attempt failed.
  492. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  493. # HMS faults already notified, with when each was last seen:
  494. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  495. # fault that flickers beside a held notice was forgotten on every gap and
  496. # notified on every return (#3226). The window is long because the measured
  497. # gaps reach 64 s.
  498. _notified_hms_errors: dict[int, dict[str, float]] = {}
  499. _HMS_CLEAR_GRACE_SECONDS = 600.0
  500. # The print state each printer was last seen in, and the faults recorded before
  501. # it last changed, which are forgotten as soon as they are gone (see
  502. # _take_new_hms_faults).
  503. _hms_print_state: dict[int, str] = {}
  504. _hms_forget_when_gone: dict[int, set[str]] = {}
  505. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  506. # Used for snapshot-diff detection at print completion
  507. _timelapse_baselines: dict[int, set[str]] = {}
  508. # Printers whose baseline above was taken off a card that could not be read,
  509. # so it is empty without the card being empty (#3412).
  510. _timelapse_baselines_unread: set[int] = set()
  511. # Track printers waiting for bed to cool after print completion.
  512. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  513. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  514. _bed_cool_waiters: dict[int, dict] = {}
  515. # Track printers where the user explicitly stopped the print from the queue UI.
  516. # When on_print_complete fires with status "failed" for these printers we treat it
  517. # as "cancelled" (stopped by user) so the correct notification email is sent.
  518. _user_stopped_printers: set[int] = set()
  519. # Printers whose running print the kill switch stopped. Their completion is a
  520. # cancel with the reason "killSwitch", not the "failed" the printer reports.
  521. _kill_switch_stopped: set[int] = set()
  522. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  523. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  524. # holds the previous observation so we only fire on the True → False edge (a
  525. # False → False repeat doesn't notify; an initial False at startup doesn't
  526. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  527. # holds the per-printer pending asyncio task that fires the notification
  528. # after a debounce window — cancelled if the printer reconnects before the
  529. # window elapses, so transient MQTT blips don't flood the user.
  530. _printer_last_connected: dict[int, bool] = {}
  531. # Printers whose relay offline event went out, so the reconnect publishes the
  532. # matching online event and a blip shorter than the debounce publishes neither.
  533. _printer_offline_published: set[int] = set()
  534. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  535. # Debounce: a printer must stay offline this long before we notify. Sized
  536. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  537. # so a single stale-trigger cooldown isn't enough to fire — only a real
  538. # offline that survives one reconnect attempt notifies.
  539. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  540. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  541. # when status="failed" to label the print's failure_reason in archives.
  542. #
  543. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  544. # which is wrong on two counts:
  545. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  546. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  547. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  548. # the public wiki) as part of its user-cancel sequence. Matching on the module
  549. # alone caused user-cancellations to be archived as "Layer shift" failures.
  550. # We now match by full short code only — anything not in this map leaves
  551. # failure_reason=None rather than guessing.
  552. # Values are the canonical camelCase failure-reason keys, NOT display labels
  553. # (issue #2974). The vocabulary is enforced on writes by
  554. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  555. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  556. # Statistics breakdown. Storing a label here instead put a second spelling of
  557. # the same cause into one column: the Failure Analysis widget groups on the raw
  558. # value, so a print the backend classified and an identical one a user
  559. # classified counted as two different reasons, and the label form could never
  560. # be translated because there was no key for ``t()`` to resolve.
  561. _HMS_FAILURE_REASONS: dict[str, str] = {
  562. # Layer shift / step loss
  563. "0300_4057": "layerShift",
  564. "0300_4068": "layerShift",
  565. "0300_800C": "layerShift",
  566. # Filament runout (printer-side & per-AMS-slot)
  567. "0300_8004": "filamentRunout",
  568. "0700_8011": "filamentRunout",
  569. "0701_8011": "filamentRunout",
  570. "0702_8011": "filamentRunout",
  571. "0703_8011": "filamentRunout",
  572. "0704_8011": "filamentRunout",
  573. "0705_8011": "filamentRunout",
  574. "0706_8011": "filamentRunout",
  575. "0707_8011": "filamentRunout",
  576. "07FF_8011": "filamentRunout",
  577. # Clogged nozzle / extruder
  578. "0300_4006": "cloggedNozzle",
  579. "0300_8016": "cloggedNozzle",
  580. "0300_801C": "cloggedNozzle",
  581. "0700_8003": "cloggedNozzle",
  582. "0700_8007": "cloggedNozzle",
  583. "0700_8013": "cloggedNozzle",
  584. "0701_8003": "cloggedNozzle",
  585. "0701_8007": "cloggedNozzle",
  586. "0701_8013": "cloggedNozzle",
  587. "0702_8003": "cloggedNozzle",
  588. # AI print monitoring — spaghetti / the model coming off the plate.
  589. # `spaghettiDetached` is a key the archive editor already offers for this
  590. # failure mode, not a new one, so a derived reason opens the dropdown on
  591. # that option rather than blank — and survives the next save, which clears
  592. # any value the editor does not recognise.
  593. #
  594. # A module-0x0C row is safe here despite the warning above: that warning is
  595. # about matching on the module alone, and 0C00_8042 is a full short code
  596. # with a documented meaning ("The AI print monitor has detected a spaghetti
  597. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  598. # cannot collide.
  599. #
  600. # 0300_8003's own text ends "before continuing your print", but on an X2D
  601. # it arrives with the print already paused, offering only
  602. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  603. #
  604. # Two neighbours are left out on purpose, so this does not get re-derived:
  605. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  606. # reads as a warning about a print that is still running, not a halt.
  607. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  608. # the waste chute. That is not the print failing.
  609. #
  610. # That line is drawn from the text, not from `severity`, because severity
  611. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  612. # module/error word with no level in it, and bambu_mqtt.py gives every
  613. # print_error entry a flat severity=3. Matching on the short code alone is
  614. # the right shape for derive_failure_reason, not an omission.
  615. "0300_8003": "spaghettiDetached",
  616. "0C00_8042": "spaghettiDetached",
  617. }
  618. def _hms_short_code(attr: int, code: int | str) -> str:
  619. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  620. if isinstance(code, str):
  621. code_int = int(code.replace("0x", ""), 16) if code else 0
  622. else:
  623. code_int = int(code or 0)
  624. attr_int = int(attr or 0)
  625. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  626. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  627. """Derive the failure_reason key for an archived print.
  628. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  629. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  630. no HMS code matches (don't guess — null is honest). The keys are the
  631. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  632. translated at render time.
  633. """
  634. if status in ("aborted", "cancelled"):
  635. return "userCancelled"
  636. if status != "failed":
  637. return None
  638. for err in hms_errors or []:
  639. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  640. if short_code in _HMS_FAILURE_REASONS:
  641. return _HMS_FAILURE_REASONS[short_code]
  642. return None
  643. # Track created_by_id for expected prints so the user email can be sent even when
  644. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  645. # {(printer_id, filename): created_by_id}
  646. _expected_print_creators: dict[tuple[int, str], int] = {}
  647. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  648. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  649. # tag tuple changes for the slot. Cleared when the slot is reported empty
  650. # so remove + reinsert reliably re-prompts the UI.
  651. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  652. async def _broadcast_unknown_tag(
  653. *,
  654. printer_id: int,
  655. ams_id: int,
  656. tray_id: int,
  657. tag_uid: str,
  658. tray_uuid: str,
  659. tray_type: str | None = None,
  660. tray_color: str | None = None,
  661. tray_sub_brands: str | None = None,
  662. tray_count: int | None = None,
  663. ) -> None:
  664. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  665. _logger = logging.getLogger(__name__)
  666. slot_key = (ams_id, tray_id)
  667. tag_key = (tag_uid or "", tray_uuid or "")
  668. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  669. if per_printer.get(slot_key) == tag_key:
  670. _logger.debug(
  671. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  672. printer_id,
  673. ams_id,
  674. tray_id,
  675. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  676. )
  677. return
  678. _logger.info(
  679. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  680. printer_id,
  681. ams_id,
  682. tray_id,
  683. tray_type,
  684. tray_color,
  685. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  686. )
  687. # Broadcast first; only commit the dedup if the WS write succeeds.
  688. # If broadcast raises, the next MQTT push retries instead of being
  689. # permanently silenced by a poisoned dedup entry.
  690. await ws_manager.broadcast(
  691. {
  692. "type": "unknown_tag",
  693. "printer_id": printer_id,
  694. "ams_id": ams_id,
  695. "tray_id": tray_id,
  696. "tag_uid": tag_uid,
  697. "tray_uuid": tray_uuid,
  698. "tray_type": tray_type,
  699. "tray_color": tray_color,
  700. "tray_sub_brands": tray_sub_brands,
  701. "tray_count": tray_count,
  702. }
  703. )
  704. per_printer[slot_key] = tag_key
  705. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  706. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  707. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  708. if per_printer is None:
  709. return
  710. per_printer.pop((ams_id, tray_id), None)
  711. # TTL for expected-print entries: evict registrations older than this to prevent
  712. # unbounded growth when a print is registered but never starts (e.g. printer
  713. # disconnect, app restart, print started from the printer panel).
  714. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  715. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  716. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  717. # Cleanup loop interval
  718. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  719. _expected_prints_cleanup_task: asyncio.Task | None = None
  720. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  721. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  722. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  723. possible_keys: list[tuple[int, str]] = []
  724. filename = (state.gcode_file or state.current_print or "").strip()
  725. subtask_name = (state.subtask_name or "").strip()
  726. if subtask_name:
  727. possible_keys.append((printer_id, subtask_name))
  728. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  729. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  730. if filename:
  731. base_name = filename.rsplit("/", 1)[-1]
  732. if base_name.endswith(".gcode.3mf"):
  733. root_name = base_name[: -len(".gcode.3mf")]
  734. possible_keys.append((printer_id, root_name))
  735. possible_keys.append((printer_id, base_name))
  736. possible_keys.append((printer_id, f"{root_name}.gcode"))
  737. possible_keys.append((printer_id, f"{root_name}.3mf"))
  738. elif base_name.endswith(".3mf"):
  739. root_name = base_name[: -len(".3mf")]
  740. possible_keys.append((printer_id, root_name))
  741. possible_keys.append((printer_id, base_name))
  742. elif base_name.endswith(".gcode"):
  743. root_name = base_name[: -len(".gcode")]
  744. possible_keys.append((printer_id, root_name))
  745. possible_keys.append((printer_id, f"{root_name}.3mf"))
  746. possible_keys.append((printer_id, base_name))
  747. else:
  748. possible_keys.append((printer_id, base_name))
  749. possible_keys.append((printer_id, f"{base_name}.3mf"))
  750. return possible_keys
  751. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  752. """The id of who started the print, unless that user has been deleted since.
  753. Deleting a user forgets them in printer_manager, but a print that ended a
  754. moment before still holds them.
  755. """
  756. if not print_user or print_user.get("user_id") is None:
  757. return None
  758. from backend.app.models.user import User
  759. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  760. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  761. """Check the cheap, process-local print ownership signals."""
  762. if printer_manager.get_current_print_user(printer_id):
  763. return True
  764. return any(
  765. key in _expected_prints or _active_prints.get(key) in _owned_print_archive_ids
  766. for key in _build_status_print_keys(printer_id, state)
  767. )
  768. def _reported_print_names(printer_id: int, state: PrinterState) -> set[str]:
  769. """The names the printer reports for its print, as it echoes them (spaces become underscores)."""
  770. return {_normalise_subtask_name(name) for _pid, name in _build_status_print_keys(printer_id, state)} - {""}
  771. async def _printing_archive_without_job_id(
  772. db, printer_id: int, reported: set[str], *, dispatched_only: bool, live_only: bool = False
  773. ):
  774. """The newest printing archive on ``printer_id`` of a print that reported no job id, under a reported name.
  775. An archive with a real id of its own is a print that reported one: a "0"
  776. print is not it, even under the same name (one whose completion was missed
  777. would otherwise cover it). ``dispatched_only`` keeps to archives carrying
  778. Bambuddy's dispatch marker; ``live_only`` leaves out deleted ones.
  779. """
  780. from backend.app.models.archive import PrintArchive
  781. query = select(PrintArchive).where(
  782. PrintArchive.printer_id == printer_id,
  783. PrintArchive.status == "printing",
  784. or_(PrintArchive.subtask_id.is_(None), PrintArchive.subtask_id.in_(("", "0"))),
  785. )
  786. if dispatched_only:
  787. query = query.where(or_(PrintArchive.billing_run_id.is_not(None), PrintArchive.created_by_id.is_not(None)))
  788. if live_only:
  789. query = query.where(PrintArchive.deleted_at.is_(None))
  790. archives = await db.execute(query.order_by(PrintArchive.created_at.desc()))
  791. return next((a for a in archives.scalars() if _archive_name_forms(a) & reported), None)
  792. async def running_print_archive(db, printer_id: int, state: PrinterState, *, printing_only: bool, by_name: bool):
  793. """The archive of the print running on ``printer_id``, or None (#3327).
  794. By the print's subtask_id first, which the firmware mints per print; with
  795. ``printing_only`` only an archive that is still printing (a leftover row of
  796. a completion never seen must not stand in for another job). A print
  797. started outside the cloud (Bambu Studio over LAN, Handy, the printer's
  798. screen) reports subtask_id "0", which links it to nothing: the archive
  799. Bambuddy bound to the running print comes next, the one completion charges
  800. and photographs. A restart forgets that binding and rebinds only Bambuddy's
  801. own prints, so with ``by_name`` a "0" print last falls back to its printing
  802. archive under the name the printer reports. That can be an earlier run of
  803. the same name whose completion was missed while Bambuddy was down: good
  804. enough for a plate label or a cover, not for which objects skip-objects
  805. offers, so those callers leave it off. None until the archive exists, and
  806. never a deleted one.
  807. """
  808. from backend.app.models.archive import PrintArchive
  809. from backend.app.services.print_log import open_run_on_printer
  810. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  811. if subtask_id not in ("", "0"):
  812. # The run open on the printer for this job: the archive row is shared
  813. # by every plate of it, its printer and job id the latest start's.
  814. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  815. if run is not None and run.archive_id is not None:
  816. archive = await db.scalar(
  817. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  818. )
  819. if archive is not None:
  820. return archive
  821. query = select(PrintArchive).where(
  822. PrintArchive.printer_id == printer_id,
  823. PrintArchive.subtask_id == subtask_id,
  824. PrintArchive.deleted_at.is_(None),
  825. )
  826. if printing_only:
  827. query = query.where(PrintArchive.status == "printing")
  828. archive = await db.scalar(query.order_by(PrintArchive.created_at.desc()).limit(1))
  829. if archive is not None:
  830. return archive
  831. bound = next(
  832. (_active_prints[key] for key in _build_status_print_keys(printer_id, state) if key in _active_prints),
  833. None,
  834. )
  835. if bound is not None:
  836. return await db.scalar(select(PrintArchive).where(PrintArchive.id == bound, PrintArchive.deleted_at.is_(None)))
  837. if not by_name or subtask_id != "0":
  838. return None
  839. reported = _reported_print_names(printer_id, state)
  840. if not reported:
  841. return None
  842. return await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=False, live_only=True)
  843. def _bind_active_print(
  844. printer_id: int,
  845. archive_id: int,
  846. archive_filename: str | None,
  847. filename: str | None = None,
  848. subtask_name: str | None = None,
  849. ) -> None:
  850. """Track a running print under every name its completion may report.
  851. One set for every path that binds a print (new archive, expected print,
  852. restart resume, fallback): the archive's file name, the name the printer
  853. reported, and the subtask with and without ``.3mf``. Paths that registered
  854. fewer names lost the bound archive at completion, and with it the plate
  855. restore's height (#3240), whenever MQTT reported a name they had left out.
  856. """
  857. for name in {archive_filename, filename, f"{subtask_name}.3mf" if subtask_name else None, subtask_name}:
  858. if name:
  859. _active_prints[(printer_id, name)] = archive_id
  860. async def _archive_of_open_run(printer_id: int, subtask_id: str | None = None) -> int | None:
  861. """The archive of the run open on the printer, if it is still there.
  862. With ``subtask_id``, only a run of that job."""
  863. try:
  864. from backend.app.models.archive import PrintArchive
  865. from backend.app.services.print_log import open_run_on_printer
  866. async with async_session() as db:
  867. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  868. if run is None or run.archive_id is None:
  869. return None
  870. return await db.scalar(
  871. select(PrintArchive.id).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  872. )
  873. except Exception as e:
  874. logging.getLogger(__name__).warning("[RUN] Could not read the open run of printer %s: %s", printer_id, e)
  875. return None
  876. async def _announce_discarded_runs(discarded, printer_id: int) -> None:
  877. """Publish the runs ``discard_open_runs`` dropped (archive redesign):
  878. each announced by run/started, now gone without an end."""
  879. if not discarded:
  880. return
  881. try:
  882. from backend.app.models.printer import Printer
  883. async with async_session() as db:
  884. printer = (
  885. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  886. ).first()
  887. if printer is not None:
  888. for run in discarded:
  889. await mqtt_relay.on_run_discarded(run, printer.serial_number, printer.name)
  890. except Exception as e:
  891. logging.getLogger(__name__).debug("[RUN] Could not announce discarded runs on printer %s: %s", printer_id, e)
  892. async def _publish_run_completed(run_id: int | None, printer_id: int) -> None:
  893. """Publish the run a print's end just wrote on the MQTT relay (archive
  894. redesign); nothing without one. Never in the way of the completion."""
  895. if run_id is None:
  896. return
  897. try:
  898. from backend.app.models.archive import PrintArchive
  899. from backend.app.models.print_log import PrintLogEntry
  900. from backend.app.models.printer import Printer
  901. async with async_session() as db:
  902. run = await db.get(PrintLogEntry, run_id)
  903. printer = (
  904. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  905. ).first()
  906. archive = await db.get(PrintArchive, run.archive_id) if run is not None and run.archive_id else None
  907. if run is not None and printer is not None:
  908. await mqtt_relay.on_run_completed(run, archive, printer.serial_number, printer.name)
  909. except Exception as e:
  910. logging.getLogger(__name__).debug("[RUN] Could not publish the end of run %s: %s", run_id, e)
  911. async def _open_run_for(archive_id: int, printer_id: int, subtask_id: str | None = None) -> None:
  912. """Write the run of the print that just started on the archive (archive
  913. redesign). In a session of its own and never in the way of the print
  914. start: until its readers move over, the archive still carries the print.
  915. The archive's start must be committed before. ``subtask_id`` is the
  916. printer's job, which finds the run again at a resume."""
  917. try:
  918. from backend.app.models.archive import PrintArchive
  919. from backend.app.models.printer import Printer
  920. from backend.app.services.print_log import open_run, open_run_on_printer, run_snapshot
  921. async with async_session() as db:
  922. archive = await db.get(PrintArchive, archive_id)
  923. if archive is None:
  924. return
  925. printer = (
  926. await db.execute(select(Printer.name, Printer.serial_number).where(Printer.id == printer_id))
  927. ).first()
  928. printer_name = printer.name if printer is not None else None
  929. already = await open_run_on_printer(db, printer_id)
  930. before = run_snapshot(already) if already is not None else None
  931. run = await open_run(
  932. db,
  933. archive,
  934. printer_id=printer_id,
  935. printer_name=printer_name,
  936. plate_id=_print_plate_ids.get((printer_id, archive_id)),
  937. subtask_id=subtask_id,
  938. )
  939. await db.commit()
  940. # Once per print: a resume or a repeated start finds the run it opened.
  941. # A new one replaced the run still open there (open_run): that one's
  942. # print ended unseen.
  943. # Compared by start too: SQLite can give the new run the id of the one
  944. # it replaced.
  945. replaced = (
  946. run is not None and before is not None and (before.id != run.id or before.started_at != run.started_at)
  947. )
  948. if run is not None and printer is not None and (before is None or replaced):
  949. if replaced:
  950. await _announce_discarded_runs([before], printer_id)
  951. try:
  952. await mqtt_relay.on_run_started(run, archive, printer.serial_number, printer_name)
  953. except Exception:
  954. pass # Don't fail the print start if MQTT fails
  955. except Exception as e:
  956. logging.getLogger(__name__).warning("[RUN] Could not open the run of archive %s: %s", archive_id, e)
  957. async def _drop_replaced_plate_videos(
  958. db, archive_id: int, plate_id: int | None, stale_relpath: str | None, logger: logging.Logger
  959. ) -> None:
  960. """Delete the videos a reprint of a plate replaces: ``stale_relpath``, the
  961. one the archive showed (when print start judged it this plate's), and
  962. those of the archive's earlier runs of the same plate. A plate keeps one
  963. video, as when the archive held the only one; another plate's stays. The
  964. runs that held them lose them. Commits."""
  965. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, PrintLogEntry
  966. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  967. runs = select(PrintLogEntry).where(
  968. PrintLogEntry.archive_id == archive_id, PrintLogEntry.timelapse_path.is_not(None)
  969. )
  970. with_video = list(await db.scalars(runs.execution_options(**{INCLUDE_OPEN_RUNS: True})))
  971. paths = {stale_relpath} if stale_relpath else set()
  972. if plate_id is not None:
  973. paths |= {r.timelapse_path for r in with_video if r.plate_id == plate_id}
  974. # A video another plate's run holds is that plate's.
  975. paths -= {r.timelapse_path for r in with_video if r.plate_id is not None and r.plate_id != plate_id}
  976. if not paths:
  977. return
  978. for run in with_video:
  979. if run.timelapse_path in paths:
  980. run.timelapse_path = None
  981. await db.commit()
  982. for relpath in sorted(p for p in paths if p):
  983. try:
  984. stale_path = safe_join_under(app_settings.base_dir, relpath, http=False)
  985. if stale_path.is_file():
  986. stale_path.unlink()
  987. logger.info("Deleted stale timelapse %s on reprint of archive %s", relpath, archive_id)
  988. except (OSError, PathTraversalError) as e:
  989. logger.warning("Failed to delete stale timelapse %s on reprint: %s", relpath, e)
  990. def _mark_owned_if_dispatched(archive) -> None:
  991. """Remember a running print's archive as Bambuddy's when it carries a
  992. dispatch marker Bambuddy writes itself: ``billing_run_id`` (minted per
  993. dispatch in the scheduler) or ``created_by_id`` (from the queue item)."""
  994. if archive.billing_run_id is not None or archive.created_by_id is not None:
  995. _owned_print_archive_ids.add(archive.id)
  996. async def _is_printer_kill_switch_enabled_cached() -> bool:
  997. """Return the kill-switch setting without querying on every MQTT frame."""
  998. global _kill_switch_setting_cache
  999. now = time.monotonic()
  1000. if _kill_switch_setting_cache is not None:
  1001. enabled, expires_at = _kill_switch_setting_cache
  1002. if now < expires_at:
  1003. return enabled
  1004. async with async_session() as db:
  1005. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  1006. enabled = await is_printer_kill_switch_enabled(db)
  1007. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  1008. return enabled
  1009. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  1010. """Resolve whether the current print was started by Bambuddy.
  1011. ``None`` means identity is not yet safe to decide. The kill switch must
  1012. defer in that case: stopping a print is irreversible, and the first status
  1013. frames after a restart may arrive before all subtask fields are populated.
  1014. """
  1015. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1016. return True
  1017. # The printer's built-in calibration runs (Bambuddy's Calibrate, the
  1018. # printer's screen) play gcode from its read-only system partition, where no
  1019. # user file can be. Only that path counts: a calibration *name* proves
  1020. # nothing, since Bambu Studio's pressure-advance print reports a user-style
  1021. # path, and any print can be given that name.
  1022. if str(getattr(state, "gcode_file", "") or "").startswith("/usr/"):
  1023. return True
  1024. # A1, A1 Mini, P1 and A2L report the same calibration as a bare file name,
  1025. # which nothing distinguishes from a user's file given that name, so it is
  1026. # not exempt: with the kill switch on, calibrate on those printers with the
  1027. # switch off.
  1028. possible_keys = _build_status_print_keys(printer_id, state)
  1029. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  1030. # is on disk. subtask_id is minted per print and pins the answer to the job
  1031. # actually running, rather than to an unrelated one that reuses a filename.
  1032. raw_subtask_id = getattr(state, "subtask_id", None)
  1033. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  1034. if subtask_id == "":
  1035. # Not reported yet: the first frames after a restart can lack it.
  1036. return None
  1037. from backend.app.models.archive import PrintArchive
  1038. if subtask_id == "0":
  1039. # A print started outside the cloud from Bambu Studio, Handy or the
  1040. # printer's screen reports "0", so there is no id to match: one of
  1041. # Bambuddy's printing archives on this printer under the name the
  1042. # printer reports, compared as the printer echoes names (spaces become
  1043. # underscores). Nothing reported to compare yet: wait.
  1044. reported = _reported_print_names(printer_id, state)
  1045. if not reported:
  1046. return None
  1047. archive = await _printing_archive_without_job_id(db, printer_id, reported, dispatched_only=True)
  1048. else:
  1049. from backend.app.services.print_log import open_run_on_printer
  1050. # This job's run open on the printer: the archive is shared by every
  1051. # plate of it, and its status, printer and job id are the latest
  1052. # start's, which may be another printer's.
  1053. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  1054. archive = await db.get(PrintArchive, run.archive_id) if run is not None and run.archive_id else None
  1055. if archive is None:
  1056. result = await db.execute(
  1057. select(PrintArchive)
  1058. .where(
  1059. PrintArchive.printer_id == printer_id,
  1060. PrintArchive.status == "printing",
  1061. PrintArchive.subtask_id == subtask_id,
  1062. )
  1063. .order_by(PrintArchive.created_at.desc())
  1064. .limit(1)
  1065. )
  1066. archive = result.scalar_one_or_none()
  1067. # An archive row on its own proves nothing: `on_print_start` archives every
  1068. # print it observes, including ones started from Bambu Studio or Handy, and
  1069. # stamps them with the same status and subtask_id. Authorizing on its mere
  1070. # existence would disable the kill switch the moment the 3MF finishes
  1071. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  1072. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  1073. # (carried over from the queue item that started it).
  1074. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  1075. # Rehydrate the fast in-memory path for subsequent status frames. Include
  1076. # both the archive filename and every normalized key reported by MQTT.
  1077. _owned_print_archive_ids.add(archive.id)
  1078. _active_prints[(printer_id, archive.filename)] = archive.id
  1079. for key in possible_keys:
  1080. _active_prints[key] = archive.id
  1081. return True
  1082. # No dispatch marker. Before calling this someone else's print, check whether
  1083. # Bambuddy has a job of its own running on this printer: a library-file
  1084. # dispatch has no archive at send time, and an archive created seconds later
  1085. # by `on_print_start` carries neither marker. The queue row, which the
  1086. # scheduler commits to status="printing" before the MQTT send, is the one
  1087. # durable record every Bambuddy print has. It cannot be tied to this
  1088. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  1089. # print is irreversible, and refusing to act costs nothing but a log line.
  1090. from backend.app.models.print_queue import PrintQueueItem
  1091. dispatched_here = await db.scalar(
  1092. select(PrintQueueItem.id)
  1093. .where(
  1094. PrintQueueItem.printer_id == printer_id,
  1095. PrintQueueItem.status == "printing",
  1096. )
  1097. .limit(1)
  1098. )
  1099. if dispatched_here is not None:
  1100. return None
  1101. return False
  1102. async def _send_kill_switch_provider_notification(
  1103. printer_id: int,
  1104. printer_name: str,
  1105. data: dict,
  1106. ) -> bool:
  1107. """Send the immediate print-stopped provider notification.
  1108. Returning a success flag lets the normal MQTT completion path retry when
  1109. this early notification could not be delivered.
  1110. """
  1111. logger = logging.getLogger(__name__)
  1112. try:
  1113. async with async_session() as db:
  1114. from backend.app.services.print_log import open_run_on_printer
  1115. # The print it stopped, for {archive_id} / {run_id}: the completion
  1116. # that would name them skips its notification after this one.
  1117. run = await open_run_on_printer(db, printer_id)
  1118. await notification_service.on_print_complete(
  1119. printer_id,
  1120. printer_name,
  1121. "stopped",
  1122. data,
  1123. db,
  1124. archive_data={"archive_id": run.archive_id, "run_id": run.id} if run is not None else None,
  1125. )
  1126. return True
  1127. except Exception as e:
  1128. logger.warning(
  1129. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  1130. printer_id,
  1131. e,
  1132. )
  1133. return False
  1134. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  1135. """Wait for an immediate kill-switch notification, if one was scheduled."""
  1136. if task is None:
  1137. return False
  1138. try:
  1139. return await task
  1140. except Exception as e:
  1141. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  1142. return False
  1143. async def _run_needs_energy_start(archive, printer_id: int, db) -> bool:
  1144. """At a resume: whether the print's run still lacks its energy start
  1145. reading. The archive's may be an earlier print's. Commits a reading
  1146. found on the archive for this run onto it."""
  1147. try:
  1148. from backend.app.services.print_log import run_needs_energy_start
  1149. needs = await run_needs_energy_start(db, archive, printer_id=printer_id)
  1150. await db.commit()
  1151. return needs
  1152. except Exception as e:
  1153. logging.getLogger(__name__).warning("[RUN] Energy start of archive %s's run not checked: %s", archive.id, e)
  1154. return archive.energy_start_kwh is None
  1155. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  1156. """Capture the smart plug lifetime counter on the archive at print start.
  1157. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  1158. tracking survives a backend restart mid-print. The print-end handler reads
  1159. this value back from the DB and computes the delta against the current
  1160. plug counter.
  1161. """
  1162. _logger = logging.getLogger(__name__)
  1163. try:
  1164. candidates = await energy_plug_candidates(db, printer_id)
  1165. if not candidates:
  1166. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  1167. return False
  1168. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  1169. if selected is None:
  1170. # Naming the plugs matters here: with several linked to one printer
  1171. # this is the difference between "the meter is offline" and "you
  1172. # linked only accessories" (#2859).
  1173. _logger.warning(
  1174. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  1175. printer_id,
  1176. archive.id,
  1177. ", ".join(plug.name for plug in candidates),
  1178. )
  1179. return False
  1180. plug, energy = selected
  1181. archive.energy_start_kwh = float(energy["total"])
  1182. # With the plug's snapshots, what lets the cost follow the price over
  1183. # the print rather than take the price at its end (#1251). A price that
  1184. # can't be had must not cost the print its energy reading.
  1185. archive.energy_start_at = utcnow_naive()
  1186. archive.energy_start_plug_id = plug.id
  1187. try:
  1188. from backend.app.services.energy_price import current_price
  1189. archive.energy_start_price = await current_price(db)
  1190. except Exception as e:
  1191. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  1192. archive.energy_start_price = None
  1193. try:
  1194. from backend.app.services.print_log import mirror_energy_start
  1195. await mirror_energy_start(db, archive, printer_id=printer_id)
  1196. except Exception as e:
  1197. _logger.warning("[RUN] Energy start not copied onto the run of archive %s: %s", archive.id, e)
  1198. await db.commit()
  1199. _logger.info(
  1200. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  1201. f" ({context})" if context else "",
  1202. archive.id,
  1203. plug.name,
  1204. energy["total"],
  1205. )
  1206. return True
  1207. except Exception as e:
  1208. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  1209. return False
  1210. def forget_print_creator(user_id: int) -> None:
  1211. """The print-start emails of a deleted user's jobs go to nobody, not to
  1212. whoever is given the id next (SQLite reuses it)."""
  1213. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  1214. del _expected_print_creators[key]
  1215. async def forget_printer(printer_id: int) -> None:
  1216. """Drop what is kept for a deleted printer's id, here and in the services.
  1217. SQLite used to give the id to the next printer created, which inherited it
  1218. all: the running print's owner (its prints passed the kill switch and were
  1219. billed to that user), the plate-clear gate, pending and suppressed
  1220. notifications, the camera feed, the plate references. Ids are no longer
  1221. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  1222. stay. Called after the delete is committed, and again by work that was in
  1223. flight and wrote state back.
  1224. Every printer-keyed map of this module is listed here or, with the reason,
  1225. in tests/unit/test_forget_printer.py.
  1226. """
  1227. from backend.app.api.routes import camera
  1228. from backend.app.services import (
  1229. bambu_ftp,
  1230. kprofile_drift,
  1231. layer_timelapse,
  1232. plate_detection,
  1233. print_dispatch_context,
  1234. usage_tracker,
  1235. )
  1236. from backend.app.services.notify_live_activities import notify_live_activities
  1237. from backend.app.services.obico_detection import obico_detection_service
  1238. from backend.app.services.printer_file_cache import printer_file_cache
  1239. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  1240. archive_ids = set()
  1241. for tracked in (_active_prints, _expected_prints):
  1242. for key in [key for key in tracked if key[0] == printer_id]:
  1243. archive_ids.add(tracked.pop(key))
  1244. for archive_id in archive_ids:
  1245. _owned_print_archive_ids.discard(archive_id)
  1246. for registered in (_print_ams_mappings, _print_cost_center_ids, _print_plate_ids):
  1247. for key in [key for key in registered if key[0] == printer_id]:
  1248. del registered[key]
  1249. for tracked in (_expected_print_creators, _expected_print_registered_at):
  1250. for key in [key for key in tracked if key[0] == printer_id]:
  1251. del tracked[key]
  1252. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  1253. _ams_index_only_logged.discard(key)
  1254. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  1255. del _ams_alarm_cooldown[key]
  1256. # Pending work that would act on the id: an offline notice, a 3MF retry.
  1257. # A kill-switch notice is about a stop that happened and is left to finish.
  1258. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  1259. task = tasks.pop(printer_id, None)
  1260. if task is not None:
  1261. task.cancel()
  1262. for keyed in (
  1263. _stage22_finish_frames,
  1264. _stage22_finish_in_flight,
  1265. _inprint_frame_bank,
  1266. _inprint_frame_bank_ts,
  1267. _printer_reconciled_since_connect,
  1268. _printer_kprofiles_primed_since_connect,
  1269. _last_progress_milestone,
  1270. _first_layer_notified,
  1271. _kill_switch_notification_tasks,
  1272. _notified_hms_errors,
  1273. _hms_print_state,
  1274. _hms_forget_when_gone,
  1275. _timelapse_baselines,
  1276. _bed_cool_waiters,
  1277. _printer_last_connected,
  1278. _unknown_tag_last_broadcast,
  1279. _last_status_broadcast,
  1280. _connection_watchdog_last_attempt,
  1281. ):
  1282. keyed.pop(printer_id, None)
  1283. for marked in (
  1284. _unauthorized_print_kill_sent,
  1285. _user_stopped_printers,
  1286. _kill_switch_stopped,
  1287. _printer_offline_published,
  1288. _nozzle_count_updated,
  1289. _runtime_seen_connected,
  1290. _timelapse_baselines_unread,
  1291. ):
  1292. marked.discard(printer_id)
  1293. printer_manager.forget_printer(printer_id)
  1294. printer_file_cache.forget_printer(printer_id)
  1295. print_dispatch_context.clear(printer_id)
  1296. kprofile_drift.forget_printer(printer_id, deleted=True)
  1297. layer_timelapse.cancel_session(printer_id)
  1298. usage_tracker.forget_printer(printer_id)
  1299. obico_detection_service.forget_printer(printer_id)
  1300. bambu_ftp.clear_3mf_cache(printer_id)
  1301. await camera.forget_printer(printer_id)
  1302. printers.clear_cover_cache(printer_id)
  1303. print_scheduler.forget_printer(printer_id)
  1304. notify_live_activities.forget_printer(printer_id)
  1305. plate_detection.remove_printer_references(printer_id)
  1306. def register_expected_print(
  1307. printer_id: int,
  1308. filename: str,
  1309. archive_id: int,
  1310. ams_mapping: list[int] | None = None,
  1311. created_by_id: int | None = None,
  1312. cost_center_id: int | None = None,
  1313. plate_id: int | None = None,
  1314. ):
  1315. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1316. # Store with multiple filename variations to catch different naming patterns
  1317. _expected_prints[(printer_id, filename)] = archive_id
  1318. # Also store without .3mf extension if present
  1319. if filename.endswith(".3mf"):
  1320. base = filename[:-4]
  1321. _expected_prints[(printer_id, base)] = archive_id
  1322. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1323. # Store AMS mapping for usage tracking at print completion, and plate_id for
  1324. # a single-plate dispatch from a multi-plate 3MF — without it, the direct-Print
  1325. # path attributes the whole file's filament total to the spool instead of just
  1326. # the printed plate (#1697). They describe this dispatch: one that has none
  1327. # drops what an earlier dispatch of the archive left (sent, never started),
  1328. # unless a plate of the archive is printing now and still needs them.
  1329. dispatch = (printer_id, archive_id)
  1330. archive_printing = _printing_here(printer_id, archive_id)
  1331. if ams_mapping is not None:
  1332. _print_ams_mappings[dispatch] = ams_mapping
  1333. elif not archive_printing:
  1334. _print_ams_mappings.pop(dispatch, None)
  1335. if cost_center_id is not None:
  1336. _print_cost_center_ids[dispatch] = cost_center_id
  1337. elif not archive_printing:
  1338. _print_cost_center_ids.pop(dispatch, None)
  1339. if plate_id is not None:
  1340. _print_plate_ids[dispatch] = plate_id
  1341. elif not archive_printing:
  1342. _print_plate_ids.pop(dispatch, None)
  1343. # Store created_by_id so the user start email can be sent even when the archive
  1344. # itself has no created_by_id (e.g. library-file-based queue prints)
  1345. if created_by_id is not None:
  1346. _expected_print_creators[(printer_id, filename)] = created_by_id
  1347. if filename.endswith(".3mf"):
  1348. base = filename[:-4]
  1349. _expected_print_creators[(printer_id, base)] = created_by_id
  1350. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1351. # Record registration time for TTL-based eviction
  1352. _registered_at = time.monotonic()
  1353. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1354. if filename.endswith(".3mf"):
  1355. base = filename[:-4]
  1356. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1357. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1358. logging.getLogger(__name__).info(
  1359. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1360. )
  1361. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1362. """Undo :func:`register_expected_print` when the print never went out.
  1363. Registration has to happen *before* the MQTT print command, because the
  1364. printer can report the print before the line after the send executes. So
  1365. every path that registers and then fails to send — a cancel winning the
  1366. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1367. between — leaves an expectation for a print that will never arrive.
  1368. The TTL sweep evicts those after two hours, which is far longer than it
  1369. takes a user to react to a failed dispatch by pressing print again: that
  1370. reprint would be folded into the *old* archive and take the stale
  1371. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1372. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1373. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1374. are keyed by printer and archive, not by file, so they may only be dropped
  1375. once no live key of the printer still points at that archive.
  1376. """
  1377. keys = [(printer_id, filename)]
  1378. if filename.endswith(".3mf"):
  1379. base = filename[:-4]
  1380. keys.append((printer_id, base))
  1381. keys.append((printer_id, f"{base}.gcode"))
  1382. removed = False
  1383. for key in keys:
  1384. if _expected_prints.pop(key, None) is not None:
  1385. removed = True
  1386. _expected_print_creators.pop(key, None)
  1387. _expected_print_registered_at.pop(key, None)
  1388. # Still needed by another expected print of the archive on the printer,
  1389. # or a plate of it printing there, as in the sweep.
  1390. if not _expected_or_printing_here(printer_id, archive_id):
  1391. _drop_dispatch(printer_id, archive_id)
  1392. if removed:
  1393. logging.getLogger(__name__).info(
  1394. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1395. printer_id,
  1396. filename,
  1397. archive_id,
  1398. )
  1399. def _compute_run_filament_grams(
  1400. status: str,
  1401. archive_filament_used_grams: float | None,
  1402. progress: float | int | None,
  1403. usage_results: list[dict] | None,
  1404. ) -> float | None:
  1405. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1406. Priority for every status:
  1407. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1408. weight delta — same source that drives "Total Consumed" on the
  1409. Inventory page, so Stats and Inventory totals stay aligned).
  1410. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1411. back to the canonical "this print used X" value).
  1412. 3. For partial statuses: ``estimate * progress%``.
  1413. 4. ``None`` if nothing is known.
  1414. """
  1415. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1416. if tracked_grams > 0:
  1417. return round(tracked_grams, 1)
  1418. if status == "completed":
  1419. return archive_filament_used_grams
  1420. if archive_filament_used_grams:
  1421. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1422. if scale > 0:
  1423. return round(archive_filament_used_grams * scale, 1)
  1424. return None
  1425. def _printing_here(printer_id: int, archive_id: int) -> bool:
  1426. """Whether a plate of the archive is printing on the printer."""
  1427. return any(key[0] == printer_id and bound == archive_id for key, bound in _active_prints.items())
  1428. def _expected_or_printing_here(printer_id: int, archive_id: int) -> bool:
  1429. """Whether a print of the archive is expected or printing on the printer."""
  1430. return _printing_here(printer_id, archive_id) or any(
  1431. key[0] == printer_id and expected == archive_id for key, expected in _expected_prints.items()
  1432. )
  1433. def _drop_dispatch(printer_id: int, archive_id: int) -> None:
  1434. """Forget what the dispatch of the archive to the printer registered."""
  1435. dispatch = (printer_id, archive_id)
  1436. _print_ams_mappings.pop(dispatch, None)
  1437. _print_cost_center_ids.pop(dispatch, None)
  1438. _print_plate_ids.pop(dispatch, None)
  1439. def _get_start_ams_mapping(data: dict, printer_id: int, archive_id: int | None) -> list[int] | None:
  1440. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1441. stored_ams_mapping = data.get("ams_mapping")
  1442. if not stored_ams_mapping and archive_id:
  1443. stored_ams_mapping = _print_ams_mappings.get((printer_id, archive_id))
  1444. return stored_ams_mapping
  1445. def _get_start_plate_id(printer_id: int, archive_id: int | None) -> int | None:
  1446. """Resolve plate_id for print start without consuming stored direct-Print state.
  1447. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1448. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1449. read it back at print-start without popping (the entry is popped on print
  1450. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1451. """
  1452. if archive_id is None:
  1453. return None
  1454. return _print_plate_ids.get((printer_id, archive_id))
  1455. def _run_print_time_seconds(archive, printer_id: int) -> int | None:
  1456. """The slicer's time for the plate this print prints, for its start
  1457. notification (#3375): ``archive.print_time_seconds`` adds every plate of
  1458. the file up (#1593). The plate is the dispatch's, else the archive's. The
  1459. whole file's time when its plates are not known; None for a plate not
  1460. known of several, and the notification takes the printer's remaining
  1461. time."""
  1462. from backend.app.services.print_cost_estimate import run_estimate
  1463. plate_id = _print_plate_ids.get((printer_id, archive.id), archive.plate_id)
  1464. estimate = run_estimate(archive, plate_id)
  1465. return estimate.seconds if estimate is not None else None
  1466. _plate_estimates_task: asyncio.Task | None = None
  1467. async def _fill_plate_estimates() -> None:
  1468. from backend.app.services.print_cost_estimate import fill_plate_estimates
  1469. try:
  1470. filled = await fill_plate_estimates(async_session)
  1471. except asyncio.CancelledError:
  1472. raise
  1473. except Exception as exc:
  1474. logging.getLogger(__name__).warning("[ARCHIVE] Reading plate estimates failed: %s", exc)
  1475. return
  1476. if filled:
  1477. logging.getLogger(__name__).info("[ARCHIVE] Read the plate estimates of %d archive(s)", filled)
  1478. def _partial_progress_scale(progress: int | float | None) -> float:
  1479. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1480. Used by every site that multiplies a "would-have-used" slicer estimate
  1481. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1482. so the three sites in ``_background_notifications`` (and the per-plate
  1483. override helper) can't drift apart on the coercion shape.
  1484. """
  1485. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1486. def _scope_notification_archive_data_to_plate(
  1487. archive_data: dict,
  1488. archive_file_path: str | None,
  1489. plate_id: int | None,
  1490. print_status: str,
  1491. progress: int | float | None,
  1492. base_dir: Path,
  1493. ) -> dict:
  1494. """Override summed-across-plates totals in ``archive_data`` with the values
  1495. for ``plate_id`` so the completion notification reports what was actually
  1496. printed, not the whole project (#1785).
  1497. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1498. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1499. the archive card's "whole project" headline, wrong for the completion
  1500. notification of a single-plate print. The queue UI already re-reads the
  1501. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1502. notification payload (filament grams, time estimate, per-slot breakdown).
  1503. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1504. no per-plate values — in every fail case the original ``archive_data`` is
  1505. returned unchanged so the notification still sends.
  1506. """
  1507. if plate_id is None or not archive_file_path:
  1508. return archive_data
  1509. from backend.app.utils.threemf_tools import (
  1510. extract_filament_usage_from_3mf,
  1511. extract_print_time_from_3mf,
  1512. )
  1513. archive_path = base_dir / archive_file_path
  1514. if not archive_path.exists():
  1515. return archive_data
  1516. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1517. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1518. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1519. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1520. if plate_time:
  1521. archive_data["print_time_seconds"] = plate_time
  1522. # Gate both the grams headline AND the per-slot breakdown on the same
  1523. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1524. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1525. # to the project-level grams the archive columns already provide rather
  1526. # than ship a project-level headline next to an all-zero per-plate
  1527. # breakdown.
  1528. if plate_grams > 0:
  1529. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1530. archive_data["filament_slots"] = [
  1531. {
  1532. "slot_id": s.get("slot_id"),
  1533. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1534. "type": s.get("type", ""),
  1535. "color": s.get("color", ""),
  1536. }
  1537. for s in plate_slots
  1538. ]
  1539. return archive_data
  1540. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1541. """Best-effort filament metadata from the MQTT print-start snapshot.
  1542. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1543. file during print, see #1533) so the fallback PrintArchive still has
  1544. enough filament info to support the inventory views and AMS-expansion
  1545. planning the operator opens it for. Returns a dict with optional
  1546. ``filament_type`` and ``filament_color`` keys in the same
  1547. comma-separated format the 3MF extractor produces, so the rest of the
  1548. codebase treats the fallback archive identically to a normal one.
  1549. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1550. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1551. entries). When supplied, only the slots actually consumed by this
  1552. print contribute. Without it the function falls back to every loaded
  1553. AMS slot — less accurate but still useful.
  1554. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1555. that the unit tests pass directly, AND the on_print_start callback
  1556. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1557. bambu_mqtt service hands to main.py at runtime. The original
  1558. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1559. handled the inner shape and silently returned ``{}`` for every real
  1560. print start, leaving fallback archives' filament fields NULL — the
  1561. exact regression the fix was meant to close. Reported with a log
  1562. proving the AMS state was right there at
  1563. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1564. """
  1565. result: dict[str, str] = {}
  1566. # Look at the on_print_start wrapper first, then the inner shape.
  1567. raw_data = (data or {}).get("raw_data")
  1568. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1569. if not isinstance(ams_root, dict):
  1570. ams_root = (data or {}).get("ams") or {}
  1571. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1572. if not isinstance(ams_units, list) or not ams_units:
  1573. return result
  1574. from backend.app.services.print_scheduler import _global_tray_id
  1575. # Map global tray id → (type, color), addressed as the print's ams_mapping
  1576. # is: unit * 4 + tray, or the bare unit id for an AMS-HT (from 128).
  1577. loaded: dict[int, tuple[str, str]] = {}
  1578. for unit in ams_units:
  1579. if not isinstance(unit, dict):
  1580. continue
  1581. try:
  1582. unit_id = int(unit.get("id", 0))
  1583. except (TypeError, ValueError):
  1584. continue
  1585. for tray in unit.get("tray") or []:
  1586. if not isinstance(tray, dict):
  1587. continue
  1588. try:
  1589. tray_id = int(tray.get("id", 0))
  1590. except (TypeError, ValueError):
  1591. continue
  1592. ttype = (tray.get("tray_type") or "").strip()
  1593. # RRGGBBAA from the printer, stored as the 3MF path stores it:
  1594. # "#RRGGBB" (the Archives page's swatches and colour filter).
  1595. hex_color = (tray.get("tray_color") or "").strip().upper()[:6]
  1596. tcolor = f"#{hex_color}" if re.fullmatch(r"[0-9A-F]{6}", hex_color) else ""
  1597. if not ttype:
  1598. continue # Empty / unloaded slot.
  1599. loaded[_global_tray_id(unit_id, tray_id)] = (ttype, tcolor)
  1600. if not loaded:
  1601. return result
  1602. if ams_mapping:
  1603. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1604. filaments = [loaded[g] for g in used_ids if g in loaded]
  1605. if not filaments:
  1606. return result # Mapping points entirely at slots we have no data for.
  1607. else:
  1608. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1609. types_joined = ",".join(f[0] for f in filaments)
  1610. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1611. # Column limits per backend/app/models/archive.py: filament_type=50,
  1612. # filament_color=200.
  1613. if types_joined:
  1614. result["filament_type"] = types_joined[:50]
  1615. if colors_joined:
  1616. result["filament_color"] = colors_joined[:200]
  1617. return result
  1618. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1619. """Start a layer-timelapse session for *archive_id* when the printer has
  1620. an external camera configured. Returns True if a session was started.
  1621. Three call sites in on_print_start (expected-archive promotion, fallback
  1622. archive creation, fresh-archive creation) used to inline this same
  1623. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1624. on the first pass). Centralising the conditional + call here makes the
  1625. contract testable in isolation and keeps the three sites locked in step.
  1626. """
  1627. if not (printer.external_camera_enabled and printer.external_camera_url):
  1628. return False
  1629. from backend.app.services.layer_timelapse import start_session
  1630. start_session(
  1631. printer_id,
  1632. archive_id,
  1633. printer.external_camera_url,
  1634. printer.external_camera_type or "mjpeg",
  1635. snapshot_url=printer.external_camera_snapshot_url,
  1636. rotation=getattr(printer, "camera_rotation", 0),
  1637. )
  1638. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1639. return True
  1640. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1641. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1642. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1643. — since #2926 — the description the parser already resolved, which is preferred
  1644. when present so the queue's failure reason reads the same as the status
  1645. response. The short code still produces the bracketed label, and still
  1646. resolves the sentence for a caller whose entries predate the field. An entry
  1647. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1648. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1649. label when no description is on file. Returns None for an empty list so
  1650. callers can leave error_message unset.
  1651. """
  1652. if not hms_errors:
  1653. return None
  1654. from backend.app.services.hms_errors import get_error_description
  1655. parts: list[str] = []
  1656. for err in hms_errors:
  1657. try:
  1658. # `_hms_short_code` rather than a local derivation: this one used to
  1659. # format the error without masking it to 16 bits, so an `hms[]` entry
  1660. # whose code carries an alert-level group produced a five-digit label
  1661. # like "0500_3000A" — not a code the user can look up, and never a
  1662. # catalogue key, so the sentence was lost with it.
  1663. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1664. except (TypeError, ValueError):
  1665. continue
  1666. description = err.get("description") or get_error_description(short_code)
  1667. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1668. # groups and is not a code anyone can look up; its full code in the
  1669. # printer screen's four groups is (#2728).
  1670. full_code = str(err.get("full_code") or "")
  1671. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1672. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1673. return "; ".join(parts) if parts else None
  1674. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1675. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1676. print completes successfully. Gated to status=='completed': failed, cancelled
  1677. and aborted prints do not count as usage. Caller is responsible for committing
  1678. the session. No-op when the queue item has no linked library file (e.g. reprints
  1679. from an archive). See #1008."""
  1680. if queue_status != "completed" or item.library_file_id is None:
  1681. return
  1682. from backend.app.models.library import LibraryFile
  1683. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1684. if lib_file is None:
  1685. return
  1686. lib_file.print_count = (lib_file.print_count or 0) + 1
  1687. lib_file.last_printed_at = datetime.now(timezone.utc)
  1688. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1689. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1690. When on_print_complete fires with status 'failed' for a printer in this set we
  1691. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1692. rather than a 'print failed' notification.
  1693. """
  1694. _user_stopped_printers.add(printer_id)
  1695. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1696. _last_status_broadcast: dict[int, str] = {}
  1697. # Track printers where we've updated nozzle_count
  1698. _nozzle_count_updated: set[int] = set()
  1699. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1700. """Wait the debounce window then fire `on_printer_offline` if the printer
  1701. is still offline.
  1702. Scheduled by `on_printer_status_change` on the connected → disconnected
  1703. edge (#1752). Cancelled by the same handler if the printer reconnects
  1704. before the window elapses, so a single MQTT blip + recovery doesn't
  1705. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1706. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1707. route through the same status-change callback, so this covers both.
  1708. """
  1709. logger = logging.getLogger(__name__)
  1710. try:
  1711. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1712. still_offline = not printer_manager.is_connected(printer_id)
  1713. logger.info(
  1714. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1715. printer_id,
  1716. still_offline,
  1717. )
  1718. if not still_offline:
  1719. return
  1720. async with async_session() as db:
  1721. from backend.app.models.printer import Printer
  1722. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1723. printer = result.scalar_one_or_none()
  1724. if not printer:
  1725. logger.warning(
  1726. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1727. printer_id,
  1728. )
  1729. return
  1730. # Recorded only when the relay can publish it, so the reconnect's
  1731. # online event always has an offline before it.
  1732. if mqtt_relay.enabled and mqtt_relay.connected:
  1733. _printer_offline_published.add(printer_id)
  1734. try:
  1735. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1736. except Exception as e:
  1737. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1738. logger.info(
  1739. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1740. printer_id,
  1741. printer.name,
  1742. )
  1743. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1744. except asyncio.CancelledError:
  1745. raise
  1746. except Exception as e:
  1747. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1748. finally:
  1749. _printer_offline_notify_tasks.pop(printer_id, None)
  1750. def _hms_notify_key(error) -> str:
  1751. """What identifies a fault for notification de-duplication.
  1752. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1753. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1754. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1755. and -0006 together) shared a key and only the first was ever notified. An
  1756. entry without a full code falls back to attr and code together.
  1757. """
  1758. full_code = getattr(error, "full_code", "") or ""
  1759. if full_code:
  1760. return full_code.upper()
  1761. return f"{error.attr:08X}:{error.code}"
  1762. def _hms_fault_counts(error) -> bool:
  1763. """Whether a fault counts as a problem: the same rule the frontend's
  1764. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1765. It counts when Bambu publishes text for it or it offers action buttons, and
  1766. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1767. no actions does not count: those are things like "the top cover is open" or
  1768. "the chamber is hot, fan speed increased", which a printer can hold through
  1769. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1770. it always has; those are prompts such as "unable to start drying" (#2728).
  1771. """
  1772. if error.severity < 1:
  1773. return False
  1774. has_actions = bool(getattr(error, "actions", None))
  1775. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1776. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1777. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1778. """The new faults that count (see ``_hms_fault_counts``).
  1779. These go to the MQTT relay; the caller also needs a description before it
  1780. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1781. used to read ``severity >= 2`` when severity held the part byte; on the real
  1782. level that would drop the task-stopping errors (#2728).
  1783. """
  1784. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1785. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1786. """The faults on this printer not notified yet, and record them as notified.
  1787. Tracking is updated before anything is sent, so concurrent status callbacks
  1788. cannot notify the same fault twice. A notified fault is forgotten once it
  1789. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1790. and on is notified once (#3226), while one that clears and comes back much
  1791. later is notified again.
  1792. When ``print_state`` changes (a print resumed, started or finished), every
  1793. fault recorded so far is forgotten the first time it is gone, without the
  1794. wait: a runout fixed before resuming must be notified if it happens again a
  1795. few minutes later, while the printer sits paused. Not only the faults gone
  1796. at the change itself, because the update that flips the state can still
  1797. carry the old fault (a ``print_error`` entry stays until a payload brings
  1798. ``hms``).
  1799. """
  1800. now = time.time()
  1801. current = {_hms_notify_key(e) for e in errors}
  1802. seen = _notified_hms_errors.setdefault(printer_id, {})
  1803. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1804. if print_state is not None:
  1805. print_state = print_state.upper()
  1806. if _hms_print_state.get(printer_id, print_state) != print_state:
  1807. forget_when_gone.update(seen)
  1808. _hms_print_state[printer_id] = print_state
  1809. for key, last_seen in list(seen.items()):
  1810. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1811. del seen[key]
  1812. forget_when_gone.discard(key)
  1813. new = current - seen.keys()
  1814. for key in current:
  1815. seen[key] = now
  1816. if not seen:
  1817. _notified_hms_errors.pop(printer_id, None)
  1818. if not forget_when_gone:
  1819. _hms_forget_when_gone.pop(printer_id, None)
  1820. return _hms_errors_to_notify(errors, new)
  1821. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1822. # "Printing", -1 and 255 are "no stage" (#3211).
  1823. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1824. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1825. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1826. Records it as notified. Called only for a printing state with progress above 0.
  1827. Progress before the first layer is not progress through the print (#3211).
  1828. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1829. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1830. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1831. 75% notification together with Print Started, and since 75 was then on
  1832. record, 25 and 50 could never fire. So nothing counts while the printer
  1833. reports a layer count but has not started layer 1.
  1834. Without a layer count -- a print whose first frame carried no
  1835. ``total_layer_num``, until the pushall that asks for it is answered
  1836. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1837. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1838. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1839. reports neither keeps the old behaviour rather than never notifying.
  1840. """
  1841. if (state.layer_num or 0) < 1:
  1842. if (state.total_layers or 0) > 0:
  1843. return None
  1844. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1845. return None
  1846. progress = state.progress or 0
  1847. current_milestone = 0
  1848. if progress >= 75:
  1849. current_milestone = 75
  1850. elif progress >= 50:
  1851. current_milestone = 50
  1852. elif progress >= 25:
  1853. current_milestone = 25
  1854. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1855. _last_progress_milestone[printer_id] = current_milestone
  1856. return current_milestone
  1857. return None
  1858. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1859. """Handle printer status changes - broadcast via WebSocket."""
  1860. try:
  1861. notify_live_activities.observe(printer_id, state)
  1862. except Exception:
  1863. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1864. try:
  1865. pause_eta.observe(printer_id, state)
  1866. except Exception:
  1867. logging.getLogger(__name__).exception("Pause heads-up check failed for printer %s", printer_id)
  1868. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1869. # transitions disconnected → connected — which covers both Bambuddy
  1870. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1871. # `reconcile_stale_active_prints` exactly once for this connection so
  1872. # any archive still in `status="printing"` that can't actually be
  1873. # running anymore (printer IDLE / different subtask / empty subtask)
  1874. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1875. # finished during a disconnect window + a smart-plug power cycle
  1876. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1877. # next boot. Reconciliation runs concurrently — it must not block the
  1878. # WebSocket dedup / broadcast logic below, and the connected edge is
  1879. # marked True BEFORE the await so concurrent status updates inside
  1880. # the same connection don't re-trigger reconciliation.
  1881. #
  1882. # Wait for a real push_status before reconciling (#1679): MQTT
  1883. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1884. # the connection, BEFORE `_request_push_all` round-trips. At that
  1885. # instant the `PrinterState` is still on construction defaults — most
  1886. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1887. # If reconcile spawns here, every in-flight archive falls through to
  1888. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1889. # creates a duplicate archive on the real PRINT COMPLETE and
  1890. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1891. # keeps the #1542 mechanism intact: once the first real push_status
  1892. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1893. # fires again with the flag still False — reconcile then runs against
  1894. # actual evidence.
  1895. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1896. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1897. _printer_reconciled_since_connect[printer_id] = True
  1898. spawn_background_task(
  1899. reconcile_stale_active_prints(printer_id),
  1900. name=f"reconcile-stale-prints-{printer_id}",
  1901. )
  1902. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1903. # Re-arm so the next reconnect triggers reconciliation again.
  1904. _printer_reconciled_since_connect[printer_id] = False
  1905. # Same edge, for the calibration table the AMS card reads its K values from.
  1906. #
  1907. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1908. # tables to ask for. A `state_known` gate alone is not enough: the first
  1909. # real push_status is what makes the state known, and the nozzle fields do
  1910. # not always arrive in it. Latching there would spend this connection's one
  1911. # attempt on a printer that could not yet say what was fitted.
  1912. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1913. if (
  1914. state.connected
  1915. and state_known
  1916. and nozzle_known
  1917. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1918. ):
  1919. _printer_kprofiles_primed_since_connect[printer_id] = True
  1920. spawn_background_task(
  1921. prime_kprofile_table(printer_id),
  1922. name=f"prime-kprofiles-{printer_id}",
  1923. )
  1924. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1925. _printer_kprofiles_primed_since_connect[printer_id] = False
  1926. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1927. # else in the AMS report changing -- a power cycle does it to every slot --
  1928. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1929. # while the printer is idle; needs_check is cheap and throttled per slot.
  1930. # Guarded: nothing here may stop the status broadcast below.
  1931. try:
  1932. if not state.connected:
  1933. kprofile_drift.forget_printer(printer_id)
  1934. elif kprofile_drift.needs_check(printer_id, state):
  1935. spawn_background_task(
  1936. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1937. name=f"reapply-kprofiles-{printer_id}",
  1938. )
  1939. except Exception:
  1940. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1941. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1942. # connected → disconnected. The "back online" channel is already covered
  1943. # by the print-failure notification (firmware reports gcode_state=FAILED
  1944. # on reconnect of an interrupted print), so there is no online
  1945. # notification. The MQTT relay gets both: offline after the debounce, and
  1946. # online on the reconnect that follows a published offline.
  1947. prev_connected = _printer_last_connected.get(printer_id)
  1948. _printer_last_connected[printer_id] = state.connected
  1949. if prev_connected is True and not state.connected:
  1950. existing = _printer_offline_notify_tasks.get(printer_id)
  1951. if existing is None or existing.done():
  1952. logging.getLogger(__name__).info(
  1953. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1954. printer_id,
  1955. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1956. )
  1957. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1958. _maybe_notify_printer_offline(printer_id),
  1959. name=f"printer-offline-notify-{printer_id}",
  1960. )
  1961. elif state.connected:
  1962. # Kept until the relay can actually send online: with its broker down
  1963. # now, the next status update after the reconnect sends it.
  1964. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1965. _printer_offline_published.discard(printer_id)
  1966. printer_info = printer_manager.get_printer(printer_id)
  1967. if printer_info:
  1968. try:
  1969. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1970. except Exception as e:
  1971. logging.getLogger(__name__).warning(
  1972. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1973. )
  1974. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1975. if pending is not None and not pending.done():
  1976. logging.getLogger(__name__).info(
  1977. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1978. printer_id,
  1979. )
  1980. pending.cancel()
  1981. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1982. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1983. temps = state.temperatures or {}
  1984. nozzle_temp = round(temps.get("nozzle", 0))
  1985. bed_temp = round(temps.get("bed", 0))
  1986. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1987. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1988. # Auto-detect dual-nozzle printers from MQTT temperature data
  1989. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1990. _nozzle_count_updated.add(printer_id)
  1991. # Update nozzle_count in database
  1992. async with async_session() as db:
  1993. from backend.app.models.printer import Printer
  1994. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1995. printer = result.scalar_one_or_none()
  1996. if printer and printer.nozzle_count != 2:
  1997. printer.nozzle_count = 2
  1998. await db.commit()
  1999. logging.getLogger(__name__).info(
  2000. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  2001. )
  2002. # Include target temps for heating phase detection
  2003. bed_target = round(temps.get("bed_target", 0))
  2004. nozzle_target = round(temps.get("nozzle_target", 0))
  2005. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  2006. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  2007. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  2008. #
  2009. # dry_countdown_stalled rides along because it is the one drying signal the
  2010. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  2011. # dry_time stopped moving, so on the frame that flips it every other member
  2012. # of this key is identical and the push would be deduplicated away. Mid-print
  2013. # a temperature would eventually break the tie, but a parked command on an
  2014. # idle machine changes nothing else at all — AMS temp and humidity are not in
  2015. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  2016. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  2017. ams_dry_key = (
  2018. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  2019. if state.raw_data
  2020. else ()
  2021. )
  2022. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  2023. #
  2024. # The filament identity fields are here because Configure Slot writes
  2025. # exactly those and nothing else. Re-configuring a slot from PLA to another
  2026. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  2027. # matched, this function returned before broadcasting, and the card kept
  2028. # showing the old filament until the 30s fallback poll or a page reload —
  2029. # even though the configure route asks the printer for a fresh pushall and
  2030. # that push does carry the new values. Reset always worked, because it
  2031. # clears tray_type.
  2032. #
  2033. # These fields only change when someone configures a slot or swaps a spool,
  2034. # so unlike temperature or progress they add no broadcast traffic mid-print.
  2035. ams_tray_key = (
  2036. tuple(
  2037. (
  2038. t.get("id"),
  2039. t.get("tray_type", ""),
  2040. t.get("state"),
  2041. t.get("tray_color", ""),
  2042. t.get("tray_info_idx", ""),
  2043. t.get("tray_sub_brands", ""),
  2044. t.get("cali_idx"),
  2045. )
  2046. for a in (state.raw_data.get("ams") or [])
  2047. for t in a.get("tray", [])
  2048. )
  2049. if state.raw_data
  2050. else ()
  2051. )
  2052. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  2053. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  2054. # in the AMS change-hash (tray fields only, and widening that would fire
  2055. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  2056. # screen changed no key at all and the card's inlet badges sat stale until a
  2057. # reload. Like the filament-backup flag, these only move when someone
  2058. # reconfigures the machine, so they add no mid-print broadcast traffic.
  2059. fts_key = (
  2060. state.fila_switch.installed if state.fila_switch else False,
  2061. tuple(sorted(state.ams_switch_inlet.items())),
  2062. # Which hotend holds which slot. Unlike the two above this does move
  2063. # mid-print, on every filament change — but only between discrete slots,
  2064. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  2065. # it live: it decides which hotend the Load dialog may offer and whether
  2066. # Unload has anything to act on.
  2067. tuple(
  2068. sorted(
  2069. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  2070. # Sort on the extruder id alone: the other members are nullable
  2071. # and comparing None with an int raises.
  2072. key=lambda entry: entry[0],
  2073. )
  2074. ),
  2075. )
  2076. status_key = (
  2077. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  2078. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  2079. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  2080. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  2081. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  2082. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  2083. )
  2084. # Fields that change only when the machine does (a nozzle swap, a firmware
  2085. # update, developer mode) or once per print (its AMS mapping): no traffic,
  2086. # but on an idle printer nothing else moves the key when they change.
  2087. machine_key = (
  2088. tuple((n.nozzle_type, n.nozzle_diameter) for n in (state.nozzles or [])),
  2089. state.firmware_version,
  2090. state.developer_mode,
  2091. tuple(state.print_ams_mapping) if isinstance(state.print_ams_mapping, list) else None,
  2092. # Cooling/heating, switched on the printer's screen too: on an idle
  2093. # printer nothing else moves the key (PSF-4).
  2094. state.airduct_mode,
  2095. )
  2096. status_key = f"{status_key}:{machine_key}"
  2097. is_active_print = state.state in _ACTIVE_PRINT_STATES
  2098. if not is_active_print:
  2099. _unauthorized_print_kill_sent.discard(printer_id)
  2100. elif printer_id in _unauthorized_print_kill_sent:
  2101. # stop_print() was already sent for this print; avoid all further
  2102. # ownership and settings work until the printer leaves an active state.
  2103. pass
  2104. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  2105. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  2106. _unauthorized_print_kill_sent.discard(printer_id)
  2107. else:
  2108. kill_switch_enabled = False
  2109. authorization: bool | None = None
  2110. status_logger = logging.getLogger(__name__)
  2111. try:
  2112. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  2113. if kill_switch_enabled:
  2114. async with async_session() as db:
  2115. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  2116. except Exception as e:
  2117. # Fail safe: a database/reconciliation error must never turn into an
  2118. # irreversible stop of a print whose ownership is still unknown.
  2119. authorization = None
  2120. status_logger.warning(
  2121. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  2122. )
  2123. if not kill_switch_enabled or authorization is True:
  2124. _unauthorized_print_kill_sent.discard(printer_id)
  2125. elif authorization is None:
  2126. _unauthorized_print_kill_sent.discard(printer_id)
  2127. status_logger.debug(
  2128. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  2129. printer_id,
  2130. )
  2131. else:
  2132. try:
  2133. stopped = printer_manager.stop_print(printer_id)
  2134. if stopped:
  2135. _unauthorized_print_kill_sent.add(printer_id)
  2136. _kill_switch_stopped.add(printer_id)
  2137. printer_info = printer_manager.get_printer(printer_id)
  2138. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  2139. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  2140. notification_data = {
  2141. "status": "stopped",
  2142. "filename": state.gcode_file or state.current_print or "",
  2143. "subtask_name": state.subtask_name or "",
  2144. "progress": state.progress,
  2145. "reason": "unauthorized_print",
  2146. }
  2147. status_logger.warning(
  2148. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  2149. printer_id,
  2150. state.state,
  2151. )
  2152. try:
  2153. await ws_manager.broadcast(
  2154. {
  2155. "type": "kill_switch_triggered",
  2156. "printer_id": printer_id,
  2157. "printer_name": printer_name,
  2158. "filename": filename,
  2159. "reason": "unauthorized_print",
  2160. }
  2161. )
  2162. except Exception as e:
  2163. status_logger.warning(
  2164. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  2165. )
  2166. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  2167. if previous_task is not None and not previous_task.done():
  2168. previous_task.cancel()
  2169. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  2170. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  2171. name=f"kill-switch-notification-{printer_id}",
  2172. )
  2173. else:
  2174. status_logger.warning(
  2175. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  2176. printer_id,
  2177. state.state,
  2178. )
  2179. except Exception as e:
  2180. status_logger.warning(
  2181. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  2182. )
  2183. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  2184. try:
  2185. printer_info = printer_manager.get_printer(printer_id)
  2186. if printer_info:
  2187. await mqtt_relay.on_printer_status(
  2188. printer_id,
  2189. state,
  2190. printer_info.name,
  2191. printer_info.serial_number,
  2192. printer_manager.is_awaiting_plate_clear(printer_id),
  2193. )
  2194. except Exception:
  2195. pass # Don't fail status callback if MQTT fails
  2196. if _last_status_broadcast.get(printer_id) == status_key:
  2197. return # No change, skip WebSocket broadcast
  2198. _last_status_broadcast[printer_id] = status_key
  2199. # Check for progress milestone notifications (25%, 50%, 75%)
  2200. progress = state.progress or 0
  2201. is_printing = state.state in ("RUNNING", "PRINTING")
  2202. if is_printing and progress > 0:
  2203. current_milestone = _progress_milestone_to_notify(printer_id, state)
  2204. if current_milestone is not None:
  2205. try:
  2206. from backend.app.models.printer import Printer
  2207. # Read the printer in a short session and release the connection
  2208. # BEFORE the ~15s camera snapshot below — holding it across the grab
  2209. # pinned a pooled connection per milestone, per printer (issue #2572).
  2210. async with async_session() as db:
  2211. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2212. printer = result.scalar_one_or_none()
  2213. printer_name = printer.name if printer else f"Printer {printer_id}"
  2214. filename = state.subtask_name or state.gcode_file or "Unknown"
  2215. # remaining_time is in minutes, convert to seconds for notification
  2216. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  2217. # Capture camera snapshot for notification image attachment (no DB held).
  2218. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  2219. # Notification send needs a session (provider/template lookups).
  2220. async with async_session() as db:
  2221. await notification_service.on_print_progress(
  2222. printer_id,
  2223. printer_name,
  2224. filename,
  2225. current_milestone,
  2226. db,
  2227. remaining_time_seconds,
  2228. image_data=image_data,
  2229. )
  2230. except Exception as e:
  2231. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  2232. elif progress < 5:
  2233. # Reset milestone tracking when print restarts or new print begins
  2234. _last_progress_milestone[printer_id] = 0
  2235. _first_layer_notified[printer_id] = False
  2236. # HMS error codes that should not trigger notifications even though they
  2237. # have known descriptions (e.g. user-initiated actions, not real errors).
  2238. _HMS_NOTIFICATION_SUPPRESS = {
  2239. "0500_400E", # Printing was cancelled (user action, not an error)
  2240. }
  2241. # Check for new HMS errors and send notifications
  2242. current_hms_errors = getattr(state, "hms_errors", []) or []
  2243. if current_hms_errors:
  2244. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  2245. if new_errors:
  2246. try:
  2247. from backend.app.models.printer import Printer
  2248. # Read the printer in a short session and release the connection
  2249. # BEFORE the ~15s camera snapshot below (issue #2572).
  2250. async with async_session() as db:
  2251. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2252. printer = result.scalar_one_or_none()
  2253. printer_name = printer.name if printer else f"Printer {printer_id}"
  2254. # Format error details for notification
  2255. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  2256. module_names = {
  2257. 0x03: "Print/Task",
  2258. 0x05: "Nozzle/Extruder",
  2259. 0x07: "AMS/Filament",
  2260. 0x0C: "Motion Controller",
  2261. 0x12: "Chamber",
  2262. }
  2263. # Capture camera snapshot once for all error notifications (no DB held).
  2264. error_image_data = await _capture_snapshot_for_notification(
  2265. printer_id, printer, logging.getLogger(__name__)
  2266. )
  2267. # Notification sends need a session (provider/template lookups).
  2268. async with async_session() as db:
  2269. sent_count = 0
  2270. for error in new_errors:
  2271. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  2272. # Build short code like "0700_8010"
  2273. # Mask to 16 bits to handle printers that send larger values
  2274. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  2275. error_code_masked = error_code_int & 0xFFFF
  2276. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  2277. # Only notify for errors Bambu publishes text for — printers
  2278. # send undocumented codes that aren't real errors, and Bambu
  2279. # lists some with empty text. Resolved at parse time (#2926);
  2280. # short_code is still needed for the suppression set below.
  2281. description = error.description
  2282. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  2283. continue
  2284. error_type = f"{module_name} Error"
  2285. error_detail = description
  2286. await notification_service.on_printer_error(
  2287. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  2288. )
  2289. sent_count += 1
  2290. if sent_count:
  2291. logging.getLogger(__name__).info(
  2292. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  2293. )
  2294. # Also publish to MQTT relay (no DB): every new fault that
  2295. # counts, with or without text, the same set the UI counts.
  2296. printer_info = printer_manager.get_printer(printer_id)
  2297. if printer_info:
  2298. errors_data = [
  2299. {
  2300. "code": e.code,
  2301. "attr": e.attr,
  2302. "module": e.module,
  2303. "severity": e.severity,
  2304. }
  2305. for e in new_errors
  2306. ]
  2307. await mqtt_relay.on_printer_error(
  2308. printer_id, printer_info.name, printer_info.serial_number, errors_data
  2309. )
  2310. except Exception as e:
  2311. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  2312. else:
  2313. # No HMS errors: nothing to send, but faults gone long enough (or gone
  2314. # across a print state change) are forgotten. Some codes, e.g. chamber
  2315. # temperature regulation during PETG prints, toggle every few seconds.
  2316. _take_new_hms_faults(printer_id, [], state.state)
  2317. await ws_manager.send_printer_status(
  2318. printer_id,
  2319. printer_state_to_dict(
  2320. state,
  2321. printer_id,
  2322. printer_manager.get_model(printer_id),
  2323. printer_manager.get_drying_targets(printer_id),
  2324. ),
  2325. )
  2326. def _is_bambu_uuid(tray_uuid: str) -> bool:
  2327. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  2328. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  2329. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  2330. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  2331. K-profiles are per-nozzle and the printer's calibration table is numbered
  2332. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  2333. switch's other inlet therefore silently invalidates every configured slot in
  2334. it: the index stays put and now resolves against the other nozzle's table.
  2335. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  2336. and 0.020 on the right kept the left profile after the move, and a manual
  2337. RFID re-read only re-asserted the same wrong one.
  2338. Configuring a slot is a deliberate preparation step, so this re-selects
  2339. rather than re-configures: only the calibration binding moves, and only for
  2340. slots whose spool already has a stored profile for the new nozzle. A slot
  2341. Bambuddy knows nothing about is left exactly as the operator left it.
  2342. """
  2343. logger = logging.getLogger(__name__)
  2344. target_extruder = extruder_for_inlet(inlet)
  2345. if target_extruder is None:
  2346. return
  2347. client = printer_manager.get_client(printer_id)
  2348. state = printer_manager.get_status(printer_id)
  2349. if not client or not state or not state.raw_data:
  2350. return
  2351. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  2352. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  2353. # the nozzle width, which changes both the K profile to select and the
  2354. # preset the slot should carry.
  2355. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  2356. ams_raw = state.raw_data.get("ams")
  2357. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2358. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  2359. if not unit:
  2360. return
  2361. try:
  2362. async with async_session() as db:
  2363. for tray in unit.get("tray", []):
  2364. tray_id = int(tray.get("id", -1))
  2365. if tray_id < 0 or not tray.get("tray_type"):
  2366. continue
  2367. current_idx = tray.get("cali_idx")
  2368. profile = await find_slot_kprofile_for_extruder(
  2369. db,
  2370. printer_id,
  2371. ams_id,
  2372. tray_id,
  2373. target_extruder,
  2374. nozzle_diameter,
  2375. printer_manager.get_model(printer_id),
  2376. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2377. )
  2378. if profile is None or profile.cali_idx is None:
  2379. continue
  2380. if current_idx == profile.cali_idx:
  2381. continue # Already on the right one.
  2382. logger.info(
  2383. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2384. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2385. printer_id,
  2386. ams_id,
  2387. tray_id,
  2388. inlet,
  2389. target_extruder,
  2390. profile.name,
  2391. current_idx,
  2392. profile.cali_idx,
  2393. profile.k_value,
  2394. )
  2395. client.extrusion_cali_sel(
  2396. ams_id=ams_id,
  2397. tray_id=tray_id,
  2398. cali_idx=profile.cali_idx,
  2399. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2400. nozzle_diameter=nozzle_diameter,
  2401. )
  2402. except Exception as e:
  2403. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2404. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2405. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2406. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2407. from the delayed re-check -- which is why it takes the AMS data and print
  2408. state as arguments instead of reading them from the push (#3186).
  2409. """
  2410. logger = logging.getLogger(__name__)
  2411. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2412. # Auto-unlink spool assignments with stale fingerprints. Under the
  2413. # per-printer assignment lock since #3186: the held-removal re-check runs
  2414. # this outside any MQTT push, so it can now overlap one.
  2415. try:
  2416. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2417. from sqlalchemy.orm import selectinload
  2418. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2419. from backend.app.models.spool import Spool as _Spool
  2420. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2421. from backend.app.services.ams_slot_presence import spool_present
  2422. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2423. # Built-in assignments only. Since #2812 they survive a switch to
  2424. # Spoolman mode rather than being deleted by it, and this pass ends
  2425. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2426. # time as the AMS contents changed under the other mode, undoing the
  2427. # preservation more slowly but just as completely.
  2428. assignments = []
  2429. if not await spoolman_owns_assignments(db):
  2430. result = await db.execute(
  2431. select(SA)
  2432. .where(SA.printer_id == printer_id)
  2433. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2434. )
  2435. assignments = result.scalars().all()
  2436. # ``printing_now`` (top of this function) keeps a runout from
  2437. # unlinking the spool that fed the print — the next idle-time pass
  2438. # unlinks it if the user really did take it out.
  2439. stale = []
  2440. # Removals this pass is holding rather than unlinking (#3186).
  2441. held: set[tuple] = set()
  2442. for assignment in assignments:
  2443. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2444. if assignment.ams_id == 255:
  2445. ps = printer_manager.get_status(printer_id)
  2446. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2447. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2448. current_tray = None
  2449. for vt in vt_tray_raw:
  2450. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2451. current_tray = vt
  2452. break
  2453. if not current_tray:
  2454. # vt_tray data may not have arrived yet — keep assignment
  2455. continue
  2456. else:
  2457. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2458. if not current_tray:
  2459. if printing_now:
  2460. logger.info(
  2461. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2462. assignment.spool_id,
  2463. assignment.ams_id,
  2464. assignment.tray_id,
  2465. )
  2466. continue
  2467. # A whole AMS unit can drop out of one push and come back in
  2468. # the next; only a slot that stays gone is a removal (#3186).
  2469. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2470. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2471. held.add(hold_key)
  2472. logger.info(
  2473. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2474. "unlinking if it is still gone in %ds",
  2475. assignment.spool_id,
  2476. assignment.ams_id,
  2477. assignment.tray_id,
  2478. int(slot_unlink_grace.GRACE_SECONDS),
  2479. )
  2480. continue
  2481. logger.info(
  2482. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2483. assignment.spool_id,
  2484. assignment.ams_id,
  2485. assignment.tray_id,
  2486. )
  2487. stale.append(assignment) # Slot empty
  2488. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2489. # A Bambu Lab spool is in this slot — check if it's the same spool
  2490. # that's currently assigned. If yes, keep the assignment (avoids
  2491. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2492. # the printer's filament preset on every startup).
  2493. tray_uuid = current_tray.get("tray_uuid", "")
  2494. tag_uid = current_tray.get("tag_uid", "")
  2495. spool = assignment.spool
  2496. spool_matches = False
  2497. if spool:
  2498. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2499. spool.tag_uid
  2500. and tag_uid
  2501. and tag_uid != "0000000000000000"
  2502. and spool.tag_uid.upper() == tag_uid.upper()
  2503. ):
  2504. spool_matches = True
  2505. if spool_matches:
  2506. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2507. cur_color = current_tray.get("tray_color", "")
  2508. cur_type = current_tray.get("tray_type", "")
  2509. fp_color = assignment.fingerprint_color or ""
  2510. fp_type = assignment.fingerprint_type or ""
  2511. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2512. assignment.fingerprint_color = cur_color
  2513. assignment.fingerprint_type = cur_type
  2514. logger.debug(
  2515. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2516. assignment.spool_id,
  2517. assignment.ams_id,
  2518. assignment.tray_id,
  2519. )
  2520. continue
  2521. # Different BL spool or unrecognized — unlink so auto-assign can match
  2522. logger.info(
  2523. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2524. assignment.spool_id,
  2525. assignment.ams_id,
  2526. assignment.tray_id,
  2527. tray_uuid,
  2528. )
  2529. stale.append(assignment)
  2530. else:
  2531. cur_color = current_tray.get("tray_color", "")
  2532. cur_type = current_tray.get("tray_type", "")
  2533. cur_state = current_tray.get("state")
  2534. fp_color = assignment.fingerprint_color or ""
  2535. fp_type = assignment.fingerprint_type or ""
  2536. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2537. # the slot was empty when the user pre-assigned via SpoolBuddy
  2538. # (the firmware drops ams_filament_setting on empty slots, so
  2539. # MQTT was deferred). The moment any filament gets inserted
  2540. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2541. # reconfigured spool — fire the deferred configuration.
  2542. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2543. # extruder" code) OR, on firmwares that don't use the state
  2544. # enum meaningfully, a non-empty tray_type when state is
  2545. # NOT one of the firmware's explicit empty signals (9, 10).
  2546. # state-only was wrong for firmwares that never set 11 — A1
  2547. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2548. # always report state=3 — so the replay never fired for them
  2549. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2550. # explicit "empty" signals authoritative over any stale
  2551. # tray_type that might survive the relay's auto-clearing.
  2552. #
  2553. # tray_exist_bits comes first because that guard cannot tell
  2554. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2555. # writes state=9 when the bit is 0 and leaves it there when the
  2556. # bit returns. A non-RFID spool inserted into a pre-assigned
  2557. # slot brings no tray_type with it, so the stale 9 made this
  2558. # expression false forever and the deferred config never fired
  2559. # — the deadlock #1322 removed from the assign path, still in
  2560. # place here (#3084, #3100).
  2561. loaded = spool_present(current_tray) is True or (
  2562. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2563. )
  2564. if not fp_type.strip() and loaded and assignment.spool:
  2565. # The fingerprint ends this replay. Not recorded when nothing
  2566. # could be sent (no MQTT client while the printer reconnects),
  2567. # so the next AMS change tries again. An attempt that raised is
  2568. # recorded as before: it may have sent part of the commands and
  2569. # would raise again on every change, remain% steps included.
  2570. configured: bool | None = False
  2571. try:
  2572. from backend.app.api.routes.inventory import (
  2573. apply_spool_to_slot_via_mqtt,
  2574. )
  2575. configured = await apply_spool_to_slot_via_mqtt(
  2576. db=db,
  2577. current_user=None,
  2578. spool=assignment.spool,
  2579. printer_id=printer_id,
  2580. ams_id=assignment.ams_id,
  2581. tray_id=assignment.tray_id,
  2582. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2583. current_tray_type=cur_type,
  2584. current_tray_sub_brands=current_tray.get("tray_sub_brands", ""),
  2585. )
  2586. except Exception:
  2587. logger.exception(
  2588. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2589. assignment.spool_id,
  2590. printer_id,
  2591. assignment.ams_id,
  2592. assignment.tray_id,
  2593. )
  2594. configured = None
  2595. if configured is False:
  2596. logger.warning(
  2597. "Pre-config not sent for spool %d on printer %d AMS%d-T%d (no MQTT client); "
  2598. "retrying on the next AMS change",
  2599. assignment.spool_id,
  2600. printer_id,
  2601. assignment.ams_id,
  2602. assignment.tray_id,
  2603. )
  2604. else:
  2605. if configured:
  2606. logger.info(
  2607. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2608. assignment.spool_id,
  2609. printer_id,
  2610. assignment.ams_id,
  2611. assignment.tray_id,
  2612. )
  2613. assignment.fingerprint_color = cur_color
  2614. assignment.fingerprint_type = cur_type
  2615. continue
  2616. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2617. # Blank tray data mid-print is a runout, not a swap: the
  2618. # firmware clears colour and type when it unloads a spool
  2619. # it just emptied. Unlinking here would erase the record
  2620. # of which spool fed the print so far.
  2621. if printing_now and not cur_color.strip() and not cur_type.strip():
  2622. logger.info(
  2623. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2624. "(runout?)",
  2625. assignment.spool_id,
  2626. assignment.ams_id,
  2627. assignment.tray_id,
  2628. )
  2629. continue
  2630. # Same reasoning off the print, on firmware's own say-so:
  2631. # a blank tray report from a slot whose tray_exist_bits
  2632. # bit is set describes a spool the AMS cannot identify —
  2633. # a non-RFID one, or one whose slot was reset — not a
  2634. # spool that was taken out. Deleting the assignment there
  2635. # threw away the identity the user had supplied, which is
  2636. # the only place it existed (#3100). A slot the bit calls
  2637. # empty, or one that carries no bit at all, still unlinks.
  2638. #
  2639. # Unless the slot was reported empty first: a removal
  2640. # already held means a spool came out and another went
  2641. # in, so the blank report keeps the hold running below
  2642. # rather than cancelling it (#3186).
  2643. if (
  2644. spool_present(current_tray) is True
  2645. and not cur_color.strip()
  2646. and not cur_type.strip()
  2647. and not slot_unlink_grace.is_held(
  2648. printer_id,
  2649. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2650. )
  2651. ):
  2652. logger.info(
  2653. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2654. "tray reports no filament data yet",
  2655. assignment.spool_id,
  2656. assignment.ams_id,
  2657. assignment.tray_id,
  2658. )
  2659. continue
  2660. # A blank report the presence bit does not vouch for is
  2661. # still only one push. An idle X1C cleared a whole AMS
  2662. # unit's bits, colour and type for a moment and lost
  2663. # four saved assignments that way (#3186); unlink only
  2664. # if the slot is still blank after the grace period.
  2665. if not cur_color.strip() and not cur_type.strip():
  2666. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2667. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2668. held.add(hold_key)
  2669. logger.info(
  2670. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2671. "unlinking if it is still blank in %ds",
  2672. assignment.spool_id,
  2673. assignment.ams_id,
  2674. assignment.tray_id,
  2675. int(slot_unlink_grace.GRACE_SECONDS),
  2676. )
  2677. continue
  2678. # Fingerprint mismatch — but check if tray now matches the
  2679. # assigned spool (e.g. auto-configure changed the tray).
  2680. # Both sides are reduced to the type the slot can carry
  2681. # before comparing: the assign path writes that rather
  2682. # than the spool's raw material (#2902), so a spool whose
  2683. # material is a product line — "PLA+", "HTPLA" — reports
  2684. # back as "PLA" and would otherwise fail this check and
  2685. # be auto-unlinked from the slot it was just assigned to.
  2686. # Reducing the printer's side too keeps slots configured
  2687. # by an older Bambuddy, still reporting "PLA+", matching.
  2688. spool = assignment.spool
  2689. if spool:
  2690. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2691. # Two ways the assign path can have arrived at the
  2692. # slot's type, so both count as "we wrote this".
  2693. # The material column is one; the spool's preset is
  2694. # the other, and it outranks the material when the
  2695. # spool has one -- a spool whose material says PLA
  2696. # and whose preset is "Bambu PLA Aero" puts
  2697. # PLA-AERO in the slot (#2902). Read from the stored
  2698. # preset name rather than resolving the preset,
  2699. # because this runs on every AMS push and a cloud
  2700. # lookup here would be both slow and unavailable on
  2701. # the unauthenticated replay path.
  2702. spool_types = {printer_filament_type(spool.material).upper()}
  2703. if spool.slicer_filament_name:
  2704. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2705. # An imported local preset stores its type outright,
  2706. # which is what the assign path used -- and the name
  2707. # above may be unset. One keyed read, and only on a
  2708. # mismatch, which is rare.
  2709. #
  2710. # slicer_filament is free text up to fifty characters,
  2711. # so the digits have to be checked against the range
  2712. # of the integer primary key they are about to be
  2713. # compared with. Postgres raises on an out-of-range
  2714. # integer rather than simply not matching, and that
  2715. # would poison this session and abandon the rest of
  2716. # the cleanup pass.
  2717. lp_ref = (spool.slicer_filament or "").strip()
  2718. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2719. from backend.app.models.local_preset import LocalPreset as _LP
  2720. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2721. if lp_type:
  2722. spool_types.add(printer_filament_type(lp_type).upper())
  2723. if (
  2724. _colors_similar(cur_color, spool_color)
  2725. and printer_filament_type(cur_type).upper() in spool_types
  2726. ):
  2727. logger.info(
  2728. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2729. assignment.spool_id,
  2730. assignment.ams_id,
  2731. assignment.tray_id,
  2732. )
  2733. assignment.fingerprint_color = cur_color
  2734. assignment.fingerprint_type = cur_type
  2735. continue
  2736. logger.info(
  2737. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2738. assignment.spool_id,
  2739. assignment.ams_id,
  2740. assignment.tray_id,
  2741. cur_color,
  2742. cur_type,
  2743. fp_color,
  2744. fp_type,
  2745. spool.rgba if spool else "?",
  2746. spool.material if spool else "?",
  2747. )
  2748. stale.append(assignment) # Spool changed
  2749. slot_unlink_grace.settle(printer_id, "inventory", held)
  2750. # Snapshot slots before delete — ORM attribute access after the
  2751. # commit would refresh against a deleted row.
  2752. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2753. for a in stale:
  2754. await db.delete(a)
  2755. if stale:
  2756. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2757. # Commit any changes (stale deletions and/or fingerprint updates)
  2758. await db.commit()
  2759. # Tell open browsers the assignment is gone (#2575). Only the manual
  2760. # REST assign/unassign endpoints broadcast this event; without it the
  2761. # frontend's spool-assignments cache keeps rendering the unlinked
  2762. # spool on the slot until an unrelated refetch — which reads exactly
  2763. # like "the fix didn't work" (reporter verified: a browser refresh
  2764. # after the swap showed the correct state all along).
  2765. for ams_id, tray_id in unlinked_slots:
  2766. await ws_manager.broadcast(
  2767. {
  2768. "type": "spool_assignment_changed",
  2769. "printer_id": printer_id,
  2770. "ams_id": ams_id,
  2771. "tray_id": tray_id,
  2772. }
  2773. )
  2774. except Exception as e:
  2775. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2776. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2777. """Delete Spoolman slot rows whose held removal has run its grace period.
  2778. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2779. talks to Spoolman for every tray; this only needs the local rows, so it
  2780. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2781. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2782. not in a slot the presence bit calls occupied -- and nothing else.
  2783. """
  2784. logger = logging.getLogger(__name__)
  2785. try:
  2786. async with async_session() as db:
  2787. from backend.app.api.routes.settings import get_setting
  2788. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2789. from backend.app.services.ams_slot_presence import spool_present
  2790. enabled = await get_setting(db, "spoolman_enabled")
  2791. if not enabled or enabled.lower() != "true":
  2792. return
  2793. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2794. if sync_mode and sync_mode != "auto":
  2795. return
  2796. trays: dict[tuple[int, int], dict] = {}
  2797. for ams_unit in ams_data or []:
  2798. if not isinstance(ams_unit, dict):
  2799. continue
  2800. for tray in ams_unit.get("tray", []):
  2801. if isinstance(tray, dict):
  2802. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2803. rows = (
  2804. (
  2805. await db.execute(
  2806. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2807. )
  2808. )
  2809. .scalars()
  2810. .all()
  2811. )
  2812. held: set[tuple] = set()
  2813. expired: list[tuple[int, int]] = []
  2814. for row in rows:
  2815. tray = trays.get((row.ams_id, row.tray_id))
  2816. if tray is None or printing_now:
  2817. continue
  2818. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2819. continue
  2820. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2821. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2822. continue
  2823. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2824. expired.append((row.ams_id, row.tray_id))
  2825. else:
  2826. held.add(hold_key)
  2827. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2828. if not expired:
  2829. return
  2830. # A statement rather than ORM deletes, like the sync pass: the two
  2831. # can overlap, and a row the other already removed must not fail
  2832. # this commit.
  2833. for ams_id, tray_id in expired:
  2834. await db.execute(
  2835. delete(SpoolmanSlotAssignment).where(
  2836. SpoolmanSlotAssignment.printer_id == printer_id,
  2837. SpoolmanSlotAssignment.ams_id == ams_id,
  2838. SpoolmanSlotAssignment.tray_id == tray_id,
  2839. )
  2840. )
  2841. await db.commit()
  2842. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2843. for ams_id, tray_id in expired:
  2844. await ws_manager.broadcast(
  2845. {
  2846. "type": "spool_assignment_changed",
  2847. "printer_id": printer_id,
  2848. "ams_id": ams_id,
  2849. "tray_id": tray_id,
  2850. }
  2851. )
  2852. except Exception as e:
  2853. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2854. async def _recheck_held_unlinks(printer_id: int) -> None:
  2855. """Re-run just the slot cleanup against the printer's current AMS state.
  2856. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2857. passes otherwise run only when the AMS hash changes, and a slot that went
  2858. empty and stayed empty may never change it again.
  2859. """
  2860. status = printer_manager.get_status(printer_id)
  2861. # A disconnected printer's state is its last report, not a new one: acting
  2862. # on it would "confirm" a removal nobody has seen for the whole grace
  2863. # period. Leave the holds; the first push after reconnecting decides.
  2864. if status is None or not status.connected:
  2865. return
  2866. ams_raw = status.raw_data.get("ams")
  2867. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2868. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2869. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2870. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2871. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2872. async def on_ams_change(printer_id: int, ams_data: list):
  2873. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2874. logger = logging.getLogger(__name__)
  2875. # Snapshot BEFORE any await: if a print is active, or a finished one is
  2876. # still being charged, skip weight sync later. on_print_complete may pop
  2877. # _active_sessions during our awaits (#880).
  2878. from backend.app.services.usage_tracker import printer_is_charging
  2879. _print_active = printer_is_charging(printer_id)
  2880. # A slot that reports empty while a print is running is a filament runout,
  2881. # not a spool swap: the spool is still physically in the AMS, just
  2882. # consumed. Dropping either inventory backend's slot link there loses the
  2883. # only record of which spool fed the print, so the completion path can't
  2884. # charge the runout segment to anything. Both cleanup passes below consult
  2885. # this; computed once, up front, so neither depends on the other having run.
  2886. _unlink_state = printer_manager.get_status(printer_id)
  2887. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2888. # The session alone is not enough: a restart that finds a stale persisted
  2889. # session registers none for the print that is running.
  2890. _print_active = _print_active or printing_now
  2891. # MQTT relay - publish AMS change
  2892. try:
  2893. printer_info = printer_manager.get_printer(printer_id)
  2894. if printer_info:
  2895. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2896. except Exception:
  2897. pass # Don't fail AMS callback if MQTT fails
  2898. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2899. # This ensures frontend gets immediate updates when AMS slots are configured
  2900. try:
  2901. state = printer_manager.get_status(printer_id)
  2902. if state:
  2903. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2904. await ws_manager.send_printer_status(
  2905. printer_id,
  2906. printer_state_to_dict(
  2907. state,
  2908. printer_id,
  2909. printer_manager.get_model(printer_id),
  2910. printer_manager.get_drying_targets(printer_id),
  2911. ),
  2912. )
  2913. except Exception as e:
  2914. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2915. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2916. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2917. # Serialised per-printer via services/ams_assignment_lock: MQTT bursts can deliver
  2918. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2919. # "no existing assignment" for the same (printer, ams, tray) and race to
  2920. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2921. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2922. # bug stayed latent there. See services/ams_assignment_lock for details.
  2923. try:
  2924. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2925. from sqlalchemy.orm import selectinload
  2926. from backend.app.api.routes.settings import get_setting
  2927. from backend.app.models.spool import Spool
  2928. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2929. from backend.app.services.spool_tag_matcher import (
  2930. auto_assign_spool,
  2931. create_spool_from_tray,
  2932. find_matching_untagged_spool,
  2933. get_spool_by_tag,
  2934. is_bambu_tag,
  2935. is_valid_tag,
  2936. link_tag_to_inventory_spool,
  2937. tag_belongs_to_archived_spool,
  2938. )
  2939. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2940. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2941. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2942. if not _spoolman_on or _spoolman_on.lower() != "true":
  2943. for ams_unit in ams_data:
  2944. if not isinstance(ams_unit, dict):
  2945. continue
  2946. ams_id = int(ams_unit.get("id", 0))
  2947. for tray in ams_unit.get("tray", []):
  2948. if not isinstance(tray, dict):
  2949. continue
  2950. tray_id = int(tray.get("id", 0))
  2951. tag_uid = tray.get("tag_uid", "")
  2952. tray_uuid = tray.get("tray_uuid", "")
  2953. tray_info_idx = tray.get("tray_info_idx", "")
  2954. if not tray.get("tray_type"):
  2955. # Slot reported empty — drop any cached unknown-tag
  2956. # broadcast so reinserting the same spool re-prompts.
  2957. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2958. continue # Empty slot
  2959. # Check if assignment already exists for this slot
  2960. existing = await db.execute(
  2961. select(SA)
  2962. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2963. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2964. )
  2965. existing_assignment = existing.scalar_one_or_none()
  2966. if existing_assignment:
  2967. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2968. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2969. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2970. # Skip during active prints: the usage tracker handles deduction
  2971. # precisely via 3MF data on print completion. Without this guard the
  2972. # AMS remain% SET and the usage tracker ADD both fire from the same
  2973. # MQTT message, doubling the deduction (#880).
  2974. if _print_active:
  2975. continue
  2976. remain_raw = tray.get("remain")
  2977. if (
  2978. remain_raw is not None
  2979. and existing_assignment.spool
  2980. and not existing_assignment.spool.weight_locked
  2981. ):
  2982. try:
  2983. remain_val = int(remain_raw)
  2984. except (TypeError, ValueError):
  2985. remain_val = -1
  2986. if 1 <= remain_val <= 100:
  2987. lw = existing_assignment.spool.label_weight or 1000
  2988. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2989. current_used = existing_assignment.spool.weight_used or 0
  2990. if new_used > current_used + 1:
  2991. # Rechecked in the statement: the spool was loaded
  2992. # before this, and a weight set by hand (or weighed)
  2993. # and locked since then must stay (WL-6).
  2994. result = cast(
  2995. CursorResult,
  2996. await db.execute(
  2997. update(Spool)
  2998. .where(
  2999. Spool.id == existing_assignment.spool_id,
  3000. Spool.weight_locked.is_not(True),
  3001. func.coalesce(Spool.weight_used, 0) < new_used - 1,
  3002. )
  3003. .values(weight_used=new_used)
  3004. ),
  3005. )
  3006. await db.commit()
  3007. if result.rowcount:
  3008. logger.info(
  3009. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  3010. existing_assignment.spool_id,
  3011. current_used,
  3012. new_used,
  3013. remain_val,
  3014. )
  3015. await ws_manager.broadcast({"type": "inventory_changed"})
  3016. # A K-profile the slot lost (the default K after a reset or
  3017. # power cycle) is put back by kprofile_drift on the next idle
  3018. # push; a different real profile was picked on purpose and
  3019. # stays (#3219, item 44).
  3020. continue
  3021. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  3022. # BL spool with RFID tag: auto-match → inventory match → auto-create
  3023. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  3024. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  3025. # An archived spool still in the AMS: the slot
  3026. # stays free rather than adopting its tag.
  3027. continue
  3028. if not spool:
  3029. # Try matching an untagged inventory spool (same material/color)
  3030. spool = await find_matching_untagged_spool(db, tray)
  3031. if spool:
  3032. await link_tag_to_inventory_spool(db, spool, tray)
  3033. elif _auto_add_unknown:
  3034. spool = await create_spool_from_tray(db, tray)
  3035. else:
  3036. # Auto-add disabled: surface the slot so the
  3037. # user can add it manually via the UI.
  3038. await _broadcast_unknown_tag(
  3039. printer_id=printer_id,
  3040. ams_id=ams_id,
  3041. tray_id=tray_id,
  3042. tag_uid=tag_uid,
  3043. tray_uuid=tray_uuid,
  3044. tray_type=tray.get("tray_type"),
  3045. tray_color=tray.get("tray_color"),
  3046. tray_sub_brands=tray.get("tray_sub_brands"),
  3047. tray_count=len(ams_unit.get("tray", [])),
  3048. )
  3049. continue
  3050. # Slot matched (existing tag, untagged inventory
  3051. # match, or freshly auto-created spool) — drop any
  3052. # stale dedup so a future tag swap re-prompts.
  3053. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  3054. await auto_assign_spool(
  3055. printer_id,
  3056. ams_id,
  3057. tray_id,
  3058. spool,
  3059. printer_manager,
  3060. db,
  3061. tray_info_idx=tray_info_idx,
  3062. )
  3063. await db.commit()
  3064. await ws_manager.broadcast(
  3065. {
  3066. "type": "spool_auto_assigned",
  3067. "printer_id": printer_id,
  3068. "ams_id": ams_id,
  3069. "tray_id": tray_id,
  3070. "spool_id": spool.id,
  3071. }
  3072. )
  3073. logger.info(
  3074. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  3075. spool.id,
  3076. printer_id,
  3077. ams_id,
  3078. tray_id,
  3079. )
  3080. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  3081. db, tag_uid, tray_uuid
  3082. ):
  3083. # Non-BL spool with some tag — let user choose (not
  3084. # an archived one's, whose slot stays free)
  3085. await _broadcast_unknown_tag(
  3086. printer_id=printer_id,
  3087. ams_id=ams_id,
  3088. tray_id=tray_id,
  3089. tag_uid=tag_uid,
  3090. tray_uuid=tray_uuid,
  3091. tray_type=tray.get("tray_type"),
  3092. tray_color=tray.get("tray_color"),
  3093. tray_sub_brands=tray.get("tray_sub_brands"),
  3094. tray_count=len(ams_unit.get("tray", [])),
  3095. )
  3096. # No-tag slots (generic non-RFID filament) are left alone:
  3097. # nothing to identify, prompting "+ Add" would just create
  3098. # ghost spools with empty tags on every confirm.
  3099. except Exception as e:
  3100. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  3101. try:
  3102. async with async_session() as db:
  3103. from backend.app.api.routes.settings import get_setting
  3104. from backend.app.models.printer import Printer
  3105. # Check if Spoolman is enabled
  3106. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  3107. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  3108. return
  3109. # Check sync mode
  3110. sync_mode = await get_setting(db, "spoolman_sync_mode")
  3111. if sync_mode and sync_mode != "auto":
  3112. return # Only sync on auto mode
  3113. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  3114. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  3115. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  3116. # always owned by per-print tracking, never by AMS auto-sync. The
  3117. # setting is still read by the settings UI for backwards compat but
  3118. # has no effect on the sync path here.
  3119. # Get Spoolman URL
  3120. spoolman_url = await get_setting(db, "spoolman_url")
  3121. if not spoolman_url:
  3122. return
  3123. # Get or create Spoolman client
  3124. client = await get_spoolman_client()
  3125. if not client:
  3126. try:
  3127. client = await init_spoolman_client(spoolman_url)
  3128. except ValueError as exc:
  3129. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  3130. return
  3131. # Check if Spoolman is reachable
  3132. if not await client.health_check():
  3133. logger.warning("Spoolman not reachable at %s", spoolman_url)
  3134. return
  3135. # Get printer name for location
  3136. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3137. printer = result.scalar_one_or_none()
  3138. printer_name = printer.name if printer else f"Printer {printer_id}"
  3139. # OPTIMIZATION: Fetch all spools once before processing trays
  3140. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  3141. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  3142. try:
  3143. cached_spools = await client.get_spools()
  3144. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  3145. except Exception as e:
  3146. logger.error(
  3147. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  3148. printer_id,
  3149. e,
  3150. )
  3151. return
  3152. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  3153. from sqlalchemy.orm import selectinload
  3154. from backend.app.models.spool_assignment import SpoolAssignment
  3155. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  3156. from backend.app.services.ams_slot_presence import spool_present
  3157. from backend.app.services.inventory_mode import spoolman_owns_assignments
  3158. # Built-in remaining weight, used by sync_ams_tray only when the
  3159. # firmware reports an unusable remain%/tray_weight for a slot.
  3160. #
  3161. # Left empty since #2812. This block runs in Spoolman mode only,
  3162. # and until then the built-in table was emptied on the switch, so
  3163. # there was never anything here to read and the fallback was inert.
  3164. # Preserving those rows makes it live again, and it is keyed by slot
  3165. # rather than by spool: after a mode switch the tray may well hold
  3166. # different filament, and ``create_spool`` writes ``remaining_weight``
  3167. # unconditionally, so a stale figure would be seeded into a brand new
  3168. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  3169. # intent survives for whoever revisits the cross-mode fallback.
  3170. inventory_weights: dict[tuple[int, int], float] = {}
  3171. if not await spoolman_owns_assignments(db):
  3172. try:
  3173. assign_result = await db.execute(
  3174. select(SpoolAssignment)
  3175. .options(selectinload(SpoolAssignment.spool))
  3176. .where(SpoolAssignment.printer_id == printer_id)
  3177. )
  3178. for assignment in assign_result.scalars().all():
  3179. spool = assignment.spool
  3180. if spool and spool.label_weight > 0:
  3181. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  3182. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  3183. except Exception as e:
  3184. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  3185. # Load existing Spoolman slot assignments for the no-RFID fallback path
  3186. spoolman_slot_map: dict[tuple[int, int], int] = {}
  3187. slot_map_read = False
  3188. try:
  3189. slot_result = await db.execute(
  3190. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  3191. )
  3192. for slot in slot_result.scalars().all():
  3193. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  3194. slot_map_read = True
  3195. except Exception as e:
  3196. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  3197. # Sync each AMS tray and collect slot changes for DB persistence
  3198. synced = 0
  3199. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  3200. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  3201. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  3202. for ams_unit in ams_data:
  3203. if not isinstance(ams_unit, dict):
  3204. continue
  3205. ams_id = int(ams_unit.get("id", 0))
  3206. trays = ams_unit.get("tray", [])
  3207. for tray_data in trays:
  3208. if not isinstance(tray_data, dict):
  3209. continue
  3210. tray_id_raw = int(tray_data.get("id", 0))
  3211. tray = client.parse_ams_tray(ams_id, tray_data)
  3212. if not tray:
  3213. # Empty tray slot — record for local assignment cleanup
  3214. # and drop any cached unknown-tag broadcast so a
  3215. # reinserted spool re-prompts.
  3216. #
  3217. # Not during a running print: a slot that empties there
  3218. # is a filament runout, and the spool is still in the
  3219. # AMS. `spoolman_slot_assignments` is how a tag-less
  3220. # spool assigned through the Bambuddy UI is resolved at
  3221. # completion (#1459), so deleting the row mid-print
  3222. # loses the runout segment's usage — the same failure
  3223. # the internal inventory's auto-unlink had.
  3224. #
  3225. # Nor when firmware's presence bit says the slot is
  3226. # occupied. parse_ams_tray calls a tray with no type or
  3227. # no colour empty, and a spool the AMS cannot read has
  3228. # neither until something configures it — so a tag-less
  3229. # spool assigned through the UI had its row deleted by
  3230. # the first idle push after it was inserted. Same
  3231. # deletion as the internal inventory's in #3100, same
  3232. # answer, so the two modes stay in step.
  3233. #
  3234. # And only once the slot has stayed empty for the grace
  3235. # period -- the internal inventory's #3186 answer, for
  3236. # the same one-push blank.
  3237. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  3238. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  3239. if not printing_now and (
  3240. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  3241. ):
  3242. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  3243. empty_slots.append((ams_id, tray_id_raw))
  3244. else:
  3245. spoolman_held.add(hold_key)
  3246. logger.info(
  3247. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  3248. "unlinking if it is still empty in %ds",
  3249. ams_id,
  3250. tray_id_raw,
  3251. linked_spool,
  3252. int(slot_unlink_grace.GRACE_SECONDS),
  3253. )
  3254. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  3255. continue
  3256. spool_tag = (
  3257. tray.tray_uuid
  3258. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  3259. else tray.tag_uid
  3260. )
  3261. # Provide the hint only when no RFID is available
  3262. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  3263. try:
  3264. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  3265. result = await client.sync_ams_tray(
  3266. tray,
  3267. printer_name,
  3268. db,
  3269. # Per-print tracking is the only weight writer (#1119).
  3270. # AMS auto-sync still maintains spool metadata / slot
  3271. # assignments but no longer touches remaining_weight.
  3272. disable_weight_sync=True,
  3273. cached_spools=cached_spools,
  3274. inventory_remaining=inv_remaining,
  3275. spoolman_spool_id_hint=hint,
  3276. auto_add_unknown_rfid=auto_add_unknown_rfid,
  3277. )
  3278. if result is None and spool_tag and not auto_add_unknown_rfid:
  3279. # Spoolman skipped auto-create per user setting — surface
  3280. # the slot so the UI can offer "+ Add to inventory".
  3281. await _broadcast_unknown_tag(
  3282. printer_id=printer_id,
  3283. ams_id=ams_id,
  3284. tray_id=tray.tray_id,
  3285. tag_uid=tray.tag_uid or "",
  3286. tray_uuid=tray.tray_uuid or "",
  3287. tray_type=tray.tray_type,
  3288. tray_color=tray.tray_color,
  3289. tray_sub_brands=tray.tray_sub_brands,
  3290. tray_count=len(trays),
  3291. )
  3292. elif result:
  3293. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  3294. if result:
  3295. synced += 1
  3296. if result.get("id"):
  3297. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  3298. # If a new spool was created, add it to the cache
  3299. # so subsequent trays can find it if they reference the same tag
  3300. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  3301. if not spool_exists:
  3302. cached_spools.append(result)
  3303. logger.debug(
  3304. "[Printer %s] Added newly created spool %s to cache",
  3305. printer_id,
  3306. result["id"],
  3307. )
  3308. # Reconcile slot_preset_mappings (the same row internal
  3309. # mode keeps in sync via inventory + spool_tag_matcher).
  3310. # Without this the slot card surfaces the previous spool's
  3311. # preset name — same bug shape, different inventory mode.
  3312. from backend.app.services.slot_preset_writer import (
  3313. upsert_slot_preset_for_spoolman_spool,
  3314. )
  3315. await upsert_slot_preset_for_spoolman_spool(
  3316. db=db,
  3317. spoolman_spool=result,
  3318. tray_info_idx=tray.tray_info_idx or "",
  3319. tray_sub_brands=tray.tray_sub_brands or "",
  3320. tray_type=tray.tray_type or "",
  3321. printer_id=printer_id,
  3322. ams_id=ams_id,
  3323. tray_id=tray.tray_id,
  3324. )
  3325. except Exception as e:
  3326. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3327. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3328. if synced > 0:
  3329. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3330. # Persist slot assignment changes to the local table: only slots
  3331. # whose spool this pass changed, and only while they still hold what
  3332. # it read before awaiting Spoolman, so a spool assigned by hand in
  3333. # between stays (SSA-3). The changed slots are announced: the slot
  3334. # card reads slot_preset_mappings (rewritten above) ahead of the live
  3335. # tray, so with no event it kept the previous spool's preset name.
  3336. if slot_changes or empty_slots:
  3337. from backend.app.services.spoolman_slot_sync import write_slot_results
  3338. try:
  3339. await write_slot_results(
  3340. db,
  3341. {(printer_id, a_id, t_id): spool_id for (a_id, t_id), spool_id in spoolman_slot_map.items()}
  3342. if slot_map_read
  3343. else None,
  3344. [(printer_id, a_id, t_id, spool_id) for a_id, t_id, spool_id in slot_changes],
  3345. [(printer_id, a_id, t_id) for a_id, t_id in empty_slots],
  3346. )
  3347. except Exception as e:
  3348. await db.rollback()
  3349. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3350. except Exception as e:
  3351. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3352. # Largest finish photo attached to a notification; a bigger one is still linked.
  3353. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3354. async def _finish_photo_for_notification(
  3355. db, archive, archive_id: int, filename: str
  3356. ) -> tuple[str | None, bytes | None]:
  3357. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3358. With authentication off the link is the archive's own photo route, as it
  3359. always was: it opens without a login and doesn't expire. With
  3360. authentication on that route needs a media token, which nothing tapping a
  3361. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3362. link only ever answered 401. The photo is then saved as a notification
  3363. photo as well (utils/notification_photos.py) and the link points there: an
  3364. unguessable name that opens this one photo and nothing else, for 3 days.
  3365. The link is relative when no External URL is set. Bytes over
  3366. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3367. ``(None, None)`` when the photo can't be found.
  3368. """
  3369. from backend.app.api.routes.settings import get_setting
  3370. from backend.app.core.auth import is_auth_enabled
  3371. from backend.app.utils.archive_paths import find_archive_photo
  3372. from backend.app.utils.notification_photos import save_notification_photo
  3373. log = logging.getLogger(__name__)
  3374. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3375. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3376. photo_bytes: bytes | None = None
  3377. try:
  3378. photo_path = find_archive_photo(archive, filename)
  3379. if photo_path is not None:
  3380. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3381. except Exception as e:
  3382. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3383. try:
  3384. auth_on = await is_auth_enabled(db)
  3385. except Exception:
  3386. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3387. if auth_on:
  3388. url = None
  3389. if photo_bytes:
  3390. try:
  3391. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3392. url = f"{base}/api/v1/notifications/photos/{name}"
  3393. except Exception as e:
  3394. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3395. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3396. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3397. return url, None
  3398. if photo_bytes:
  3399. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3400. return url, photo_bytes
  3401. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3402. """Capture a camera snapshot for notification image attachment.
  3403. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3404. Uses: external camera > buffered frame > fresh capture.
  3405. Turns the chamber light on for the picture when the printer asks for it
  3406. (#1655). ``light=False`` is for callers that capture all through a print,
  3407. where the light would flash with every frame.
  3408. """
  3409. if not printer:
  3410. return None
  3411. async with camera_light(printer if light else None):
  3412. return await _capture_snapshot_frame(printer_id, printer, logger)
  3413. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3414. """The capture behind ``_capture_snapshot_for_notification``."""
  3415. try:
  3416. from backend.app.api.routes.settings import get_setting
  3417. async with async_session() as db:
  3418. capture_enabled = await get_setting(db, "capture_finish_photo")
  3419. if capture_enabled is not None and capture_enabled.lower() != "true":
  3420. return None
  3421. # Try external camera first
  3422. if printer.external_camera_enabled and printer.external_camera_url:
  3423. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3424. from backend.app.api.routes.camera import live_frame_for_capture
  3425. from backend.app.services.external_camera import capture_frame
  3426. # An external camera allows one reader, so capturing while a viewer
  3427. # is attached fails (#2707). A None here falls through to the paths
  3428. # below exactly as a failed capture did.
  3429. defer, buffered = live_frame_for_capture(printer_id)
  3430. if defer:
  3431. frame_data = buffered
  3432. else:
  3433. frame_data = await capture_frame(
  3434. printer.external_camera_url,
  3435. printer.external_camera_type or "mjpeg",
  3436. snapshot_url=printer.external_camera_snapshot_url,
  3437. )
  3438. if frame_data and len(frame_data) <= 2_500_000:
  3439. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3440. return _apply_camera_rotation(frame_data, printer, logger)
  3441. # Try buffered frame from active stream
  3442. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3443. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3444. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3445. buffered_frame = get_buffered_frame(printer_id)
  3446. if (active_for_printer or active_chamber) and buffered_frame:
  3447. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3448. if len(buffered_frame) <= 2_500_000:
  3449. return _apply_camera_rotation(buffered_frame, printer, logger)
  3450. # Fresh capture from printer camera
  3451. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3452. from backend.app.services.camera import capture_camera_frame_bytes
  3453. frame_data = await capture_camera_frame_bytes(
  3454. printer.ip_address, printer.access_code, printer.model, timeout=15
  3455. )
  3456. if frame_data and len(frame_data) <= 2_500_000:
  3457. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3458. return _apply_camera_rotation(frame_data, printer, logger)
  3459. except Exception as e:
  3460. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3461. return None
  3462. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3463. """#1867: bank a recent in-print camera frame for the finish photo.
  3464. Called on every layer change and (#2547) on every print-progress advance.
  3465. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3466. path has a pre-End-G-code image for prints that end with a plate swap.
  3467. Both drivers are print telemetry that stops the instant printing ends: no
  3468. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3469. plate swap) executes. So the last banked frame is always the finished print,
  3470. never the swapped plate — that property is what the #1867 path relies on and
  3471. it must survive any change to the throttle below.
  3472. Layer changes alone were not enough: they stop when the *final* layer
  3473. begins, which on a three-minute last layer left the bank stale by the whole
  3474. length of that layer (#2547). Progress keeps ticking through it.
  3475. Best-effort: any failure just leaves the previous banked frame.
  3476. """
  3477. logger = logging.getLogger(__name__)
  3478. client = printer_manager.get_client(printer_id)
  3479. state = client.state if client else None
  3480. if not state or state.state != "RUNNING":
  3481. return
  3482. # Only during actual extrusion — firmware ticks layer_num during the
  3483. # pre-print calibration sequence, whose sub-stages are non-zero.
  3484. if state.mc_print_sub_stage not in (None, 0):
  3485. return
  3486. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3487. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3488. # now that progress advances also drive banking, that exemption would fire a
  3489. # camera grab on every percent tick of the last layer. Bambu printers accept
  3490. # one RTSP client at a time, so each grab contends with the live view.
  3491. now = time.monotonic()
  3492. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3493. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3494. return
  3495. total = state.total_layers or 0
  3496. try:
  3497. async with async_session() as db:
  3498. from backend.app.models.printer import Printer
  3499. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3500. printer = result.scalar_one_or_none()
  3501. if not printer:
  3502. return
  3503. # Reuses the notification snapshot path, which honours the
  3504. # `capture_finish_photo` setting (returns None when disabled) so we
  3505. # don't bank frames the user never asked for. Without the chamber light
  3506. # (#1655): this runs every 25 seconds for the whole print.
  3507. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3508. if frame:
  3509. _inprint_frame_bank[printer_id] = frame
  3510. _inprint_frame_bank_ts[printer_id] = now
  3511. logger.debug(
  3512. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3513. printer_id,
  3514. layer_num,
  3515. total,
  3516. len(frame),
  3517. )
  3518. except Exception as e:
  3519. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3520. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3521. """Apply camera rotation to snapshot image if configured."""
  3522. from backend.app.services.camera import apply_camera_rotation
  3523. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3524. async def _send_print_start_notification(
  3525. printer_id: int,
  3526. data: dict,
  3527. archive_data: dict | None = None,
  3528. logger=None,
  3529. ):
  3530. """Helper to send print start notification with optional archive data."""
  3531. if logger is None:
  3532. logger = logging.getLogger(__name__)
  3533. try:
  3534. async with async_session() as db:
  3535. from backend.app.models.printer import Printer
  3536. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3537. printer = result.scalar_one_or_none()
  3538. printer_name = printer.name if printer else f"Printer {printer_id}"
  3539. # Capture camera snapshot for notification image attachment
  3540. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3541. if image_data:
  3542. if archive_data is None:
  3543. archive_data = {}
  3544. archive_data["image_data"] = image_data
  3545. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3546. # Send user-specific email notification for print start
  3547. if archive_data and archive_data.get("created_by_id"):
  3548. await notification_service.send_user_print_email(
  3549. event_type="user_print_start",
  3550. created_by_id=archive_data["created_by_id"],
  3551. printer_name=printer_name,
  3552. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3553. db=db,
  3554. )
  3555. except Exception as e:
  3556. logger.warning("Notification on_print_start failed: %s", e)
  3557. async def _dispatch_user_print_email(
  3558. status: str,
  3559. created_by_id: int | None,
  3560. printer_name: str,
  3561. filename: str,
  3562. db,
  3563. image_data: bytes | None = None,
  3564. finish_photo_url: str | None = None,
  3565. ) -> None:
  3566. """Send a user-specific print-completion email based on print status.
  3567. Maps the normalised print status to the correct event type and delegates
  3568. to :meth:`NotificationService.send_user_print_email`. A single helper
  3569. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3570. "stopped"`` dispatch block at every call site.
  3571. Does nothing if *created_by_id* is ``None``.
  3572. """
  3573. if created_by_id is None:
  3574. return
  3575. if status == "completed":
  3576. event_type = "user_print_complete"
  3577. elif status == "failed":
  3578. event_type = "user_print_failed"
  3579. elif status in ("stopped", "aborted", "cancelled"):
  3580. event_type = "user_print_stopped"
  3581. else:
  3582. return
  3583. await notification_service.send_user_print_email(
  3584. event_type=event_type,
  3585. created_by_id=created_by_id,
  3586. printer_name=printer_name,
  3587. filename=filename,
  3588. db=db,
  3589. image_data=image_data,
  3590. finish_photo_url=finish_photo_url,
  3591. )
  3592. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3593. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3594. try:
  3595. from backend.app.services.archive import extract_printable_objects_from_archive
  3596. client = printer_manager.get_client(printer_id)
  3597. if not client:
  3598. return
  3599. # Extract with positions for UI overlay, scoped to the plate that
  3600. # is printing — resolve_plate_id is the same resolver /cover uses,
  3601. # so the object list can't disagree with the thumbnail it is drawn
  3602. # over (#2522).
  3603. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3604. app_settings.base_dir / archive.file_path,
  3605. plate_number=resolve_plate_id(client.state),
  3606. )
  3607. if printable_objects:
  3608. client.state.printable_objects = printable_objects
  3609. client.state.printable_objects_bbox_all = bbox_all
  3610. client.state.skipped_objects = []
  3611. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3612. except Exception as e:
  3613. logger.debug("Failed to extract printable objects from archive: %s", e)
  3614. def _load_pauses_from_3mf(threemf_path, printer_id: int, *, warned_layers=(), passed_through_layer: int = 0) -> None:
  3615. """Read the running print's slicer pauses from its 3MF, in the background (#2984).
  3616. In a thread: a plate's G-code runs to tens of MB, and the print-start
  3617. handler must not wait for it. Kept only while the printer is still on
  3618. the print they were read for: a new print replaces the list.
  3619. ``warned_layers``: pauses this print was already warned about, kept on its
  3620. archive, so a restart does not send the heads-up again.
  3621. ``passed_through_layer``: for a print resumed after a restart, the layer it
  3622. is on. Its pauses up to there are behind it, though the printer's layer
  3623. reads 0 until it reports the next one.
  3624. """
  3625. client = printer_manager.get_client(printer_id)
  3626. if not client:
  3627. return
  3628. state = client.state
  3629. read_for = state.pause_points
  3630. try:
  3631. plate_id = resolve_plate_id(state)
  3632. except Exception:
  3633. # Never at the cost of the print-start handler this runs inside.
  3634. logging.getLogger(__name__).warning("[Printer %s] Could not tell the plate to read pauses for", printer_id)
  3635. return
  3636. async def _load() -> None:
  3637. from backend.app.utils.threemf_tools import extract_pause_points_from_3mf
  3638. points = await asyncio.to_thread(extract_pause_points_from_3mf, Path(threemf_path), plate_id)
  3639. if state.pause_points is not read_for:
  3640. return
  3641. state.pause_points = [p for p in points if p.layer > passed_through_layer]
  3642. state.pause_warned_layers = set(state.pause_warned_layers) | set(warned_layers)
  3643. if points:
  3644. logging.getLogger(__name__).info(
  3645. "Loaded %s slicer pause(s) for printer %s at layer(s) %s",
  3646. len(points),
  3647. printer_id,
  3648. [p.layer for p in points],
  3649. )
  3650. spawn_background_task(_load(), name=f"load-pauses-{printer_id}")
  3651. def _load_pauses_from_resumed_archive(archive, printer_id: int) -> None:
  3652. """Pauses for a print start taken as the resumption of a running print.
  3653. A restart while the print was paused makes its resume look like a new
  3654. print (#2984): the pauses warned about and passed are kept from before.
  3655. """
  3656. client = printer_manager.get_client(printer_id)
  3657. state = client.state if client else None
  3658. _load_pauses_from_3mf(
  3659. app_settings.base_dir / archive.file_path,
  3660. printer_id,
  3661. warned_layers=pause_eta.warned_layers_of(archive, state) if state is not None else (),
  3662. passed_through_layer=getattr(client, "layer_before_new_print", 0) if client else 0,
  3663. )
  3664. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3665. """Put the skip-objects list back after a restart mid-print.
  3666. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3667. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3668. which the #1304 guard suppresses on the first RUNNING push after startup.
  3669. Everything else this hook restores (the archive, the usage-tracking session,
  3670. the timelapse baseline) was already handled; the object list was not, so a
  3671. restart mid-print took skip-objects away for the rest of that print.
  3672. Nothing recovered it either: the printer card gates its Skip button on the
  3673. object count, and the one endpoint that can rebuild the list is reachable
  3674. only from the modal that button opens.
  3675. The archive is the running print's as ``running_print_archive`` finds it:
  3676. by subtask_id, or for a print that reports none by the archive bound to it
  3677. (#3327), never by name: a leftover ``status="printing"`` row from a
  3678. completion we never saw must not hand this print someone else's objects.
  3679. After a restart that binding exists only for Bambuddy's own prints, so a
  3680. print that reports no subtask_id loads nothing rather than a guess; the
  3681. reload path on ``GET /print/objects`` covers that case on demand.
  3682. """
  3683. client = printer_manager.get_client(printer_id)
  3684. if client is None or (client.state.printable_objects and client.state.pause_points):
  3685. return
  3686. archive = await running_print_archive(db, printer_id, state, printing_only=True, by_name=False)
  3687. if archive is not None and archive.file_path:
  3688. if not client.state.printable_objects:
  3689. _load_objects_from_archive(archive, printer_id, logger)
  3690. # The slicer's pauses are in-memory only as well (#2984).
  3691. if not client.state.pause_points:
  3692. _load_pauses_from_3mf(
  3693. app_settings.base_dir / archive.file_path,
  3694. printer_id,
  3695. warned_layers=pause_eta.warned_layers_of(archive, state),
  3696. )
  3697. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3698. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3699. # past it; the second covers a handshake that failed again on the way back and
  3700. # armed a fresh one. Module-level so tests can shrink them.
  3701. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3702. # Retry ladder for the other temporary give-up: the file service answered and
  3703. # the transfer still did not finish, which at print start is usually the printer
  3704. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3705. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3706. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3707. # two cover a printer that stays busy well into the print.
  3708. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3709. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3710. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3711. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3712. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3713. # by view, so two views race), the cool-off retry task, and print completion.
  3714. # Without this they each read file_path == "" and each run a full copy, so the row
  3715. # ends up pointing at one timestamped directory while the others sit orphaned.
  3716. #
  3717. # Keyed by printer rather than archive because a printer runs one print at a time,
  3718. # which makes the two equally strong here — and it bounds the dict by printer
  3719. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3720. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3721. # resuming, so "no waiters" is not a question this API can answer.
  3722. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3723. # How many of a printer's newest archives a touchscreen reprint is compared
  3724. # against (#3307). A repeat is usually of a recent job; the bound keeps a
  3725. # print start from reading a long history's extra_data.
  3726. _REPEAT_LOOKBACK = 200
  3727. async def _archived_3mf_for_repeat(
  3728. db, printer_id: int, subtask_name: str | None, gcode_file: str | None, total_layers: int | None
  3729. ):
  3730. """The newest archive of the job this printer is running again, with its 3MF.
  3731. A "Print again" on the printer's screen never names the file on the card:
  3732. it reports its own history copy under a generic name
  3733. (``file:///userdata/project_file.gcode.3mf``), the 3MF's internal title as
  3734. ``subtask_name`` and the plate as ``gcode_file`` -- and the title is often
  3735. not the card file's name, so every lookup built from it misses (#3307).
  3736. An earlier run that was archived recorded that same title and plate in its
  3737. ``_print_data``, and holds the 3MF.
  3738. Same printer, same title, same plate, a 3MF still on disk. A layer count
  3739. known on both sides must agree: the same title and plate re-sliced is
  3740. another job. None when nothing matches.
  3741. """
  3742. from backend.app.models.archive import PrintArchive
  3743. if not subtask_name or not gcode_file:
  3744. return None
  3745. rows = (
  3746. (
  3747. await db.execute(
  3748. select(PrintArchive)
  3749. .where(
  3750. PrintArchive.printer_id == printer_id,
  3751. PrintArchive.deleted_at.is_(None),
  3752. PrintArchive.file_path.isnot(None),
  3753. PrintArchive.file_path != "",
  3754. )
  3755. .order_by(PrintArchive.created_at.desc(), PrintArchive.id.desc())
  3756. .limit(_REPEAT_LOOKBACK)
  3757. )
  3758. )
  3759. .scalars()
  3760. .all()
  3761. )
  3762. for archive in rows:
  3763. extra = archive.extra_data if isinstance(archive.extra_data, dict) else {}
  3764. run = extra.get("_print_data")
  3765. if not isinstance(run, dict):
  3766. continue
  3767. if run.get("subtask_name") != subtask_name or run.get("filename") != gcode_file:
  3768. continue
  3769. if total_layers and archive.total_layers and archive.total_layers != total_layers:
  3770. continue
  3771. if not (app_settings.base_dir / archive.file_path).is_file():
  3772. continue
  3773. return archive
  3774. return None
  3775. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True) -> bool:
  3776. """Fill in a no-3MF archive from a 3MF that turned up later.
  3777. Returns True when the row was upgraded. Safe to call speculatively: it
  3778. verifies the archive still exists, is still a fallback, and that the file
  3779. is a readable 3MF before touching anything.
  3780. Serialised per printer — see ``_fallback_recovery_locks``.
  3781. """
  3782. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3783. async with lock:
  3784. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id, price=price)
  3785. async def _recover_fallback_archive_locked(
  3786. archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True
  3787. ) -> bool:
  3788. """The body of :func:`_recover_fallback_archive`, under its per-printer lock.
  3789. ``price`` is False when the print's end is being handled: the archive
  3790. still reads "printing" then, and its end prices it.
  3791. """
  3792. import zipfile
  3793. from backend.app.models.archive import PrintArchive
  3794. from backend.app.services.archive import ArchiveService
  3795. logger = logging.getLogger(__name__)
  3796. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3797. return False
  3798. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3799. # A truncated or half-written download is worse than no download: it
  3800. # would replace an honest empty archive with wrong metadata.
  3801. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3802. return False
  3803. async with async_session() as db:
  3804. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3805. if archive is None or archive.deleted_at is not None:
  3806. return False
  3807. if archive.file_path:
  3808. # Already recovered, or never was a fallback. Either way there is a
  3809. # real 3MF attached and overwriting it is not this function's job.
  3810. return False
  3811. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3812. service = ArchiveService(db)
  3813. recovered = await service.archive_print(
  3814. printer_id=printer_id,
  3815. source_file=source_3mf,
  3816. print_data={**print_data, "status": archive.status or "printing"},
  3817. subtask_id=archive.subtask_id,
  3818. update_archive_id=archive.id,
  3819. )
  3820. if recovered is None:
  3821. return False
  3822. logger.info(
  3823. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3824. archive_id,
  3825. source_3mf,
  3826. recovered.file_size,
  3827. )
  3828. # Spoolman's tracking stored no 3MF usage at print start and would
  3829. # charge the AMS remain% change; the built-in tracker reads the archive
  3830. # at completion and needs nothing. Also at the print's end (``price``
  3831. # False): that recovery runs inside the close-out, before the charge.
  3832. try:
  3833. from backend.app.services.spoolman_tracking import attach_recovered_3mf
  3834. from backend.app.services.usage_tracker import is_completing
  3835. await attach_recovered_3mf(
  3836. printer_id,
  3837. recovered.id,
  3838. recovered.file_path,
  3839. db,
  3840. printer_manager,
  3841. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3842. may_start=not price or (recovered.status == "printing" and not is_completing(printer_id)),
  3843. )
  3844. except Exception:
  3845. logger.warning(
  3846. "[RECOVER] Archive %s: could not add the 3MF to Spoolman's usage tracking", archive_id, exc_info=True
  3847. )
  3848. if price and recovered.status == "printing" and recovered.file_path:
  3849. # Print start had no 3MF to read the slicer's pauses from (#2984).
  3850. _load_pauses_from_3mf(app_settings.base_dir / recovered.file_path, printer_id)
  3851. if price and recovered.status == "printing":
  3852. # Print start priced it from the default rate, having no 3MF to
  3853. # estimate from; now it has one. An ended print is left alone: its
  3854. # end prices it. A print Bambuddy didn't dispatch has no start
  3855. # plate; the one the archive just read from the 3MF stands in.
  3856. _schedule_archive_cost_estimate(
  3857. printer_id,
  3858. recovered.id,
  3859. printer_manager,
  3860. ams_mapping=_get_start_ams_mapping(print_data, printer_id, recovered.id),
  3861. plate_id=_get_start_plate_id(printer_id, recovered.id) or recovered.plate_id,
  3862. session_factory=async_session,
  3863. )
  3864. # `archive_updated`, not `archive_created` — the row was already on the
  3865. # Archives page as an empty card and is now filled in, not new.
  3866. await ws_manager.send_archive_updated(
  3867. {
  3868. "id": recovered.id,
  3869. "printer_id": recovered.printer_id,
  3870. "filename": recovered.filename,
  3871. "print_name": recovered.print_name,
  3872. "status": recovered.status,
  3873. }
  3874. )
  3875. return True
  3876. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path, *, price: bool = True) -> bool:
  3877. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3878. Called from the paths that pull a 3MF for a print that is already under way
  3879. — chiefly the cover endpoint, which downloads the very file the archive flow
  3880. could not get and, before #2957, used it for a thumbnail and nothing else.
  3881. The bytes are already local, so this costs a parse and a row update.
  3882. No-op when the running print has a real archive, which is the common case.
  3883. """
  3884. from backend.app.models.archive import PrintArchive
  3885. logger = logging.getLogger(__name__)
  3886. # `_active_prints` is keyed on the raw names seen at print start — the
  3887. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3888. # Callers here arrive with whichever variant their own path produced, so
  3889. # match on the same normalization the download cache uses rather than on an
  3890. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3891. # endpoint find an archive registered under "Desktop_Goose".
  3892. wanted = normalize_3mf_name(name)
  3893. archive_id = None
  3894. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3895. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3896. archive_id = value
  3897. break
  3898. if archive_id is None:
  3899. return False
  3900. async with async_session() as db:
  3901. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3902. # Cheap pre-check so the common case (a normal archive) does no work.
  3903. if archive is None or archive.file_path or archive.deleted_at is not None:
  3904. return False
  3905. try:
  3906. return await _recover_fallback_archive(archive_id, path, printer_id, price=price)
  3907. except Exception as e:
  3908. # Recovery is opportunistic. A failure here must never take down the
  3909. # caller, which is usually just trying to render a thumbnail.
  3910. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3911. return False
  3912. def _schedule_fallback_3mf_retry(
  3913. printer_id: int,
  3914. archive_id: int,
  3915. filenames: list[str],
  3916. delays: tuple[float, ...] | None = None,
  3917. reason: str = REASON_FTPS_COOLOFF,
  3918. ) -> None:
  3919. """Re-attempt the 3MF download after a temporary give-up.
  3920. ``reason`` says which give-up this is, and picks the default ladder: an
  3921. FTPS cool-off has to be waited out, while a transfer that timed out under
  3922. contention is worth asking about again straight away (#3063). It is only
  3923. read for the ladder and the log line -- the retry itself is identical, since
  3924. in both cases the file is on the printer and the last attempt at it failed
  3925. for a reason that does not last.
  3926. """
  3927. logger = logging.getLogger(__name__)
  3928. if delays is None:
  3929. delays = (
  3930. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3931. if reason == REASON_FTP_TRANSFER_FAILED
  3932. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3933. )
  3934. async def _retry() -> None:
  3935. from backend.app.models.archive import PrintArchive
  3936. from backend.app.models.printer import Printer
  3937. for delay in delays:
  3938. await asyncio.sleep(delay)
  3939. async with async_session() as db:
  3940. archive = (
  3941. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3942. ).scalar_one_or_none()
  3943. if archive is None or archive.deleted_at is not None or archive.file_path:
  3944. return
  3945. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3946. if printer is None:
  3947. return
  3948. # Read the fields while the session is open rather than touching
  3949. # a detached instance minutes later, mid-download.
  3950. printer_ip = printer.ip_address
  3951. printer_code = printer.access_code
  3952. printer_model = printer.model
  3953. # Someone else may have fetched it in the meantime — the cover
  3954. # endpoint routinely does, and its copy is the same bytes.
  3955. for name in filenames:
  3956. cached = get_cached_3mf(printer_id, name)
  3957. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3958. return
  3959. if ftps_handshake_blocked(printer_ip):
  3960. logger.info(
  3961. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3962. printer_id,
  3963. archive_id,
  3964. )
  3965. continue
  3966. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3967. for candidate in filenames:
  3968. # Bare name only. These come from the print-start flow, which
  3969. # already strips the path, but the local temp write must not
  3970. # depend on that holding for every future caller — a name that
  3971. # is absolute or contains ".." would otherwise escape the data
  3972. # volume via the `/` operator.
  3973. name = Path(candidate).name
  3974. if not name or name in (".", ".."):
  3975. continue
  3976. if not name.endswith(".3mf"):
  3977. name = f"{name}.3mf"
  3978. temp_path = app_settings.archive_dir / "temp" / name
  3979. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3980. try:
  3981. hit = await download_file_try_paths_async(
  3982. printer_ip,
  3983. printer_code,
  3984. ftp_probe_paths(name),
  3985. temp_path,
  3986. socket_timeout=ftp_timeout,
  3987. printer_model=printer_model,
  3988. max_total_timeout=RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  3989. )
  3990. except Exception as e:
  3991. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3992. continue
  3993. if not hit:
  3994. continue
  3995. cache_3mf_download(printer_id, name, temp_path)
  3996. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3997. return
  3998. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3999. async def _guarded() -> None:
  4000. try:
  4001. await _retry()
  4002. except asyncio.CancelledError:
  4003. raise
  4004. except Exception as e:
  4005. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  4006. finally:
  4007. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  4008. _fallback_3mf_retry_tasks.pop(printer_id, None)
  4009. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  4010. if existing and not existing.done():
  4011. existing.cancel()
  4012. task = asyncio.create_task(_guarded())
  4013. _fallback_3mf_retry_tasks[printer_id] = task
  4014. logger.info(
  4015. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  4016. archive_id,
  4017. reason,
  4018. printer_id,
  4019. ", ".join(f"{d:g}s" for d in delays),
  4020. )
  4021. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  4022. """Whether an archive created here should ask for the print's outcome (#1898).
  4023. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  4024. branches below: a queued job already has its archive and takes the
  4025. expected-print branch, where the queue item's own ``confirm_outcome``
  4026. decides. The queue is still consulted, because a restart mid-print empties
  4027. ``_expected_prints`` — without the check the setting could override a queue
  4028. item that deliberately has the flag off. Any failure answers "don't ask":
  4029. an unwanted prompt is worse than a missing one, and this must never be the
  4030. reason a print goes unarchived.
  4031. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  4032. leaves one behind when a completion cannot be matched to it
  4033. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  4034. only takes it back once the printer has sat connected and terminal for
  4035. minutes. Until then every screen-started print on that printer would
  4036. silently lose its prompt, so the row is held against ``observed_name`` by
  4037. the same comparison a completion uses: a positive disagreement means the row
  4038. is about some other run and this print is external after all.
  4039. """
  4040. logger = logging.getLogger(__name__)
  4041. try:
  4042. # A savepoint rather than a rollback of the caller's transaction on
  4043. # failure: a failed statement leaves the transaction unusable, but a
  4044. # full rollback also expires every object the caller has loaded (the
  4045. # printer, the archive it just created), and on an async session the
  4046. # next attribute read then raises instead of reloading. Everything here
  4047. # is a read, so undoing the savepoint loses nothing.
  4048. async with db.begin_nested():
  4049. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  4050. except Exception as e:
  4051. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  4052. return False
  4053. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  4054. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  4055. from backend.app.api.routes.settings import get_setting, setting_is_true
  4056. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  4057. return False
  4058. from backend.app.models.print_queue import PrintQueueItem
  4059. dispatched_here = await db.scalar(
  4060. select(PrintQueueItem)
  4061. .where(
  4062. PrintQueueItem.printer_id == printer_id,
  4063. PrintQueueItem.status == "printing",
  4064. )
  4065. .limit(1)
  4066. )
  4067. if dispatched_here is None:
  4068. return True
  4069. expected = await _queue_item_dispatched_name(db, dispatched_here)
  4070. observed = (observed_name or "").strip()
  4071. if not expected or not observed or _subtask_names_match(expected, observed):
  4072. logger.info(
  4073. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  4074. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  4075. printer_id,
  4076. dispatched_here.id,
  4077. )
  4078. return False
  4079. logger.info(
  4080. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  4081. "%r; treating this as an externally started print.",
  4082. dispatched_here.id,
  4083. printer_id,
  4084. expected,
  4085. observed,
  4086. )
  4087. return True
  4088. async def _dispatch_outcome_confirmation_safely(
  4089. db,
  4090. printer_id: int,
  4091. printer_name: str,
  4092. data: dict,
  4093. archive_id: int,
  4094. archive_data: dict | None = None,
  4095. run_id: int | None = None,
  4096. ) -> None:
  4097. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  4098. The completion task sends the per-user print email on the same session
  4099. right after the prompt. A failed statement in the prompt leaves that
  4100. session needing a rollback, and without one the email step fails with
  4101. PendingRollbackError; the prompt is the optional part, so it must not be
  4102. the reason the email never goes out.
  4103. """
  4104. try:
  4105. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data, run_id=run_id)
  4106. except Exception as e:
  4107. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  4108. try:
  4109. await db.rollback()
  4110. except Exception:
  4111. pass
  4112. async def _outcome_answerers(db, owner_id: int | None) -> set[int] | None:
  4113. """Who may answer a print's outcome prompt in the app: its owner and anyone
  4114. who may change everyone's archives. None (everyone on the printer) with auth
  4115. off, or for a print nobody owns."""
  4116. from sqlalchemy.orm import selectinload
  4117. from backend.app.core.auth import is_auth_enabled
  4118. from backend.app.core.permissions import Permission
  4119. from backend.app.models.user import User
  4120. if owner_id is None or not await is_auth_enabled(db):
  4121. return None
  4122. users = (await db.execute(select(User).options(selectinload(User.groups)).where(User.is_active))).scalars().all()
  4123. return {owner_id} | {u.id for u in users if u.has_permission(Permission.ARCHIVES_UPDATE_ALL.value)}
  4124. async def dispatch_outcome_confirmation(
  4125. db,
  4126. printer_id: int,
  4127. printer_name: str,
  4128. data: dict,
  4129. archive_id: int,
  4130. archive_data: dict | None = None,
  4131. *,
  4132. run_id: int | None = None,
  4133. ) -> bool:
  4134. """Emit the post-print outcome prompt for a completed print (#1898).
  4135. Gated on the run that ended (``run_id``): ``confirm_requested`` is the
  4136. opt-in (from the queue item, or from ``confirm_outcome_external_prints``
  4137. for a print Bambuddy did not start, copied onto the run at its start) and
  4138. ``user_verdict`` being unset is what makes the question still open. Mints
  4139. the run's capability token the one-tap verdict links carry: plates of one
  4140. archive each have their own question. Without a run, the archive's, as
  4141. before runs.
  4142. Lives here rather than inline in ``on_print_complete``'s notification task
  4143. because that task swallows every exception: extracted, the gate and the two
  4144. emissions can be driven by a test, which is the only thing standing between
  4145. a regression here and a farm that quietly stops asking.
  4146. Returns whether a prompt was sent.
  4147. """
  4148. logger = logging.getLogger(__name__)
  4149. from backend.app.models.archive import PrintArchive
  4150. from backend.app.models.print_log import PrintLogEntry
  4151. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  4152. if confirm_archive is None:
  4153. return False
  4154. run = await db.get(PrintLogEntry, run_id) if run_id is not None else None
  4155. if run is not None and run.archive_id != archive_id:
  4156. run = None
  4157. # The run carries the opt-in from its start; one logged before it did
  4158. # (None) asks as its archive does.
  4159. asks = confirm_archive if run is None or run.confirm_requested is None else run
  4160. holder = run if run is not None else confirm_archive
  4161. if not (asks.confirm_requested and holder.user_verdict is None):
  4162. return False
  4163. import secrets as _secrets
  4164. # A spent token stays on the row so the one-tap route can recognise it, so
  4165. # "has a token" no longer means "answerable". A prompt going out now needs a
  4166. # live one: mint a new token whenever the stored one is already spent, or
  4167. # every button in the new message would land on the already-answered page.
  4168. if not holder.confirm_token or holder.confirm_token_used_at is not None:
  4169. holder.confirm_token = _secrets.token_urlsafe(32)
  4170. holder.confirm_token_used_at = None
  4171. await db.commit()
  4172. from backend.app.api.routes.settings import get_external_base_url, get_setting
  4173. base = await get_external_base_url(db)
  4174. if not await get_setting(db, "external_url"):
  4175. # Both the Telegram inline keyboard and the ntfy action buttons need an
  4176. # absolute URL, so an unconfigured install used to get a message body
  4177. # with two unusable relative paths and no buttons at all. The shared
  4178. # fallback at least produces tappable links; say which setting makes
  4179. # them resolve from a phone.
  4180. logger.warning(
  4181. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  4182. "Set Settings → External URL so they resolve away from this host.",
  4183. base,
  4184. )
  4185. token = holder.confirm_token
  4186. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  4187. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  4188. confirm_url = f"{base}/archives?confirm={archive_id}" + (f"&run={run.id}" if run is not None else "")
  4189. await ws_manager.send_print_confirm_request(
  4190. printer_id,
  4191. {
  4192. "archive_id": archive_id,
  4193. "run_id": run.id if run is not None else None,
  4194. "print_name": confirm_archive.print_name or confirm_archive.filename,
  4195. },
  4196. user_ids=await _outcome_answerers(db, confirm_archive.created_by_id),
  4197. )
  4198. await notification_service.on_print_confirm_request(
  4199. printer_id,
  4200. printer_name,
  4201. data,
  4202. db,
  4203. archive_data=archive_data,
  4204. good_url=good_url,
  4205. reject_url=reject_url,
  4206. confirm_url=confirm_url,
  4207. archive_id=archive_id,
  4208. run_id=run.id if run is not None else None,
  4209. )
  4210. return True
  4211. async def _printer_gone(db, printer_id: int) -> bool:
  4212. """Whether the printer was deleted. A column read: the session's loaded
  4213. Printer would otherwise answer for the database."""
  4214. from backend.app.models.printer import Printer
  4215. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  4216. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  4217. """Remove the archive just written if its printer was deleted meanwhile.
  4218. The delete route sweeps the printer's archives before it commits, so a row
  4219. committed after that sweep (the check before writing passed while the
  4220. delete was still uncommitted) is left for a printer that will never report
  4221. the print's end. A row the sweep reached is the route's: deleted with the
  4222. printer's archives, or detached (printer_id NULL) when the user kept them,
  4223. and then left as it is. Either way nothing is registered for it. Run after
  4224. the archive's commit, before anything is registered for it.
  4225. """
  4226. from backend.app.models.archive import PrintArchive
  4227. if not await _printer_gone(db, printer_id):
  4228. return False
  4229. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  4230. if owner == printer_id:
  4231. logging.getLogger(__name__).info(
  4232. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  4233. )
  4234. await ArchiveService(db).delete_archive(archive_id)
  4235. await forget_printer(printer_id)
  4236. return True
  4237. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  4238. """After an IntegrityError on a print start's archive write: whether it was
  4239. the printer being deleted, forgotten then (the caller returns).
  4240. PostgreSQL: the delete route locks the printer from its archive sweep to its
  4241. commit, so an archive written or adopted for it meanwhile (one that sets
  4242. printer_id) waits and the printer's foreign key then refuses it. That is
  4243. the printer being deleted, not an error; anything else is re-raised by the
  4244. caller.
  4245. """
  4246. await db.rollback()
  4247. if not await _printer_gone(db, printer_id):
  4248. return False
  4249. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  4250. await forget_printer(printer_id)
  4251. return True
  4252. async def _forget_if_printer_gone(printer_id: int) -> None:
  4253. """At the end of a print start: the slow steps after the last check (smart
  4254. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  4255. printer's delete and its forget_printer, and then wrote state back.
  4256. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  4257. SQLite; PostgreSQL refuses it.)
  4258. Its own session: those steps can leave the handler's needing a rollback (a
  4259. write to the archive the delete removed). Never raises: it runs inside the
  4260. fallback branch's try, whose except reports the archive as failed.
  4261. """
  4262. try:
  4263. async with async_session() as db:
  4264. gone = await _printer_gone(db, printer_id)
  4265. if gone:
  4266. await forget_printer(printer_id)
  4267. except Exception:
  4268. logging.getLogger(__name__).warning(
  4269. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  4270. )
  4271. async def _announce_plate_check_failed(printer_id: int, printer_name: str, reason: str) -> None:
  4272. """Tell the UI a plate check could not run. It does not block the print,
  4273. but an unchecked plate is not an empty one."""
  4274. try:
  4275. await ws_manager.broadcast(
  4276. {"type": "plate_check_failed", "printer_id": printer_id, "printer_name": printer_name, "reason": reason}
  4277. )
  4278. except Exception as e:
  4279. logging.getLogger(__name__).warning("[PLATE CHECK] Could not announce the failed check: %s", e)
  4280. def _expected_print_keys(printer_id: int, filename: str | None, subtask_name: str | None) -> list[tuple[int, str]]:
  4281. """The ``_expected_prints`` keys a print start may be registered under."""
  4282. keys: list[tuple[int, str]] = []
  4283. if subtask_name:
  4284. keys.append((printer_id, subtask_name))
  4285. keys.append((printer_id, f"{subtask_name}.3mf"))
  4286. keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  4287. if filename:
  4288. fname = filename.split("/")[-1] if "/" in filename else filename
  4289. keys.append((printer_id, fname))
  4290. # Strip extensions to match
  4291. base = fname.replace(".gcode", "").replace(".3mf", "")
  4292. keys.append((printer_id, base))
  4293. keys.append((printer_id, f"{base}.3mf"))
  4294. return keys
  4295. async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, subtask_name: str | None) -> bool:
  4296. """Whether this print start is one Bambuddy sent to the printer."""
  4297. if any(key in _expected_prints for key in _expected_print_keys(printer_id, filename, subtask_name)):
  4298. return True
  4299. from backend.app.models.archive import PrintArchive
  4300. from backend.app.models.print_queue import PrintQueueItem
  4301. # The queue row the scheduler sets to printing before it sends -- but only
  4302. # when it was sent as this print: a row left printing by a run whose end
  4303. # was missed names another file.
  4304. dispatched_names = (
  4305. await db.execute(
  4306. select(PrintArchive.filename)
  4307. .join(PrintQueueItem, PrintQueueItem.archive_id == PrintArchive.id)
  4308. .where(PrintQueueItem.printer_id == printer_id, PrintQueueItem.status == "printing")
  4309. )
  4310. ).scalars()
  4311. observed = [name for name in (subtask_name, (filename or "").rsplit("/", 1)[-1]) if name]
  4312. return any(
  4313. _subtask_names_match(_subtask_name_from_filename(dispatched), _subtask_name_from_filename(seen))
  4314. for dispatched in dispatched_names
  4315. if dispatched
  4316. for seen in observed
  4317. )
  4318. async def on_print_start(printer_id: int, data: dict):
  4319. """Handle print start - archive the 3MF file immediately."""
  4320. logger = logging.getLogger(__name__)
  4321. # The print's start, before the 3MF download that the archive waits for
  4322. # (#3327): a minute of it would otherwise be missing from the print time.
  4323. detected_at = datetime.now(timezone.utc)
  4324. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  4325. try:
  4326. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  4327. except Exception:
  4328. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  4329. # Clear any stale user-stopped flag from previous print cycles
  4330. _user_stopped_printers.discard(printer_id)
  4331. _kill_switch_stopped.discard(printer_id)
  4332. # A new print starts its milestones from zero (#3211). The status path only
  4333. # resets on progress below 5 while not printing, which a printer that goes
  4334. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  4335. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  4336. # or on resume from pause, so it cannot repeat a milestone mid-print.
  4337. _last_progress_milestone[printer_id] = 0
  4338. _kill_switch_notification_tasks.pop(printer_id, None)
  4339. # #1721: drop any leftover pre-captured finish frame from a prior print
  4340. # so a never-consumed cache entry can't bleed into the new print's photo.
  4341. _stage22_finish_frames.pop(printer_id, None)
  4342. # #1867: same for the in-print frame bank — a queued print must not reuse
  4343. # the previous job's banked frame.
  4344. _inprint_frame_bank.pop(printer_id, None)
  4345. _inprint_frame_bank_ts.pop(printer_id, None)
  4346. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  4347. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  4348. # print's flag instead of inheriting it.
  4349. print_dispatch_context.adopt(printer_id)
  4350. # Cancel any active bed cooldown waiter for this printer
  4351. if _bed_cool_waiters.pop(printer_id, None):
  4352. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  4353. # Clear cached cover images so the new print's thumbnail is fetched fresh
  4354. from backend.app.api.routes.printers import clear_cover_cache
  4355. clear_cover_cache(printer_id)
  4356. await ws_manager.send_print_start(printer_id, data)
  4357. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  4358. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  4359. # MQTT relay - publish print start
  4360. try:
  4361. printer_info = printer_manager.get_printer(printer_id)
  4362. if printer_info:
  4363. await mqtt_relay.on_print_start(
  4364. printer_id,
  4365. printer_info.name,
  4366. printer_info.serial_number,
  4367. data.get("filename", ""),
  4368. data.get("subtask_name", ""),
  4369. )
  4370. except Exception:
  4371. pass # Don't fail print start callback if MQTT fails
  4372. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  4373. # and mapping, and the seeded tray-change log.
  4374. #
  4375. # Unconditional, for both inventory backends. This only *captures* — the
  4376. # writing is still split, with the internal tracker skipped at completion
  4377. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  4378. # carries its plate-scoped 3MF figures and stored mapping, but not the
  4379. # tray-change log, and that log is the only record of which spool fed
  4380. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  4381. # it on one side only would leave Spoolman users with the mid-print
  4382. # restart bug this fixes for everyone else.
  4383. try:
  4384. async with async_session() as db:
  4385. from backend.app.api.routes.settings import get_setting
  4386. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  4387. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4388. await usage_on_print_start(
  4389. printer_id,
  4390. data,
  4391. printer_manager,
  4392. db=db,
  4393. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  4394. )
  4395. except Exception as e:
  4396. logger.warning("Usage tracker on_print_start failed: %s", e)
  4397. # Track if notification was sent (to avoid sending twice)
  4398. notification_sent = False
  4399. # Smart plug automation: turn on plug when print starts
  4400. try:
  4401. async with async_session() as db:
  4402. await smart_plug_manager.on_print_start(printer_id, db)
  4403. except Exception as e:
  4404. logger.warning("Smart plug on_print_start failed: %s", e)
  4405. async with async_session() as db:
  4406. from backend.app.models.printer import Printer
  4407. from backend.app.services.bambu_ftp import list_files_async
  4408. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4409. printer = result.scalar_one_or_none()
  4410. # Plate detection check - pause if objects detected on build plate
  4411. logger.info(
  4412. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  4413. )
  4414. if printer and printer.plate_detection_enabled:
  4415. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  4416. # Release the pooled DB connection before the plate-detection camera
  4417. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  4418. # printer SELECT has run so far — nothing to persist — so this commit
  4419. # is a data-noop that ends the read transaction and returns the
  4420. # connection to the pool during the I/O (issue #2572). expire_on_commit
  4421. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  4422. # archive lookups below re-acquire a fresh connection on next execute.
  4423. await db.commit()
  4424. try:
  4425. from backend.app.services.plate_detection import check_plate_empty
  4426. # Build ROI tuple from printer settings if available
  4427. roi = None
  4428. if all(
  4429. [
  4430. printer.plate_detection_roi_x is not None,
  4431. printer.plate_detection_roi_y is not None,
  4432. printer.plate_detection_roi_w is not None,
  4433. printer.plate_detection_roi_h is not None,
  4434. ]
  4435. ):
  4436. roi = (
  4437. printer.plate_detection_roi_x,
  4438. printer.plate_detection_roi_y,
  4439. printer.plate_detection_roi_w,
  4440. printer.plate_detection_roi_h,
  4441. )
  4442. # The light is held, not switched, so a live view opened
  4443. # meanwhile keeps it when the check lets go (SP-C11). Every
  4444. # printer, whatever the camera light mode: detection needs it.
  4445. plate_photo_data = None
  4446. objects_detected = False
  4447. check_failure: str | None = None
  4448. async with camera_light(printer, any_mode=True, settle=2.5):
  4449. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  4450. plate_result = await check_plate_empty(
  4451. printer_id=printer_id,
  4452. ip_address=printer.ip_address,
  4453. access_code=printer.access_code,
  4454. model=printer.model,
  4455. include_debug_image=False,
  4456. external_camera_url=printer.external_camera_url,
  4457. external_camera_type=printer.external_camera_type,
  4458. use_external=printer.external_camera_enabled,
  4459. roi=roi,
  4460. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  4461. )
  4462. # No reference to compare against is a check that did not
  4463. # run either: say so rather than call the plate empty.
  4464. check_failure = getattr(plate_result, "failure_reason", None) or (
  4465. "not_calibrated" if plate_result.needs_calibration else None
  4466. )
  4467. objects_detected = not check_failure and not plate_result.is_empty
  4468. if objects_detected:
  4469. # Objects detected - pause the print!
  4470. logger.warning(
  4471. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  4472. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  4473. )
  4474. pause_client = printer_manager.get_client(printer_id)
  4475. if pause_client:
  4476. pause_client.pause_print()
  4477. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  4478. # Snapshot while the light's still on — restoring it first
  4479. # would leave the notification with a dark photo.
  4480. try:
  4481. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  4482. except Exception as snap_err:
  4483. logger.warning(
  4484. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  4485. )
  4486. if objects_detected:
  4487. # Send notification about plate not empty
  4488. await ws_manager.broadcast(
  4489. {
  4490. "type": "plate_not_empty",
  4491. "printer_id": printer_id,
  4492. "printer_name": printer.name,
  4493. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  4494. }
  4495. )
  4496. # Also send push notification
  4497. try:
  4498. await notification_service.on_plate_not_empty(
  4499. printer_id=printer_id,
  4500. printer_name=printer.name,
  4501. db=db,
  4502. difference_percent=plate_result.difference_percent,
  4503. image_data=plate_photo_data,
  4504. )
  4505. except Exception as notif_err:
  4506. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4507. elif check_failure:
  4508. logger.warning(
  4509. "[PLATE CHECK] Plate check could not run for printer %s (%s): %s; proceeding with print",
  4510. printer_id,
  4511. check_failure,
  4512. plate_result.message,
  4513. )
  4514. await _announce_plate_check_failed(printer_id, printer.name, check_failure)
  4515. else:
  4516. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4517. except Exception as plate_err:
  4518. # Don't block print on plate detection errors
  4519. logger.warning(
  4520. "[PLATE CHECK] Plate check could not run for printer %s: %s; proceeding with print",
  4521. printer_id,
  4522. plate_err,
  4523. )
  4524. await _announce_plate_check_failed(printer_id, printer.name, "error")
  4525. if not printer:
  4526. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4527. if not notification_sent:
  4528. await _send_print_start_notification(printer_id, data, logger=logger)
  4529. return
  4530. # Skip the printer's own jobs — a calibration run is not a user's print.
  4531. # See is_internal_printer_job for what counts and why both fields are
  4532. # tested; the pressure-advance line reports as a subtask name with no
  4533. # /usr/ path, which the old prefix-only test here missed entirely.
  4534. #
  4535. # No notification either. The event describes the printer calibrating
  4536. # itself, so "Print started" is as wrong as the archive was, and the
  4537. # matching completion is suppressed in on_print_complete for the same
  4538. # reason. Checked before the auto-archive switches, whose "off" path
  4539. # still notifies.
  4540. # A /usr/ path is the printer's own file. A name alone is not proof: a
  4541. # print Bambuddy dispatched is never one, whatever it is called.
  4542. # Dispatched = an expected print, or, after a restart that lost those,
  4543. # a queue job printing on the printer.
  4544. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")) and (
  4545. (data.get("filename") or "").startswith("/usr/")
  4546. or not await _dispatched_by_bambuddy(db, printer_id, data.get("filename", ""), data.get("subtask_name", ""))
  4547. ):
  4548. logger.info(
  4549. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4550. data.get("filename", ""),
  4551. data.get("subtask_name", ""),
  4552. )
  4553. return
  4554. # The global switch is the master: off, no printer archives prints
  4555. # started outside Bambuddy; on, each printer's own switch decides.
  4556. from backend.app.api.routes.settings import get_setting
  4557. _global_auto_archive = await get_setting(db, "auto_archive")
  4558. archives_prints = printer.auto_archive and (
  4559. _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4560. )
  4561. if not archives_prints:
  4562. # auto-archive disabled — check if there's an expected print (dispatched
  4563. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4564. # If so, fall through to the expected-print handling below so the archive
  4565. # is tracked in _active_prints and usage tracking works at completion.
  4566. _fn = data.get("filename", "")
  4567. _sn = data.get("subtask_name", "")
  4568. _check_keys: list[tuple[int, str]] = []
  4569. if _sn:
  4570. _check_keys += [
  4571. (printer_id, _sn),
  4572. (printer_id, f"{_sn}.3mf"),
  4573. (printer_id, f"{_sn}.gcode.3mf"),
  4574. ]
  4575. if _fn:
  4576. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4577. _check_keys.append((printer_id, _base_fn))
  4578. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4579. _check_keys += [
  4580. (printer_id, _no_archive_base),
  4581. (printer_id, f"{_no_archive_base}.3mf"),
  4582. ]
  4583. _has_expected = any(k in _expected_prints for k in _check_keys)
  4584. if not _has_expected:
  4585. # No expected print — truly external print (started from slicer/touchscreen)
  4586. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4587. if not notification_sent:
  4588. _no_archive_creator: int | None = None
  4589. for _key in _check_keys:
  4590. _expected_prints.pop(_key, None)
  4591. _expected_print_registered_at.pop(_key, None)
  4592. popped_creator = _expected_print_creators.pop(_key, None)
  4593. if _no_archive_creator is None:
  4594. _no_archive_creator = popped_creator
  4595. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4596. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4597. return
  4598. else:
  4599. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4600. # Get the filename and subtask_name
  4601. filename = data.get("filename", "")
  4602. subtask_name = data.get("subtask_name", "")
  4603. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4604. # present, it lets us match an archive across a backend restart (#972):
  4605. # same id → same print → resume the existing row instead of cancelling
  4606. # it and recreating from scratch (which loses started_at). Treat "0"
  4607. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4608. raw_mqtt = data.get("raw_data") or {}
  4609. subtask_id = raw_mqtt.get("subtask_id")
  4610. if subtask_id is not None:
  4611. subtask_id = str(subtask_id).strip()
  4612. if subtask_id in ("", "0"):
  4613. subtask_id = None
  4614. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4615. if not filename and not subtask_name:
  4616. # Send notification without archive data (no filename)
  4617. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4618. if not notification_sent:
  4619. await _send_print_start_notification(printer_id, data, logger=logger)
  4620. return
  4621. # Check if this is an expected print from reprint/scheduled
  4622. expected_keys = _expected_print_keys(printer_id, filename, subtask_name)
  4623. expected_archive_id = None
  4624. # Who queued it, taken with the entries it was registered beside: left
  4625. # behind once those are gone (the archive deleted mid-dispatch, or the
  4626. # start notification already sent), the expiry never saw it, and an
  4627. # unrelated later print of that name was attributed to that user (EP-2).
  4628. fallback_creator = None
  4629. for key in expected_keys:
  4630. expected_archive_id = _expected_prints.pop(key, None)
  4631. _expected_print_registered_at.pop(key, None)
  4632. if expected_archive_id:
  4633. # Clean up other possible keys for this print
  4634. for other_key in expected_keys:
  4635. _expected_prints.pop(other_key, None)
  4636. _expected_print_registered_at.pop(other_key, None)
  4637. creator = _expected_print_creators.pop(other_key, None)
  4638. if fallback_creator is None:
  4639. fallback_creator = creator
  4640. break
  4641. if expected_archive_id:
  4642. # This is a reprint/scheduled print - use existing archive, don't create new one
  4643. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4644. # Bambuddy dispatched it: the kill switch's fast path keeps it as
  4645. # Bambuddy's once the expected entry is consumed here.
  4646. _owned_print_archive_ids.add(expected_archive_id)
  4647. from backend.app.models.archive import PrintArchive
  4648. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4649. archive = result.scalar_one_or_none()
  4650. # Deleted after this handler loaded it (the plate check waits
  4651. # seconds) but before the route forgot the expected print: the
  4652. # archive the route kept or deleted is left as the route left it.
  4653. if archive and await _printer_gone(db, printer_id):
  4654. logger.info(
  4655. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4656. )
  4657. await forget_printer(printer_id)
  4658. return
  4659. if archive:
  4660. # As it was before this adoption: put back if the printer turns
  4661. # out to have been deleted while it was adopted (below).
  4662. before_adoption = {
  4663. attr.columns[0].name: getattr(archive, attr.key)
  4664. for attr in sa_inspect(PrintArchive).column_attrs
  4665. if attr.key != "id"
  4666. }
  4667. # Update archive status to printing
  4668. archive.status = "printing"
  4669. archive.started_at = datetime.now(timezone.utc)
  4670. # The previous run's outcome is not this one's: a reprint that
  4671. # completes must not keep showing why the last one failed.
  4672. archive.failure_reason = None
  4673. archive.completed_at = None
  4674. # The previous run's answer is still on this row and the
  4675. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4676. # so without a reset the second run inherits the first run's
  4677. # verdict: no prompt at all, and a green "good" badge on a run
  4678. # nobody ever judged.
  4679. if archive.confirm_requested:
  4680. archive.user_verdict = None
  4681. archive.user_verdict_source = None
  4682. archive.user_verdict_at = None
  4683. archive.confirm_token = None
  4684. archive.confirm_token_used_at = None
  4685. # Reprint of an archive reuses the source row. Without resetting
  4686. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4687. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4688. # extracts the *original* print's last frame, which then ships in
  4689. # the completion notification (#1707). Clear the path so the
  4690. # scanner runs fresh; also unlink the old video file so reprints
  4691. # don't accumulate orphans in the archive directory. Photos list
  4692. # is left alone — accumulating one finish photo per run is fine.
  4693. # The print-start baseline (#2704) is stale for the same reason:
  4694. # it describes the printer before the previous run. The capture
  4695. # below overwrites it, but clear it here too so an early failure
  4696. # can't leave the scan diffing against the wrong snapshot.
  4697. #
  4698. # Unlinked only when it is the same plate printing again. Every
  4699. # plate of a Send All shares this archive, and the video on it
  4700. # can be the only copy of another plate's run -- the printer's
  4701. # was deleted once it attached (#3275). That one is left in the
  4702. # archive directory, which goes with the archive. A video whose
  4703. # plate is not on record (attached by hand, or before the
  4704. # column existed) is kept too where the 3MF has other plates,
  4705. # or cannot be read: nothing tells it apart from another plate's,
  4706. # and keeping costs one file where deleting can cost the only
  4707. # copy. On an archive with exactly one plate it is that plate's.
  4708. archive.timelapse_baseline = None
  4709. stale_timelapse_relpath = archive.timelapse_path
  4710. stale_timelapse_plate_id = archive.timelapse_plate_id
  4711. starting_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4712. if stale_timelapse_relpath:
  4713. archive.timelapse_path = None
  4714. archive.timelapse_plate_id = None
  4715. stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
  4716. if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
  4717. from backend.app.services.archive import plate_indexes_in_3mf
  4718. plates = await asyncio.to_thread(
  4719. plate_indexes_in_3mf,
  4720. app_settings.base_dir / archive.file_path, # SEC-PATH-OK: stored relative archive path
  4721. )
  4722. stale_is_this_plates = len(plates) == 1
  4723. if stale_timelapse_relpath and not stale_is_this_plates:
  4724. logger.info(
  4725. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4726. stale_timelapse_relpath,
  4727. stale_timelapse_plate_id,
  4728. expected_archive_id,
  4729. starting_plate_id,
  4730. )
  4731. # The video is deleted once the adoption stands (below).
  4732. delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
  4733. # Persist a restart-stable id so a later restart resumes this
  4734. # archive by subtask_id instead of name-matching + duplicating
  4735. # it (#1485). The printer often hasn't echoed subtask_id back
  4736. # this soon after dispatch, so fall back to the id Bambuddy
  4737. # minted when it sent the print command. Scoped to this
  4738. # expected-print branch on purpose: an expected match means
  4739. # Bambuddy dispatched this exact print in this process, so the
  4740. # client's last-dispatch id genuinely belongs to it — using it
  4741. # for an externally-started print could mis-tag the archive.
  4742. effective_subtask_id = subtask_id
  4743. if not effective_subtask_id:
  4744. _client = printer_manager.get_client(printer_id)
  4745. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4746. if _dispatched:
  4747. effective_subtask_id = str(_dispatched).strip() or None
  4748. # Update on first-set OR on reprint (the queue dispatcher mints
  4749. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4750. # the rewrite for reprints leaves the archive holding the FIRST
  4751. # run's id; if MQTT then reconnects mid-print, the reconciler
  4752. # (#1542) compares the stale stored id against the printer's
  4753. # live id, sees a mismatch, and synthesises a bogus PRINT
  4754. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4755. # in #1807. Inequality check preserves the noop-on-stable-push
  4756. # behaviour the earlier `not archive.subtask_id` guard provided.
  4757. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4758. archive.subtask_id = effective_subtask_id
  4759. # #1403 follow-up: VP-queue archives are created with
  4760. # printer_id=None at queue-add time (we don't know which
  4761. # printer will run the job yet). When the print actually
  4762. # starts on a specific printer the expected-archive lookup
  4763. # used to skip this assignment, leaving printer_id=None
  4764. # forever — which then disables the "Scan for timelapse"
  4765. # button in ArchivesPage (gated on !archive.printer_id).
  4766. if archive.printer_id != printer_id:
  4767. archive.printer_id = printer_id
  4768. adopting_id = archive.id # a rollback expires the object
  4769. try:
  4770. await db.commit()
  4771. except (IntegrityError, StaleDataError):
  4772. # The archive stays unchanged, or is gone: "delete archives"
  4773. # removed the row under the adoption, which then matched no
  4774. # row (StaleDataError) rather than being refused.
  4775. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4776. return
  4777. raise
  4778. # The printer can be deleted between the check above and this
  4779. # commit (the route's transaction lasts seconds), and the commit
  4780. # then adopted the archive anyway: status, verdict and timelapse
  4781. # changed, and the deleted printer's id written on a row the
  4782. # route had detached or never touched. Undo the adoption.
  4783. if await _printer_gone(db, printer_id):
  4784. logger.info(
  4785. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4786. printer_id,
  4787. archive.id,
  4788. )
  4789. # Everything as before this adoption. The printer it had
  4790. # then stays, unless it was the deleted one: the route
  4791. # detached that row (kept) or deleted it (no row matches).
  4792. previous_printer = before_adoption["printer_id"]
  4793. await db.execute(
  4794. update(PrintArchive)
  4795. .where(PrintArchive.id == archive.id)
  4796. .values(
  4797. {
  4798. **before_adoption,
  4799. "printer_id": None if previous_printer == printer_id else previous_printer,
  4800. }
  4801. )
  4802. )
  4803. await db.commit()
  4804. await forget_printer(printer_id)
  4805. return
  4806. await _drop_replaced_plate_videos(
  4807. db,
  4808. archive.id,
  4809. starting_plate_id,
  4810. stale_timelapse_relpath if delete_stale_video else None,
  4811. logger,
  4812. )
  4813. # Track as active print
  4814. _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
  4815. await _open_run_for(archive.id, printer_id, subtask_id)
  4816. # Start timelapse session if external camera is enabled (#1353).
  4817. # Queue / VP-dispatched prints land here in the expected-archive
  4818. # branch and used to skip start_session entirely — frames were
  4819. # never captured and the post-print stitch silently returned None.
  4820. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4821. # Inject ams_mapping into usage tracker session — the session was created
  4822. # before expected-print promotion, so it may have ams_mapping=None when
  4823. # the MQTT request topic subscription failed (common on P1S/A1).
  4824. _stored_map = _print_ams_mappings.get((printer_id, expected_archive_id))
  4825. _stored_plate_id = _print_plate_ids.get((printer_id, expected_archive_id))
  4826. if _stored_map or _stored_plate_id is not None:
  4827. try:
  4828. from backend.app.services.usage_tracker import _active_sessions
  4829. _ut_session = _active_sessions.get(printer_id)
  4830. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4831. _ut_session.ams_mapping = _stored_map
  4832. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4833. # plate_id injection covers direct-Print of plate N of a multi-plate
  4834. # 3MF — queue prints already capture it via the on_print_start queue
  4835. # lookup, but direct-Print never goes through the queue (#1697).
  4836. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4837. _ut_session.plate_id = _stored_plate_id
  4838. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4839. except Exception:
  4840. pass
  4841. # Set up energy tracking (#941: persist start on archive row)
  4842. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4843. await ws_manager.send_archive_updated(
  4844. {
  4845. "id": archive.id,
  4846. "status": "printing",
  4847. }
  4848. )
  4849. # Send notification with archive data (reprint/scheduled)
  4850. if not notification_sent:
  4851. # Use archive's created_by_id; fall back to the creator registered via
  4852. # register_expected_print (handles library-file-based queue items where
  4853. # the freshly-created archive has no created_by_id yet), taken above.
  4854. archive_data = {
  4855. "print_time_seconds": _run_print_time_seconds(archive, printer_id),
  4856. "created_by_id": archive.created_by_id or fallback_creator,
  4857. }
  4858. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4859. # Extract printable objects from the archived 3MF file
  4860. _load_objects_from_archive(archive, printer_id, logger)
  4861. if archive.file_path:
  4862. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  4863. # Store Spoolman tracking data for per-filament usage reporting
  4864. try:
  4865. await _store_spoolman_print_data(
  4866. printer_id,
  4867. archive.id,
  4868. archive.file_path,
  4869. db,
  4870. printer_manager,
  4871. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4872. plate_id=_get_start_plate_id(printer_id, archive.id),
  4873. )
  4874. except Exception as e:
  4875. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4876. # Price the print from its spools now rather than only at completion (#3261)
  4877. _schedule_archive_cost_estimate(
  4878. printer_id,
  4879. archive.id,
  4880. printer_manager,
  4881. ams_mapping=_get_start_ams_mapping(data, printer_id, archive.id),
  4882. plate_id=_get_start_plate_id(printer_id, archive.id),
  4883. session_factory=async_session,
  4884. )
  4885. # Capture timelapse file baseline for snapshot-diff on completion
  4886. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4887. # hit this branch — without the baseline the completion-time scan
  4888. # falls into its "take baseline now" fallback, which snapshots
  4889. # AFTER the new MP4 already exists and never matches a diff
  4890. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4891. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4892. await _forget_if_printer_gone(printer_id)
  4893. return # Skip creating a new archive
  4894. # The archive was deleted after the job was queued.
  4895. if not archives_prints:
  4896. # Only the expected print brought a printer that does not
  4897. # archive this far; with it gone, nothing is archived.
  4898. return
  4899. # Otherwise archive the print anew rather than drop it, so it still
  4900. # gets its notification, usage tracking and history.
  4901. logger.warning(
  4902. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4903. expected_archive_id,
  4904. printer_id,
  4905. )
  4906. # Check if there's already a "printing" archive for this printer/file
  4907. # This prevents duplicates when backend restarts during an active print
  4908. from backend.app.models.archive import PrintArchive
  4909. existing_archive: PrintArchive | None = None
  4910. resumed_by_run = False
  4911. # Best match: this job's run, open on the printer since the print
  4912. # started. The archive row is shared by every plate of it, and its
  4913. # printer, job id and status are the latest start's, which may be
  4914. # another printer's.
  4915. if subtask_id:
  4916. from backend.app.services.print_log import open_run_on_printer
  4917. run = await open_run_on_printer(db, printer_id, subtask_id=subtask_id)
  4918. if run is not None and run.archive_id is not None:
  4919. existing_archive = await db.scalar(
  4920. select(PrintArchive).where(PrintArchive.id == run.archive_id, PrintArchive.deleted_at.is_(None))
  4921. )
  4922. resumed_by_run = existing_archive is not None
  4923. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4924. # across a backend restart for the same print, so this is the most
  4925. # reliable way to reattach. Only a row still printing: a cancelled one
  4926. # has been through completion (usage, history, notifications) already,
  4927. # and reopening it would count the print twice.
  4928. if subtask_id and existing_archive is None:
  4929. by_id = await db.execute(
  4930. select(PrintArchive)
  4931. .where(PrintArchive.printer_id == printer_id)
  4932. .where(PrintArchive.subtask_id == subtask_id)
  4933. .where(PrintArchive.status == "printing")
  4934. .order_by(PrintArchive.created_at.desc())
  4935. .limit(1)
  4936. )
  4937. existing_archive = by_id.scalar_one_or_none()
  4938. # Fallback match: name-based lookup. Kept as-is for prints whose
  4939. # subtask_id is missing ("0" / local / non-cloud prints).
  4940. if existing_archive is None:
  4941. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4942. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4943. # A print started from the printer's screen names its file in full,
  4944. # so the forms above double its extension. The file itself is the
  4945. # one exact match, and nothing looser is added (#3009).
  4946. if _subtask_is_the_file(subtask_name, filename):
  4947. archive_filenames.append(subtask_name)
  4948. existing = await db.execute(
  4949. select(PrintArchive)
  4950. .where(PrintArchive.printer_id == printer_id)
  4951. .where(PrintArchive.status == "printing")
  4952. .where(
  4953. or_(
  4954. PrintArchive.print_name == check_name,
  4955. PrintArchive.filename.in_(archive_filenames),
  4956. )
  4957. )
  4958. .order_by(PrintArchive.created_at.desc())
  4959. .limit(1)
  4960. )
  4961. existing_archive = existing.scalar_one_or_none()
  4962. if existing_archive:
  4963. # subtask_id match → always resume, regardless of age. Same print,
  4964. # just a backend restart.
  4965. subtask_match = resumed_by_run or bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4966. if subtask_match:
  4967. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4968. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4969. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  4970. _mark_owned_if_dispatched(existing_archive)
  4971. if await _run_needs_energy_start(existing_archive, printer_id, db):
  4972. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4973. if not notification_sent:
  4974. archive_data = {
  4975. "print_time_seconds": _run_print_time_seconds(existing_archive, printer_id),
  4976. "created_by_id": existing_archive.created_by_id,
  4977. }
  4978. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4979. _load_objects_from_archive(existing_archive, printer_id, logger)
  4980. if existing_archive.file_path:
  4981. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  4982. return
  4983. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4984. # stale from the printer's *current* progress, not wall-clock age.
  4985. # A genuinely long print used to trip a blind 4h cutoff and have its
  4986. # live archive cancelled + duplicated on every backend restart
  4987. # (#1485). If the printer reports real progress, this name-matched
  4988. # 'printing' archive IS that ongoing print — resume it whatever its
  4989. # age. Only treat it as a stale leftover when the printer clearly
  4990. # shows a different, freshly-started print: near-0% progress on an
  4991. # archive far too old to still be at 0%. Unknown progress (printer
  4992. # not connected) never cancels — resuming is the safe default.
  4993. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4994. live_status = printer_manager.get_status(printer_id)
  4995. live_progress = getattr(live_status, "progress", None) if live_status else None
  4996. looks_stale = (
  4997. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4998. )
  4999. # Two subtask ids are two prints, however young the archive: one
  5000. # whose completion was missed must not swallow the next print of
  5001. # the same file. Except Bambuddy's own reprint, which reuses the
  5002. # row and mints a fresh id (#1807): the id it last sent says so,
  5003. # and after a restart, which forgets it, this printer's queue job
  5004. # running the archive.
  5005. if (
  5006. not looks_stale
  5007. and subtask_id
  5008. and existing_archive.subtask_id
  5009. and existing_archive.subtask_id != subtask_id
  5010. ):
  5011. _client = printer_manager.get_client(printer_id)
  5012. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  5013. if _dispatched:
  5014. looks_stale = _dispatched != subtask_id
  5015. else:
  5016. from backend.app.models.print_queue import PrintQueueItem as _PQI
  5017. queue_run = await db.scalar(
  5018. select(_PQI.id)
  5019. .where(_PQI.archive_id == existing_archive.id)
  5020. .where(_PQI.printer_id == printer_id)
  5021. .where(_PQI.status == "printing")
  5022. .limit(1)
  5023. )
  5024. looks_stale = queue_run is None
  5025. if looks_stale:
  5026. logger.warning(
  5027. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  5028. " — marking cancelled and creating new archive",
  5029. existing_archive.id,
  5030. archive_age,
  5031. live_progress,
  5032. existing_archive.subtask_id,
  5033. subtask_id,
  5034. )
  5035. existing_archive.status = "cancelled"
  5036. # Canonical key, not a sentence (issue #2974). "No status update
  5037. # received" is what both stale paths actually observed; which of
  5038. # the two it was is already carried by ``status`` -- cancelled
  5039. # here, the reconciled outcome at the reconnect site -- so one
  5040. # key loses no information and gives the Statistics breakdown a
  5041. # single bucket instead of two untranslatable prose strings.
  5042. existing_archive.failure_reason = "noStatusUpdate"
  5043. # And its run, as before runs were opened at the start: a new
  5044. # print starts on the printer, so whatever is open there ended
  5045. # unseen. Left open, the next reconnect would close it again.
  5046. from backend.app.services.print_log import discard_open_runs
  5047. discarded = await discard_open_runs(db, printer_id)
  5048. await db.commit()
  5049. await _announce_discarded_runs(discarded, printer_id)
  5050. # Its print keys go with it; the new archive registers its own.
  5051. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id and k[0] == printer_id]:
  5052. del _active_prints[_key]
  5053. # Fall through to create new archive (don't return)
  5054. else:
  5055. logger.info(
  5056. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  5057. )
  5058. # Track this as the active print
  5059. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  5060. _mark_owned_if_dispatched(existing_archive)
  5061. # Attach subtask_id retroactively so future restarts can resume.
  5062. # Compare for inequality (not "is empty") to also pick up reprint
  5063. # dispatches that mint a fresh id — see #1807 for the bogus
  5064. # "Print Stopped" the strict-empty guard caused on reconnect.
  5065. if subtask_id and existing_archive.subtask_id != subtask_id:
  5066. existing_archive.subtask_id = subtask_id
  5067. await db.commit()
  5068. await _open_run_for(existing_archive.id, printer_id, subtask_id)
  5069. # Also set up energy tracking if not already tracked (#941: persisted column)
  5070. if await _run_needs_energy_start(existing_archive, printer_id, db):
  5071. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  5072. # Send notification with archive data (existing archive)
  5073. if not notification_sent:
  5074. archive_data = {
  5075. "print_time_seconds": _run_print_time_seconds(existing_archive, printer_id),
  5076. "created_by_id": existing_archive.created_by_id,
  5077. }
  5078. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5079. # Extract printable objects from the archived 3MF file
  5080. _load_objects_from_archive(existing_archive, printer_id, logger)
  5081. if existing_archive.file_path:
  5082. _load_pauses_from_resumed_archive(existing_archive, printer_id)
  5083. return
  5084. # Build list of possible 3MF filenames to try
  5085. possible_names = []
  5086. # Bambu printers typically store files as "Name.gcode.3mf"
  5087. # The subtask_name is usually the best source for the filename
  5088. if subtask_name:
  5089. if _subtask_is_the_file(subtask_name, filename):
  5090. # A print started from the printer's own screen reports the
  5091. # file's full name, extension included. That is the file, so
  5092. # no extension is appended to it (#3009).
  5093. possible_names.append(subtask_name)
  5094. else:
  5095. # Try common Bambu naming patterns
  5096. possible_names.append(f"{subtask_name}.gcode.3mf")
  5097. possible_names.append(f"{subtask_name}.3mf")
  5098. # Try original filename with .3mf extension
  5099. if filename:
  5100. # Extract just the filename part, not the full path
  5101. fname = filename.split("/")[-1] if "/" in filename else filename
  5102. if fname.endswith(".3mf"):
  5103. possible_names.append(fname)
  5104. elif fname.endswith(".gcode"):
  5105. base = fname.rsplit(".", 1)[0]
  5106. possible_names.append(f"{base}.gcode.3mf")
  5107. possible_names.append(f"{base}.3mf")
  5108. else:
  5109. possible_names.append(f"{fname}.gcode.3mf")
  5110. possible_names.append(f"{fname}.3mf")
  5111. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  5112. space_variants = []
  5113. for name in possible_names:
  5114. if " " in name:
  5115. space_variants.append(name.replace(" ", "_"))
  5116. possible_names.extend(space_variants)
  5117. # Remove duplicates while preserving order
  5118. seen = set()
  5119. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  5120. logger.info("Trying filenames: %s", possible_names)
  5121. # Release the pooled DB connection before the 3MF FTP download. Reaching
  5122. # here means none of the expected-/existing-archive write branches ran
  5123. # (they all return earlier) — only SELECTs have executed on this path, so
  5124. # this commit persists nothing; it ends the read transaction so the
  5125. # connection returns to the pool during the download. That download tries
  5126. # up to five remote paths per candidate filename with retry/backoff and
  5127. # can run for minutes under FTP contention; holding the session across it
  5128. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  5129. # work runs during the download — the new-archive writes below re-acquire
  5130. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  5131. await db.commit()
  5132. # Try to find and download the 3MF file
  5133. temp_path = None
  5134. downloaded_filename = None
  5135. # Cache check: cover endpoint may have already pulled this 3MF during
  5136. # the print (frontend opens the card and shows the thumbnail) — reuse
  5137. # that file instead of re-downloading 36MB over the same FTP link that
  5138. # just served it (#972). The cache keys on a normalized filename so
  5139. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  5140. for try_filename in possible_names:
  5141. if not try_filename.endswith(".3mf"):
  5142. continue
  5143. cached = get_cached_3mf(printer_id, try_filename)
  5144. if cached:
  5145. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  5146. temp_path = cached
  5147. downloaded_filename = try_filename
  5148. break
  5149. # Does this printer keep the sliced file somewhere FTPS can reach? On
  5150. # H2-series and P2S the answer is routinely no — the file stays on
  5151. # internal eMMC and port 990 only ever serves external storage — and
  5152. # then the whole sweep below (six filenames x five directories x four
  5153. # retries, then the directory walk) is ~110 connections that cannot
  5154. # succeed. Skip it and say why (#2780).
  5155. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  5156. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  5157. # running rather than because the file is somewhere unreachable. The
  5158. # distinction is the whole of #2957: one is permanent, the other clears
  5159. # in minutes with the file still sitting on the printer.
  5160. blocked_by_ftps_cooloff = False
  5161. # Set when a probe reached the printer and still came back without the
  5162. # file -- a timeout mid-transfer, a refused connection, anything that is
  5163. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  5164. # caught by name below, so a file that genuinely is not on the card
  5165. # leaves this False and schedules nothing. Anything else means the
  5166. # transfer, not the file, is what failed, and that does not last (#3063).
  5167. ftp_transfer_failed = False
  5168. # The narrower case of the above: the directory walk *listed* a file
  5169. # for this print and could not fetch it, so the file is on the card
  5170. # under a name that matches. The only failure that rules out an
  5171. # earlier run's 3MF standing in for it (#3307).
  5172. walk_transfer_failed = False
  5173. # Paths the sweep reached and could not transfer -- a timeout, not a
  5174. # 550. The directory walk lists the same folders and would download
  5175. # the same file again: on a slow A1 that was a second 300 s on the
  5176. # printer's one FTPS slot, at print start, for a file the recovery
  5177. # retry fetches with a deadline twice as long (#3308).
  5178. sweep_failed_paths: set[str] = set()
  5179. # The print's name, for a fallback archive whose `subtask_name` the
  5180. # plate guard below had to disown. Display only, and deliberately kept
  5181. # apart from `subtask_name`: that variable is what every file lookup
  5182. # here is built from, and once a name has been shown to fetch another
  5183. # plate's 3MF it must not key `_active_prints` either, or the cover
  5184. # endpoint hands the same contradicted file to
  5185. # `_recover_fallback_archive` and fills the row in with it (#3126).
  5186. display_name_after_plate_reject: str | None = None
  5187. # Get FTP retry settings
  5188. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  5189. # ...but "the printer put it on eMMC" is where it went, not whether we
  5190. # can read it. An H2D with a card in mirrors the job to /cache and
  5191. # serves it happily, and skipping on the URL alone cost that reporter
  5192. # every archive for two days (#2856). So ask the printer instead of
  5193. # guessing: the dispatch named the exact file, which is one connection
  5194. # walking five paths rather than the sweep's ~110. Only when the probe
  5195. # comes back empty does the verdict's reason stand.
  5196. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  5197. if ftps_handshake_blocked(printer.ip_address):
  5198. # Deliberately NOT recorded as a cool-off give-up. This branch
  5199. # only runs on an unreachable verdict, and that verdict is the
  5200. # honest, permanent reason the archive is empty — the probe was
  5201. # a long shot on top of it. Blaming the cool-off here would
  5202. # schedule a retry for a file sitting on internal eMMC, which is
  5203. # the sweep #2780 removed (#2957).
  5204. logger.debug(
  5205. "Not probing for %s on printer %s: its file service is not answering over TLS",
  5206. storage.probe_filename,
  5207. printer_id,
  5208. )
  5209. else:
  5210. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  5211. probe_path.parent.mkdir(parents=True, exist_ok=True)
  5212. try:
  5213. probe_hit = await download_file_try_paths_async(
  5214. printer.ip_address,
  5215. printer.access_code,
  5216. ftp_probe_paths(storage.probe_filename),
  5217. probe_path,
  5218. socket_timeout=ftp_timeout,
  5219. printer_model=printer.model,
  5220. )
  5221. except Exception as e:
  5222. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  5223. probe_hit = False
  5224. if probe_hit:
  5225. downloaded_filename = storage.probe_filename
  5226. temp_path = probe_path
  5227. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  5228. # Naming the path, not just the file: a printer that keeps
  5229. # uploads around for weeks can serve a same-named copy of an
  5230. # earlier slice, and without the directory in the log that
  5231. # mismatch is invisible rather than merely rare (#1820).
  5232. logger.info(
  5233. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  5234. downloaded_filename,
  5235. probe_hit,
  5236. printer_id,
  5237. storage.reason,
  5238. )
  5239. if not storage.reachable and not downloaded_filename:
  5240. # Same opening words whether or not a probe ran, because that is
  5241. # the phrase support asks people to grep for — only the tail says
  5242. # which of the two happened.
  5243. logger.info(
  5244. "Skipping the 3MF lookup for printer %s: %s — %s",
  5245. printer_id,
  5246. storage.reason,
  5247. "no copy of it on external storage either"
  5248. if storage.probe_filename
  5249. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  5250. )
  5251. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  5252. if not try_filename.endswith(".3mf"):
  5253. continue
  5254. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  5255. # printers, so try it first — deferring it to last cost #972's reporter
  5256. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  5257. # landing on the path that actually had the file.
  5258. remote_paths = [
  5259. f"/{try_filename}",
  5260. f"/cache/{try_filename}",
  5261. f"/model/{try_filename}",
  5262. f"/data/{try_filename}",
  5263. f"/data/Metadata/{try_filename}",
  5264. ]
  5265. temp_path = app_settings.archive_dir / "temp" / try_filename
  5266. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5267. for remote_path in remote_paths:
  5268. if ftps_handshake_blocked(printer.ip_address):
  5269. # The printer's FTPS service is not completing a TLS
  5270. # handshake, so it has no path we could reach — walking the
  5271. # remaining candidates only re-runs the same failure
  5272. # (#2780). Fall through to the no-3MF archive now.
  5273. #
  5274. # Remember *why*, though. This is the one give-up that is
  5275. # temporary: the cool-off clears in minutes and the file was
  5276. # on the printer the whole time. The fallback archive is
  5277. # stamped with it so a retry can be scheduled, and so the
  5278. # Archives banner stops blaming storage (#2957).
  5279. blocked_by_ftps_cooloff = True
  5280. logger.warning(
  5281. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  5282. printer_id,
  5283. )
  5284. break
  5285. logger.debug("Trying FTP download: %s", remote_path)
  5286. try:
  5287. if ftp_retry_enabled:
  5288. downloaded = await with_ftp_retry(
  5289. download_file_async,
  5290. printer.ip_address,
  5291. printer.access_code,
  5292. remote_path,
  5293. temp_path,
  5294. timeout=ftp_timeout,
  5295. socket_timeout=ftp_timeout,
  5296. printer_model=printer.model,
  5297. max_retries=ftp_retry_count,
  5298. retry_delay=ftp_retry_delay,
  5299. operation_name=f"Download 3MF from {remote_path}",
  5300. cooloff_ip=printer.ip_address,
  5301. non_retry_exceptions=(FileNotOnPrinterError,),
  5302. )
  5303. else:
  5304. downloaded = await download_file_async(
  5305. printer.ip_address,
  5306. printer.access_code,
  5307. remote_path,
  5308. temp_path,
  5309. timeout=ftp_timeout,
  5310. socket_timeout=ftp_timeout,
  5311. printer_model=printer.model,
  5312. )
  5313. if downloaded:
  5314. downloaded_filename = try_filename
  5315. logger.info("Downloaded: %s", remote_path)
  5316. # Populate shared cache so the cover endpoint (if it
  5317. # runs next) doesn't refetch the same 36MB over FTP.
  5318. cache_3mf_download(printer_id, try_filename, temp_path)
  5319. break
  5320. # with_ftp_retry returns None once it has spent its budget,
  5321. # and download_file_async returns False on a timeout, so an
  5322. # exhausted transfer arrives here rather than as an
  5323. # exception (#3063).
  5324. ftp_transfer_failed = True
  5325. sweep_failed_paths.add(remote_path)
  5326. except FileNotOnPrinterError:
  5327. # 550 — file isn't at this path. Advance to next candidate
  5328. # without burning the retry budget.
  5329. logger.debug("3MF not at %s (550), trying next path", remote_path)
  5330. except Exception as e:
  5331. ftp_transfer_failed = True
  5332. sweep_failed_paths.add(remote_path)
  5333. logger.debug("FTP download failed for %s: %s", remote_path, e)
  5334. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  5335. break
  5336. # If still not found, try listing directories to find matching file
  5337. # Different printer models use different directory structures. Skipped
  5338. # when the printer's FTPS handshake is failing — the directory walk is
  5339. # five more connections that cannot get further than the download did.
  5340. if (
  5341. not downloaded_filename
  5342. and storage.reachable
  5343. and (filename or subtask_name)
  5344. and not ftps_handshake_blocked(printer.ip_address)
  5345. ):
  5346. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  5347. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  5348. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  5349. # Every folder is listed before one file is picked, so a file named
  5350. # for the print in a later folder wins over one that merely
  5351. # contains the name in an earlier folder.
  5352. listed_paths: list[str] = []
  5353. for search_dir in search_dirs:
  5354. try:
  5355. dir_files = await list_files_async(
  5356. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  5357. )
  5358. except Exception as e:
  5359. logger.debug("Failed to list %s: %s", search_dir, e)
  5360. continue
  5361. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  5362. if threemf_files:
  5363. logger.info(
  5364. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  5365. )
  5366. listed_paths += [
  5367. posixpath.join(search_dir, f.get("name", "")) for f in dir_files if not f.get("is_directory")
  5368. ]
  5369. for remote_full_path in _3mf_files_for_print(listed_paths, search_term):
  5370. if remote_full_path in sweep_failed_paths:
  5371. # Listed for this print, and its transfer already failed:
  5372. # the same as a failed walk download, without spending a
  5373. # second deadline on it. Skipping it cannot hand the walk a
  5374. # look-alike: while a file of the print's own name is
  5375. # listed, files that merely contain the name are not.
  5376. logger.info(
  5377. "Not downloading %s again: its transfer already failed; the recovery retry will fetch it",
  5378. remote_full_path,
  5379. )
  5380. walk_transfer_failed = True
  5381. continue
  5382. fname = posixpath.basename(remote_full_path)
  5383. logger.info("Found matching file: %s", remote_full_path)
  5384. temp_path = app_settings.archive_dir / "temp" / fname
  5385. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5386. try:
  5387. if ftp_retry_enabled:
  5388. downloaded = await with_ftp_retry(
  5389. download_file_async,
  5390. printer.ip_address,
  5391. printer.access_code,
  5392. remote_full_path,
  5393. temp_path,
  5394. timeout=ftp_timeout,
  5395. socket_timeout=ftp_timeout,
  5396. printer_model=printer.model,
  5397. max_retries=ftp_retry_count,
  5398. retry_delay=ftp_retry_delay,
  5399. operation_name=f"Download 3MF from {remote_full_path}",
  5400. cooloff_ip=printer.ip_address,
  5401. )
  5402. else:
  5403. downloaded = await download_file_async(
  5404. printer.ip_address,
  5405. printer.access_code,
  5406. remote_full_path,
  5407. temp_path,
  5408. timeout=ftp_timeout,
  5409. socket_timeout=ftp_timeout,
  5410. printer_model=printer.model,
  5411. )
  5412. except Exception as e:
  5413. logger.debug("Failed to download %s: %s", remote_full_path, e)
  5414. continue
  5415. if downloaded:
  5416. downloaded_filename = fname
  5417. logger.info("Found and downloaded: %s", remote_full_path)
  5418. cache_3mf_download(printer_id, fname, temp_path)
  5419. break
  5420. # The listing named the file, so it is on the card;
  5421. # only the transfer failed (#3063).
  5422. ftp_transfer_failed = True
  5423. walk_transfer_failed = True
  5424. # A "Print again" on the printer's screen names no file Bambuddy can
  5425. # find: only its history copy under a generic name, and the 3MF's
  5426. # internal title (#3307). When an earlier run of the same job was
  5427. # archived, its 3MF is the one being printed again. Not when the
  5428. # directory walk listed a file for this print and only its transfer
  5429. # failed: that file is on the card, and the retry fetches it. A
  5430. # cool-off or a failed sweep path is no such evidence -- the retry
  5431. # tries the same names, which this print's file never had.
  5432. reused_3mf_from: int | None = None
  5433. if not downloaded_filename and not walk_transfer_failed:
  5434. reported_layers = raw_mqtt.get("total_layer_num")
  5435. earlier = await _archived_3mf_for_repeat(
  5436. db,
  5437. printer_id,
  5438. subtask_name,
  5439. filename,
  5440. reported_layers if isinstance(reported_layers, int) and reported_layers > 0 else None,
  5441. )
  5442. if earlier is not None:
  5443. reuse_name = Path(earlier.filename or "").name or f"archive_{earlier.id}.3mf"
  5444. # Per printer: two printers reprinting the same job at once
  5445. # must not write one temp file (archive_print names the
  5446. # archive after original_filename, not this path).
  5447. reuse_path = app_settings.archive_dir / "temp" / f"reprint_{printer_id}_{reuse_name}"
  5448. try:
  5449. reuse_path.parent.mkdir(parents=True, exist_ok=True)
  5450. await asyncio.to_thread(shutil.copyfile, app_settings.base_dir / earlier.file_path, reuse_path)
  5451. except OSError as e:
  5452. # A copy that fails leaves the print the fallback archive
  5453. # it would have had, not no archive at all.
  5454. logger.warning("Could not copy the 3MF of archive %s for printer %s: %s", earlier.id, printer_id, e)
  5455. else:
  5456. temp_path = reuse_path
  5457. downloaded_filename = reuse_name
  5458. reused_3mf_from = earlier.id
  5459. cache_3mf_download(printer_id, reuse_name, temp_path)
  5460. logger.info(
  5461. "No 3MF on printer %s for %s (%s); using the 3MF of archive %s, an earlier run of the same job",
  5462. printer_id,
  5463. subtask_name,
  5464. filename,
  5465. earlier.id,
  5466. )
  5467. # Validate the downloaded 3MF actually matches the plate that's running
  5468. # (#1204): subtask_name lags across consecutive plates of the same model,
  5469. # so the first FTP candidate (built from subtask_name) can land on the
  5470. # previous plate's still-resident upload. Cross-check the slice_info
  5471. # plate index against the plate parsed from gcode_file (always fresh —
  5472. # it's the field whose change triggered this callback).
  5473. if downloaded_filename and temp_path:
  5474. expected_plate = parse_plate_id(filename)
  5475. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  5476. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  5477. logger.warning(
  5478. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  5479. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  5480. downloaded_filename,
  5481. actual_plate,
  5482. expected_plate,
  5483. subtask_name,
  5484. )
  5485. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  5486. retry_succeeded = False
  5487. if corrected_subtask and corrected_subtask != subtask_name:
  5488. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  5489. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  5490. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  5491. for remote_path in (
  5492. f"/{try_filename}",
  5493. f"/cache/{try_filename}",
  5494. f"/model/{try_filename}",
  5495. f"/data/{try_filename}",
  5496. f"/data/Metadata/{try_filename}",
  5497. ):
  5498. try:
  5499. if ftp_retry_enabled:
  5500. downloaded = await with_ftp_retry(
  5501. download_file_async,
  5502. printer.ip_address,
  5503. printer.access_code,
  5504. remote_path,
  5505. retry_temp_path,
  5506. timeout=ftp_timeout,
  5507. socket_timeout=ftp_timeout,
  5508. printer_model=printer.model,
  5509. max_retries=ftp_retry_count,
  5510. retry_delay=ftp_retry_delay,
  5511. operation_name=f"Re-download 3MF from {remote_path}",
  5512. cooloff_ip=printer.ip_address,
  5513. non_retry_exceptions=(FileNotOnPrinterError,),
  5514. )
  5515. else:
  5516. downloaded = await download_file_async(
  5517. printer.ip_address,
  5518. printer.access_code,
  5519. remote_path,
  5520. retry_temp_path,
  5521. timeout=ftp_timeout,
  5522. socket_timeout=ftp_timeout,
  5523. printer_model=printer.model,
  5524. )
  5525. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  5526. logger.info(
  5527. "[CALLBACK] Re-download succeeded with corrected name %s "
  5528. "(plate %s) — replacing wrong file",
  5529. try_filename,
  5530. expected_plate,
  5531. )
  5532. try:
  5533. temp_path.unlink(missing_ok=True)
  5534. except OSError:
  5535. pass
  5536. temp_path = retry_temp_path
  5537. downloaded_filename = try_filename
  5538. subtask_name = corrected_subtask
  5539. cache_3mf_download(printer_id, try_filename, temp_path)
  5540. retry_succeeded = True
  5541. break
  5542. elif downloaded:
  5543. # Wrong plate again — discard and keep trying
  5544. try:
  5545. retry_temp_path.unlink(missing_ok=True)
  5546. except OSError:
  5547. pass
  5548. except FileNotOnPrinterError:
  5549. continue
  5550. except Exception as e:
  5551. logger.debug("Re-download failed for %s: %s", remote_path, e)
  5552. if retry_succeeded:
  5553. break
  5554. # If the retry didn't find a matching file, drop the wrong 3MF
  5555. # so the no-3MF fallback below creates an archive whose name
  5556. # at least reflects the right plate.
  5557. if not retry_succeeded:
  5558. logger.warning(
  5559. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  5560. expected_plate,
  5561. )
  5562. try:
  5563. temp_path.unlink(missing_ok=True)
  5564. except OSError:
  5565. pass
  5566. temp_path = None
  5567. downloaded_filename = None
  5568. # Whatever the sweep's transport did earlier, it is not why
  5569. # this archive ends up empty: a 3MF downloaded fine, it was
  5570. # just the wrong plate. Retrying would re-fetch that same
  5571. # contradicted file under the same stale names and hand it
  5572. # to _recover_fallback_archive, which checks that a
  5573. # candidate is a readable 3MF but not which plate it is --
  5574. # so the row would be filled in with another plate's
  5575. # filament and cost, the exact swap #2957 removed (#3063).
  5576. ftp_transfer_failed = False
  5577. # Disown the name for *lookups*: it has just been shown to
  5578. # fetch another plate's 3MF, and it keys `_active_prints`
  5579. # below, where the cover endpoint's own download of that
  5580. # same name would find this archive and fill it in with the
  5581. # file we are discarding here.
  5582. #
  5583. # Keep it for the *title*, which is a separate question.
  5584. # ``swap_plate_suffix`` returns None both for a name that
  5585. # carries no "- Plate N" / "_plate_N" suffix and for no
  5586. # name at all, and those are not the same situation: a name
  5587. # without a suffix holds no stale plate number to be wrong
  5588. # about. Blanking both uses at once dropped the project
  5589. # name too, and the row fell through to the gcode_file path
  5590. # titled "plate_1" though the real name was in hand.
  5591. # #1204's own premise is consecutive plates *of the same
  5592. # model*, so the project part is right either way (#3126).
  5593. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  5594. subtask_name = corrected_subtask or ""
  5595. # Deleted while the 3MF was being fetched (that can take minutes): no
  5596. # archive, timelapse or tracking for a printer that will never report
  5597. # the print's end. forget_printer again: the download registered its
  5598. # 3MF cache entry after the delete cleared the id. (A delete committing
  5599. # while the archive is written is caught after its commit.)
  5600. if await _printer_gone(db, printer_id):
  5601. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  5602. await forget_printer(printer_id)
  5603. return
  5604. if not downloaded_filename or not temp_path:
  5605. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  5606. # Create a fallback archive without 3MF data so the print is still tracked
  5607. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  5608. try:
  5609. from backend.app.models.archive import PrintArchive
  5610. # Why the card is empty. The two temporary causes outrank the
  5611. # storage verdict because they say the sweep never got a fair
  5612. # answer: a cool-off skipped it at the transport, and a failed
  5613. # transfer reached the printer but never finished. Either way
  5614. # the file is still on the card, so reporting where the printer
  5615. # files its jobs would describe a setting that is not the
  5616. # problem (#2957, #3063).
  5617. if blocked_by_ftps_cooloff:
  5618. no_3mf_reason = REASON_FTPS_COOLOFF
  5619. elif storage.reachable and ftp_transfer_failed:
  5620. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5621. else:
  5622. no_3mf_reason = storage.reason
  5623. # Derive print name from subtask_name or filename. The
  5624. # plate guard's disowned name comes second: it is a real name
  5625. # for a real print, and only the gcode_file path is left
  5626. # otherwise -- which titles the row "plate_1" (#3126).
  5627. print_name = subtask_name or display_name_after_plate_reject or filename
  5628. if print_name:
  5629. # Clean up the name (remove extensions, path parts)
  5630. print_name = print_name.split("/")[-1]
  5631. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5632. else:
  5633. print_name = "Unknown Print"
  5634. # Recover estimated print time from MQTT (best-effort for notifications)
  5635. fallback_print_time = None
  5636. mqtt_remaining = data.get("remaining_time")
  5637. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5638. fallback_print_time = int(mqtt_remaining)
  5639. if fallback_print_time is None:
  5640. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5641. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5642. fallback_print_time = int(mc_remaining * 60)
  5643. # Best-effort filament metadata from MQTT — see
  5644. # _extract_filament_data_from_mqtt. Without this the fallback
  5645. # archive's filament fields stayed NULL even though the AMS
  5646. # state at print start was sitting right there in `data`.
  5647. # The slicer's ams_mapping (when present) narrows the result
  5648. # to slots actually used by the print (#1533).
  5649. mqtt_filament_meta = _extract_filament_data_from_mqtt(
  5650. data, _get_start_ams_mapping(data, printer_id, None)
  5651. )
  5652. # Create minimal archive entry
  5653. fallback_archive = PrintArchive(
  5654. printer_id=printer_id,
  5655. filename=filename or f"{print_name}.3mf",
  5656. file_path="", # Empty - no 3MF file available
  5657. file_size=0,
  5658. print_name=print_name,
  5659. print_time_seconds=fallback_print_time,
  5660. status="printing",
  5661. started_at=detected_at,
  5662. subtask_id=subtask_id,
  5663. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5664. filament_type=mqtt_filament_meta.get("filament_type"),
  5665. filament_color=mqtt_filament_meta.get("filament_color"),
  5666. extra_data={
  5667. "no_3mf_available": True,
  5668. # Why the card is empty, when we know -- see above. The
  5669. # banner reads this to stop telling H2/P2 owners to
  5670. # switch on a setting that is already on and would not
  5671. # have helped (#2780).
  5672. "no_3mf_reason": no_3mf_reason,
  5673. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5674. "_print_data": data,
  5675. },
  5676. )
  5677. db.add(fallback_archive)
  5678. try:
  5679. await db.commit()
  5680. except IntegrityError:
  5681. # Not "Failed to create fallback archive" below, and no
  5682. # start notification for a printer that is gone.
  5683. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5684. return
  5685. raise
  5686. await db.refresh(fallback_archive)
  5687. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5688. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5689. return
  5690. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5691. # Track as active print
  5692. _bind_active_print(printer_id, fallback_archive.id, fallback_archive.filename, filename, subtask_name)
  5693. await _open_run_for(fallback_archive.id, printer_id, subtask_id)
  5694. # Record starting energy if smart plug available (#941: persisted column)
  5695. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5696. # Send WebSocket notification
  5697. await ws_manager.send_archive_created(
  5698. {
  5699. "id": fallback_archive.id,
  5700. "printer_id": fallback_archive.printer_id,
  5701. "filename": fallback_archive.filename,
  5702. "print_name": fallback_archive.print_name,
  5703. "status": fallback_archive.status,
  5704. }
  5705. )
  5706. # MQTT relay - publish archive created
  5707. try:
  5708. await mqtt_relay.on_archive_created(
  5709. archive_id=fallback_archive.id,
  5710. print_name=fallback_archive.print_name,
  5711. printer_name=printer.name,
  5712. status=fallback_archive.status,
  5713. )
  5714. except Exception:
  5715. pass # Don't fail if MQTT fails
  5716. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5717. try:
  5718. await _store_spoolman_print_data(
  5719. printer_id,
  5720. fallback_archive.id,
  5721. fallback_archive.file_path,
  5722. db,
  5723. printer_manager,
  5724. ams_mapping=_get_start_ams_mapping(data, printer_id, fallback_archive.id),
  5725. plate_id=_get_start_plate_id(printer_id, fallback_archive.id),
  5726. )
  5727. except Exception as e:
  5728. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5729. # Both temporary give-ups are worth coming back for, and for
  5730. # the same reason: the file is on the printer and the last look
  5731. # failed at the transport rather than finding nothing. One waits
  5732. # out the handshake block (#2957), the other waits for the
  5733. # printer to stop being busy (#3063). Deliberately not scheduled
  5734. # for a storage verdict: a file on internal eMMC will not appear
  5735. # at any FTPS path however long we wait, and retrying it is
  5736. # exactly the sweep #2780 removed.
  5737. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5738. # `possible_names`, not the raw MQTT strings: it is the exact
  5739. # list this flow just tried, already stripped of any path
  5740. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5741. # some firmware) and deduped.
  5742. _schedule_fallback_3mf_retry(
  5743. printer_id=printer_id,
  5744. archive_id=fallback_archive.id,
  5745. filenames=list(possible_names),
  5746. reason=no_3mf_reason,
  5747. )
  5748. # Send notification without archive data (file not found)
  5749. if not notification_sent:
  5750. await _send_print_start_notification(printer_id, data, logger=logger)
  5751. # The same baseline the other two on_print_start branches take
  5752. # (#2704), and last for the same reason they are: it lists the
  5753. # printer's timelapse directory, so a slow card must not delay
  5754. # the _active_prints registration, the energy reading, the
  5755. # archive-created event or the start notification above it.
  5756. #
  5757. # This branch never took one, so every no-3MF archive reached
  5758. # completion with no baseline in memory and none on the row, and
  5759. # the completion scan fell into its "snapshot now" fallback --
  5760. # which runs after the printer has written the video, so the new
  5761. # file landed inside the baseline and no diff ever matched
  5762. # (#2957 follow-up).
  5763. #
  5764. # Skipped when the FTPS cool-off is what produced this fallback:
  5765. # the listing needs the same connection that just failed, so it
  5766. # could only record that the card was unreadable. The scan
  5767. # handles that case by refusing to choose between candidates.
  5768. if not blocked_by_ftps_cooloff:
  5769. await _capture_timelapse_baseline_at_start(
  5770. printer, printer_id, logger, archive_id=fallback_archive.id
  5771. )
  5772. await _forget_if_printer_gone(printer_id)
  5773. return
  5774. except Exception as e:
  5775. logger.error("Failed to create fallback archive: %s", e)
  5776. # Send notification without archive data (file not found)
  5777. if not notification_sent:
  5778. await _send_print_start_notification(printer_id, data, logger=logger)
  5779. return
  5780. try:
  5781. # Archive the file with status "printing"
  5782. service = ArchiveService(db)
  5783. try:
  5784. archive = await service.archive_print(
  5785. printer_id=printer_id,
  5786. source_file=temp_path,
  5787. print_data={
  5788. **data,
  5789. "status": "printing",
  5790. # Where the 3MF came from when the printer had none to
  5791. # give (#3307), for whoever reads this archive later.
  5792. **({"_3mf_from_archive": reused_3mf_from} if reused_3mf_from is not None else {}),
  5793. },
  5794. subtask_id=subtask_id,
  5795. started_at=detected_at,
  5796. # The reused copy's temp name carries the printer id; a
  5797. # download's is the file's own name, as before.
  5798. original_filename=downloaded_filename if reused_3mf_from is not None else None,
  5799. )
  5800. except IntegrityError:
  5801. # archive_print removed the folder it had copied the 3MF into.
  5802. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5803. return
  5804. raise
  5805. if archive:
  5806. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5807. # Set on the row rather than passed to archive_print, which also
  5808. # serves the queue dispatcher — there the queue item decides.
  5809. # Guarded because this branch has no ``except``: an unhandled
  5810. # write error would take the _active_prints registration, the
  5811. # start notification, the energy reading and the timelapse
  5812. # baseline below it with it, and a missing prompt is by far the
  5813. # cheaper failure.
  5814. archive_id = archive.id
  5815. try:
  5816. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5817. archive.confirm_requested = True
  5818. await db.commit()
  5819. except Exception as e:
  5820. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5821. # The rollback expires every loaded object, and on an async
  5822. # session reading one afterwards raises instead of
  5823. # reloading, so the two this branch goes on to use are
  5824. # fetched again. The archive itself was committed by
  5825. # archive_print; only the flag is lost.
  5826. try:
  5827. await db.rollback()
  5828. archive = await db.get(PrintArchive, archive_id)
  5829. printer = await db.get(Printer, printer_id)
  5830. except Exception as reload_error:
  5831. logger.warning(
  5832. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5833. )
  5834. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5835. return
  5836. # Track this active print (use both original filename and downloaded filename)
  5837. _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
  5838. await _open_run_for(archive_id, printer_id, subtask_id)
  5839. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5840. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5841. # Record starting energy from smart plug if available (#941: persisted column)
  5842. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5843. await ws_manager.send_archive_created(
  5844. {
  5845. "id": archive.id,
  5846. "printer_id": archive.printer_id,
  5847. "filename": archive.filename,
  5848. "print_name": archive.print_name,
  5849. "status": archive.status,
  5850. }
  5851. )
  5852. # MQTT relay - publish archive created
  5853. try:
  5854. await mqtt_relay.on_archive_created(
  5855. archive_id=archive.id,
  5856. print_name=archive.print_name,
  5857. printer_name=printer.name,
  5858. status=archive.status,
  5859. )
  5860. except Exception:
  5861. pass # Don't fail if MQTT fails
  5862. # Send notification with archive data (new archive created)
  5863. if not notification_sent:
  5864. archive_data = {
  5865. "print_time_seconds": _run_print_time_seconds(archive, printer_id),
  5866. "created_by_id": archive.created_by_id,
  5867. }
  5868. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5869. # Extract printable objects for skip object functionality
  5870. try:
  5871. from backend.app.services.archive import extract_printable_objects_from_3mf
  5872. client = printer_manager.get_client(printer_id)
  5873. if client:
  5874. with open(temp_path, "rb") as f:
  5875. threemf_data = f.read()
  5876. # Extract with positions for UI overlay, scoped to the
  5877. # plate that is printing — an all-plates 3MF carries
  5878. # every plate's objects (#2522).
  5879. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5880. threemf_data,
  5881. plate_number=resolve_plate_id(client.state),
  5882. include_positions=True,
  5883. )
  5884. if printable_objects:
  5885. # Store objects in printer state
  5886. client.state.printable_objects = printable_objects
  5887. client.state.printable_objects_bbox_all = bbox_all
  5888. client.state.skipped_objects = [] # Reset skipped objects for new print
  5889. logger.info(
  5890. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5891. )
  5892. except Exception as e:
  5893. logger.debug("Failed to extract printable objects: %s", e)
  5894. # From the archived copy: the downloaded one may be removed
  5895. # below while the pauses are still being read.
  5896. if archive is not None and archive.file_path:
  5897. _load_pauses_from_3mf(app_settings.base_dir / archive.file_path, printer_id)
  5898. # Store Spoolman tracking data for per-filament usage reporting
  5899. try:
  5900. await _store_spoolman_print_data(
  5901. printer_id,
  5902. archive.id,
  5903. archive.file_path,
  5904. db,
  5905. printer_manager,
  5906. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5907. plate_id=_get_start_plate_id(printer_id, archive_id),
  5908. )
  5909. except Exception as e:
  5910. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5911. # Price the print from its spools now rather than only at completion (#3261)
  5912. _schedule_archive_cost_estimate(
  5913. printer_id,
  5914. archive.id,
  5915. printer_manager,
  5916. ams_mapping=_get_start_ams_mapping(data, printer_id, archive_id),
  5917. plate_id=_get_start_plate_id(printer_id, archive_id),
  5918. session_factory=async_session,
  5919. )
  5920. # Capture timelapse file baseline for snapshot-diff on completion
  5921. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5922. await _forget_if_printer_gone(printer_id)
  5923. finally:
  5924. # Keep temp_path around until print completes so the cover endpoint
  5925. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5926. # the file. If the cache entry was evicted early (file vanished),
  5927. # clean up any stragglers here to avoid leaking disk on retries.
  5928. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5929. if temp_path and temp_path.exists() and cached_now != temp_path:
  5930. temp_path.unlink()
  5931. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5932. _TIMELAPSE_DIRECTORIES = ("/timelapse", "/timelapse/video", "/record", "/recording")
  5933. # A baseline that could not be read at print start is read again on this
  5934. # schedule while the print runs (#3412). The printer writes the video only once
  5935. # the print has ended, so a reading taken mid-print is as good as one taken at
  5936. # the start. The interval is shorter than the FTPS handshake cool-off (300 s),
  5937. # which is what usually makes the card unreadable, so the first reading after
  5938. # it ends is not long behind; while the cool-off runs a round costs nothing, as
  5939. # no connection is opened. The cap bounds a print that never reports an end.
  5940. _TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS = 120.0
  5941. _TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS = 720
  5942. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5943. # tests can shrink them without waiting out real delays.
  5944. #
  5945. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  5946. # looking. Across 247 support bundles the attempt that found the video was #1
  5947. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  5948. # decaying one, which is the signature of a budget that expires while files are
  5949. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  5950. # prints make big videos and the printer writes them after the print ends, so
  5951. # the poll now runs for minutes and costs one FTP LIST per round.
  5952. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  5953. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  5954. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  5955. def _timelapse_scan_max_attempts() -> int:
  5956. """Round cap for the poll, derived from the wall-clock budget.
  5957. The deadline alone is not a sufficient bound: it assumes each round really
  5958. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5959. and an FTP list that fails immediately would otherwise spin against the
  5960. printer at full speed for the whole window. Whichever bound is reached
  5961. first ends the poll.
  5962. """
  5963. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5964. # A zero interval makes the wall-clock budget meaningless; fall back to
  5965. # the round count the production interval would have given.
  5966. return 32
  5967. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5968. async def _read_timelapse_baseline(printer) -> tuple[set[str], bool]:
  5969. """The video names on *printer*'s card, and whether the card was read.
  5970. ``_list_timelapse_videos`` answers ``[]`` when its connect fails rather
  5971. than raising, so a card behind the FTPS handshake cool-off, or one whose
  5972. listing timed out, is indistinguishable from one holding no videos.
  5973. Everywhere that only wants to know "is there a video yet" the difference
  5974. does not matter -- both mean "not yet, retry".
  5975. It matters where an empty listing is recorded as a *baseline*. Recording
  5976. "the card held nothing" for a card that was never read means every video on
  5977. it counts as new, and the completion scan then attaches a stale video to
  5978. this print and deletes it from the printer (#2957 follow-up, #3412). So an
  5979. empty listing is asked again here in a way that tells the two apart: the
  5980. card counts as read only when every directory walked answered, with a
  5981. listing or with "no such directory". One that failed may be the one
  5982. holding the videos.
  5983. """
  5984. from backend.app.services.bambu_ftp import ftps_handshake_blocked, list_files_result_async
  5985. files, _ = await _list_timelapse_videos(printer)
  5986. if files:
  5987. return {f.get("name", "") for f in files}, True
  5988. ip_address = getattr(printer, "ip_address", None)
  5989. printer_id = getattr(printer, "id", None)
  5990. if not ip_address:
  5991. return set(), True
  5992. # No card in the slot: nothing to read, and nothing a video could land on.
  5993. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5994. return set(), True
  5995. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  5996. if ftps_handshake_blocked(ip_address):
  5997. # Below any path: every remaining one would fail the same way.
  5998. return set(), False
  5999. listing = await list_files_result_async(
  6000. ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  6001. )
  6002. if not (listing.available or listing.missing):
  6003. return set(), False
  6004. videos = [
  6005. f
  6006. for f in listing.files
  6007. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  6008. ]
  6009. if videos:
  6010. return {f.get("name", "") for f in videos}, True
  6011. return set(), True
  6012. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  6013. """List video files from printer's timelapse directory.
  6014. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  6015. Returns (video_files, found_path) where video_files is a list of file dicts
  6016. and found_path is the directory where they were found, or ([], None).
  6017. An empty return does not distinguish "no videos" from "could not read the
  6018. card" — see :func:`_read_timelapse_baseline`, which the two baseline
  6019. callers use instead.
  6020. """
  6021. from backend.app.services.bambu_ftp import list_files_async
  6022. logger = logging.getLogger(__name__)
  6023. # No card in the slot means no /timelapse to walk — four connections that
  6024. # can only fail, on a path whose failures are swallowed and so would go on
  6025. # costing time silently forever (#2780).
  6026. #
  6027. # ``getattr`` rather than ``printer.id``: every dereference below happens
  6028. # inside the loop's own try/except, so a caller that passed something
  6029. # unexpected used to get an empty listing rather than an exception. Keep
  6030. # that, instead of making this gate the first thing that can raise here.
  6031. printer_id = getattr(printer, "id", None)
  6032. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  6033. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  6034. return [], None
  6035. for timelapse_path in _TIMELAPSE_DIRECTORIES:
  6036. try:
  6037. found_files = await list_files_async(
  6038. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  6039. )
  6040. if found_files:
  6041. video_files = [
  6042. f
  6043. for f in found_files
  6044. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  6045. ]
  6046. if video_files:
  6047. return video_files, timelapse_path
  6048. except Exception as e:
  6049. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  6050. continue
  6051. return [], None
  6052. async def _capture_timelapse_baseline_at_start(
  6053. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  6054. ) -> None:
  6055. """Snapshot the printer's timelapse directory at print start so the
  6056. completion-time scan can pick the new file by set-difference.
  6057. Must be called from every on_print_start path that proceeds to a real
  6058. print — both the new-archive branch and the expected-archive branch (which
  6059. queue / VP-dispatched prints take). Without a baseline,
  6060. _scan_for_timelapse_with_retries falls into its "take baseline now"
  6061. fallback that runs AFTER the new MP4 has already landed on the SD card,
  6062. so the new file ends up in the "baseline" set and no diff ever matches.
  6063. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  6064. unreliable — the snapshot-diff approach sidesteps that entirely.
  6065. When ``archive_id`` is known the baseline is also written to the archive
  6066. row, so it survives a restart and the manual "Scan for Timelapse" button
  6067. can run the same diff instead of falling back to clock-based matching
  6068. (#2704). Only baselines taken at print start are persisted — one taken at
  6069. completion already contains the new video and would poison a later scan.
  6070. """
  6071. names: set[str] | None = None
  6072. unread = False
  6073. _timelapse_baselines_unread.discard(printer_id)
  6074. try:
  6075. names, read = await _read_timelapse_baseline(printer)
  6076. unread = not read
  6077. _timelapse_baselines[printer_id] = names
  6078. if unread:
  6079. # Recorded anyway, deliberately, and marked. An empty baseline taken
  6080. # off a card we could not read is not evidence, but it is still the
  6081. # right *default*: Bambuddy deletes each video from the printer once
  6082. # it is attached, so the usual card holds exactly one video at
  6083. # completion and an empty baseline resolves it. Persisting NULL
  6084. # instead would send completion to take its own snapshot, by which
  6085. # point this print's video is on the card and would be swallowed by
  6086. # it. The mark keeps the scan from choosing between several videos
  6087. # (#3412), and the card is read again while the print runs.
  6088. _timelapse_baselines_unread.add(printer_id)
  6089. logger.warning(
  6090. "[TIMELAPSE] Baseline for printer %s taken while its card could not be read — "
  6091. "treating it as empty for now and reading it again during the print",
  6092. printer_id,
  6093. )
  6094. logger.info(
  6095. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  6096. len(names),
  6097. printer_id,
  6098. )
  6099. except Exception as e:
  6100. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  6101. run_started_at: datetime | None = None
  6102. run_id: int | None = None
  6103. if archive_id is not None:
  6104. try:
  6105. async with async_session() as db:
  6106. from backend.app.models.archive import PrintArchive
  6107. from backend.app.services.print_log import open_run_on_printer
  6108. archive = await db.get(PrintArchive, archive_id)
  6109. if archive is not None:
  6110. # Written even when the listing failed, and then as NULL. A
  6111. # reprint reuses the archive row, so leaving the previous
  6112. # run's baseline in place would have the scan diff this print
  6113. # against the state of the printer before the *last* one —
  6114. # and a stale baseline reads as authoritative, where NULL
  6115. # correctly falls back to a fresh snapshot.
  6116. baseline = sorted(names) if names is not None else None
  6117. archive.timelapse_baseline = baseline
  6118. archive.timelapse_baseline_unread = unread
  6119. run_started_at = archive.started_at
  6120. # And on the run this print opened, whose scan reads it:
  6121. # the archive's is its latest start's, which another plate
  6122. # of it on another printer can take over.
  6123. run = await open_run_on_printer(db, printer_id)
  6124. if run is not None and run.archive_id == archive_id:
  6125. run.timelapse_baseline = baseline
  6126. run.timelapse_baseline_unread = unread
  6127. run_id = run.id
  6128. await db.commit()
  6129. except Exception as e:
  6130. # In-memory baseline still covers the normal completion path.
  6131. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  6132. if unread and names is not None:
  6133. spawn_background_task(
  6134. _reread_unread_timelapse_baseline(printer_id, names, archive_id, run_started_at, run_id),
  6135. name=f"reread-timelapse-baseline-{printer_id}",
  6136. )
  6137. # Before the print has ended there is no video yet: a long PREPARE (heating,
  6138. # levelling) counts as much as the print itself.
  6139. _BASELINE_REREAD_STATES = _ACTIVE_PRINT_STATES | {"PREPARE", "SLICING"}
  6140. def _schedule_timelapse_scan(
  6141. archive_id: int, printer_id: int, *, plate_id: int | None, run_id: int | None = None
  6142. ) -> None:
  6143. """Start the completion scan with the print-start baseline: the names, and
  6144. whether they were taken off a card that could not be read. Taking them
  6145. ends any re-read still running for it. ``run_id`` is the print that
  6146. ended, whose video it looks for."""
  6147. unread = printer_id in _timelapse_baselines_unread
  6148. _timelapse_baselines_unread.discard(printer_id)
  6149. baseline = _timelapse_baselines.pop(printer_id, None)
  6150. from backend.app.services import archive_work
  6151. # Held while it looks: it finds its print by the archive's id, which a
  6152. # merge would move away (archive redesign P2).
  6153. spawn_background_task(
  6154. archive_work.held_while(
  6155. archive_id,
  6156. _scan_for_timelapse_with_retries(
  6157. archive_id, baseline, plate_id=plate_id, baseline_unread=unread, run_id=run_id
  6158. ),
  6159. ),
  6160. name=f"scan-timelapse-{archive_id}",
  6161. )
  6162. def _unread_baseline_round(printer_id: int, names: set[str]) -> bool | None:
  6163. """Whether to read an unread baseline again now: True to read, None to
  6164. skip this round, False once it is over -- the print it was taken for is
  6165. no longer the one on the printer, has stopped printing, or the baseline
  6166. has been read.
  6167. ``names`` is the very set object recorded at print start: completion pops
  6168. it and the next print records a new one, so identity marks the run. A
  6169. printer that is momentarily disconnected says nothing about its print, so
  6170. that only skips the round.
  6171. """
  6172. if _timelapse_baselines.get(printer_id) is not names or printer_id not in _timelapse_baselines_unread:
  6173. return False
  6174. state = printer_manager.get_status(printer_id)
  6175. if state is None or not state.connected:
  6176. return None
  6177. return state.state in _BASELINE_REREAD_STATES
  6178. async def _reread_unread_timelapse_baseline(
  6179. printer_id: int,
  6180. names: set[str],
  6181. archive_id: int | None,
  6182. run_started_at: datetime | None,
  6183. run_id: int | None = None,
  6184. ) -> None:
  6185. """Read again a print-start baseline the card could not give (#3412).
  6186. The printer writes the video only once the print has ended, so the card
  6187. read at any point during the print holds exactly what it held at the
  6188. start. Each round stops once the print is no longer the one the baseline
  6189. was taken for or has stopped printing, and checks that again after the
  6190. listing returns, before anything is recorded.
  6191. """
  6192. from backend.app.models.archive import PrintArchive
  6193. from backend.app.models.printer import Printer
  6194. from backend.app.services.print_log import run_of
  6195. logger = logging.getLogger(__name__)
  6196. for _ in range(_TIMELAPSE_BASELINE_REREAD_MAX_ATTEMPTS):
  6197. await asyncio.sleep(_TIMELAPSE_BASELINE_REREAD_INTERVAL_SECONDS)
  6198. now = _unread_baseline_round(printer_id, names)
  6199. if now is False:
  6200. return
  6201. if now is None:
  6202. continue
  6203. try:
  6204. async with async_session() as db:
  6205. printer = await db.get(Printer, printer_id)
  6206. if printer is None:
  6207. return
  6208. fresh, read = await _read_timelapse_baseline(printer)
  6209. except Exception as e:
  6210. logger.debug("[TIMELAPSE] Re-reading the baseline for printer %s failed: %s", printer_id, e)
  6211. continue
  6212. if not read:
  6213. continue
  6214. now = _unread_baseline_round(printer_id, names)
  6215. if now is False:
  6216. return
  6217. if now is None:
  6218. # The printer dropped off while the listing was out, so nothing
  6219. # says it did not end meanwhile: keep the reading for a round that
  6220. # can vouch for it.
  6221. continue
  6222. names.update(fresh)
  6223. _timelapse_baselines_unread.discard(printer_id)
  6224. logger.info(
  6225. "[TIMELAPSE] Baseline for printer %s read during the print: %s video files",
  6226. printer_id,
  6227. len(fresh),
  6228. )
  6229. if archive_id is None:
  6230. return
  6231. try:
  6232. async with async_session() as db:
  6233. archive = await db.get(PrintArchive, archive_id)
  6234. # Only the run it was taken for: by now the row can belong to a
  6235. # reprint, whose baseline is its own.
  6236. if archive is not None and archive.started_at == run_started_at and archive.timelapse_baseline_unread:
  6237. archive.timelapse_baseline = sorted(names)
  6238. archive.timelapse_baseline_unread = False
  6239. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6240. if run is not None and run.timelapse_baseline_unread:
  6241. run.timelapse_baseline = sorted(names)
  6242. run.timelapse_baseline_unread = False
  6243. await db.commit()
  6244. except Exception as e:
  6245. # The in-memory baseline is read now, which covers completion
  6246. # unless Bambuddy restarts first.
  6247. logger.warning("[TIMELAPSE] Failed to persist the re-read baseline for archive %s: %s", archive_id, e)
  6248. return
  6249. async def _timelapse_still_wanted(db, archive, run_id: int | None, run_started_at: datetime | None) -> bool:
  6250. """Whether the print a timelapse is for still has none: its run, by id,
  6251. exists without a video and no later print took over (``superseded``).
  6252. Without a run, the archive is still on that print's start (a newer run's
  6253. video is its own) and has none."""
  6254. from backend.app.services.print_log import run_of, superseded
  6255. if run_id is not None:
  6256. run = await run_of(db, archive.id, run_id)
  6257. return run is not None and run.timelapse_path is None and not await superseded(db, run)
  6258. return archive.timelapse_path is None and archive.started_at == run_started_at
  6259. async def _scan_for_timelapse_with_retries(
  6260. archive_id: int,
  6261. baseline_names: set[str] | None = None,
  6262. *,
  6263. plate_id: int | None = None,
  6264. baseline_unread: bool = False,
  6265. run_id: int | None = None,
  6266. ):
  6267. """Poll the printer for this print's timelapse and attach it.
  6268. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  6269. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  6270. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  6271. (#2704). Comparing the current listing against the set of filenames that
  6272. existed when the print started needs no clock at all, because the printer
  6273. writes the video only once the print has ended.
  6274. Baseline precedence: the caller's in-memory set, then the one persisted on
  6275. the archive at print start, then a snapshot taken now. The last of those is
  6276. a poor substitute — by completion the new video may already be on the card,
  6277. in which case it lands in the "baseline" and no diff can ever match — but it
  6278. is all that is available for a print that began before Bambuddy started.
  6279. On success the video is deleted from the printer, which keeps ``/timelapse``
  6280. down to the unclaimed files and makes the next diff unambiguous.
  6281. ``baseline_unread`` marks the caller's baseline as taken off a card that
  6282. could not be read; a stored one carries the same mark on the archive.
  6283. ``run_id`` is the print that ended (archive redesign): the video is that
  6284. run's, the stored baseline is the run's own, and the poll ends once the
  6285. run has a video or is gone. Without it (no run was written), the run is
  6286. whichever the archive is on when the scan starts.
  6287. """
  6288. from backend.app.services.print_log import run_of
  6289. logger = logging.getLogger(__name__)
  6290. # Cleared when the baseline was taken off a card we could not read, so the
  6291. # attach step refuses to choose between several candidates (#2957, #3412).
  6292. baseline_trusted = True
  6293. # --- Phase 1: establish the baseline -------------------------------------
  6294. try:
  6295. async with async_session() as db:
  6296. from backend.app.models.printer import Printer
  6297. service = ArchiveService(db)
  6298. archive = await service.get_archive(archive_id)
  6299. if not archive:
  6300. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  6301. return
  6302. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6303. if run_id is not None and run is None:
  6304. logger.info("[TIMELAPSE] Run %s of archive %s is gone, aborting", run_id, archive_id)
  6305. return
  6306. if run.timelapse_path if run is not None else archive.timelapse_path:
  6307. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  6308. return
  6309. # The printer the print ran on: plates of one archive can print on
  6310. # two printers, and the archive's is the one that started last.
  6311. scan_printer_id = run.printer_id if run is not None and run.printer_id else archive.printer_id
  6312. if not scan_printer_id:
  6313. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  6314. return
  6315. # The run this scan is for. The archive row passes to a newer run
  6316. # when it prints again (the next plate, a reprint), and that run's
  6317. # video is its own.
  6318. run_started_at = run.started_at if run is not None else archive.started_at
  6319. # The baseline stored for it: the run's own, else the archive's
  6320. # while that is still this run's start's.
  6321. stored_baseline, stored_unread = None, False
  6322. if run is not None and run.timelapse_baseline is not None:
  6323. stored_baseline, stored_unread = run.timelapse_baseline, bool(run.timelapse_baseline_unread)
  6324. elif archive.started_at == run_started_at:
  6325. stored_baseline, stored_unread = archive.timelapse_baseline, archive.timelapse_baseline_unread
  6326. if baseline_names is not None and baseline_unread and stored_baseline is not None and not stored_unread:
  6327. # The card was read at print start, and the in-memory copy is
  6328. # one Bambuddy took after a restart off a card it could not
  6329. # read: the stored one is this run's and is evidence.
  6330. baseline_names = set(stored_baseline)
  6331. logger.info(
  6332. "[TIMELAPSE] Using stored baseline over an unread one: %s existing video files for archive %s",
  6333. len(baseline_names),
  6334. archive_id,
  6335. )
  6336. elif baseline_names is not None:
  6337. baseline_trusted = not baseline_unread
  6338. logger.info(
  6339. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  6340. len(baseline_names),
  6341. archive_id,
  6342. )
  6343. elif stored_baseline is not None:
  6344. # Persisted at print start — survives a restart mid-print.
  6345. baseline_names = set(stored_baseline)
  6346. baseline_trusted = not stored_unread
  6347. logger.info(
  6348. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  6349. len(baseline_names),
  6350. archive_id,
  6351. )
  6352. else:
  6353. result = await db.execute(select(Printer).where(Printer.id == scan_printer_id))
  6354. printer = result.scalar_one_or_none()
  6355. if not printer:
  6356. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  6357. return
  6358. baseline_names, baseline_trusted = await _read_timelapse_baseline(printer)
  6359. if not baseline_trusted:
  6360. # The card is unreadable at the one moment a baseline has to
  6361. # be taken, so the empty listing means "we never looked",
  6362. # not "these are all new". Carry on with it anyway — the
  6363. # usual card holds exactly one video, which resolves
  6364. # correctly — but stop the poll from *choosing* between
  6365. # several, which is how a stale video got attached to this
  6366. # print and then deleted off the printer (#2957 follow-up).
  6367. logger.warning(
  6368. "[TIMELAPSE] Baseline for archive %s taken while printer %s's card could not be "
  6369. "read. A single new video still resolves; several will not be guessed between — "
  6370. "use Scan for Timelapse to pick one by hand",
  6371. archive_id,
  6372. scan_printer_id,
  6373. )
  6374. logger.info(
  6375. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  6376. len(baseline_names),
  6377. archive_id,
  6378. )
  6379. except Exception as e:
  6380. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  6381. return
  6382. # --- Phase 2: poll for a file that was not there when the print began -----
  6383. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  6384. max_attempts = _timelapse_scan_max_attempts()
  6385. seen_names: set[str] = set()
  6386. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  6387. attempt = 0
  6388. while True:
  6389. await asyncio.sleep(delay)
  6390. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  6391. attempt += 1
  6392. try:
  6393. from backend.app.models.printer import Printer
  6394. # Read phase: fetch archive + printer in a short session and release
  6395. # the pooled connection BEFORE the FTP list/download below. Holding it
  6396. # across the FTP round-trips left one connection idle-in-transaction per
  6397. # in-flight scan (issue #2572).
  6398. async with async_session() as db:
  6399. from backend.app.services.print_log import claimed_timelapse_stems
  6400. service = ArchiveService(db)
  6401. archive = await service.get_archive(archive_id)
  6402. if not archive:
  6403. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  6404. return
  6405. if not await _timelapse_still_wanted(db, archive, run_id, run_started_at):
  6406. logger.info(
  6407. "[TIMELAPSE] Archive %s has its video or is printing again, stopping the run's poll",
  6408. archive_id,
  6409. )
  6410. return
  6411. result = await db.execute(select(Printer).where(Printer.id == scan_printer_id))
  6412. printer = result.scalar_one_or_none()
  6413. if not printer:
  6414. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  6415. return
  6416. claimed = await claimed_timelapse_stems(db, scan_printer_id, archive_id=archive_id, run_id=run_id)
  6417. # I/O phase (no DB connection held): FTP list + download.
  6418. video_files, found_path = await _list_timelapse_videos(printer)
  6419. # The poll can run for dozens of rounds, so only narrate a round
  6420. # that saw something change. Repeating the whole listing every 30 s
  6421. # would bury the one interesting line in the support bundle.
  6422. names_now = {f.get("name", "") for f in video_files}
  6423. changed = attempt == 1 or names_now != seen_names
  6424. seen_names = names_now
  6425. speak = logger.info if changed else logger.debug
  6426. if video_files:
  6427. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  6428. if changed:
  6429. for f in video_files[:5]:
  6430. logger.info("[TIMELAPSE] - %s", f.get("name"))
  6431. attached = await _attach_first_unclaimed_timelapse(
  6432. archive_id,
  6433. printer,
  6434. video_files,
  6435. baseline_names,
  6436. claimed,
  6437. attempt,
  6438. logger,
  6439. quiet=not changed,
  6440. require_unambiguous=not baseline_trusted,
  6441. plate_id=plate_id,
  6442. run_started_at=run_started_at,
  6443. run_id=run_id,
  6444. )
  6445. if attached:
  6446. return
  6447. else:
  6448. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  6449. except Exception as e:
  6450. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  6451. if attempt >= max_attempts or time.monotonic() >= deadline:
  6452. break
  6453. # No name-match fallback: it compared the print name against the filename,
  6454. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  6455. # bundles it fired 159 times and matched zero times, so all it added was a
  6456. # misleading log line before giving up.
  6457. logger.warning(
  6458. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  6459. archive_id,
  6460. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  6461. )
  6462. async def _attach_layer_timelapse(
  6463. archive_id: int,
  6464. timelapse_path: Path,
  6465. plate_id: int | None,
  6466. run_started_at: datetime | None,
  6467. run_id: int | None = None,
  6468. ) -> None:
  6469. """Attach the external camera's stitched timelapse to the archive.
  6470. The camera's video is the one the user set up in Bambuddy, so it wins
  6471. over the printer's own when both are on: it replaces the printer's video
  6472. (usually there first; stitching takes minutes) and that file is deleted,
  6473. leaving nothing in the archive folder unreferenced. ``run_started_at`` is
  6474. the run the frames were taken for: when the archive is printing again by
  6475. the time the stitch is done, the video is not the new run's and is
  6476. dropped. The stitched file is a temporary either way.
  6477. ``run_id`` is the print that ended (archive redesign): the video is that
  6478. run's and replaces that run's printer video; the poll by start above is
  6479. for a print without a run.
  6480. """
  6481. from backend.app.services.print_log import run_of, superseded
  6482. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  6483. logger = logging.getLogger(__name__)
  6484. try:
  6485. async with async_session() as db:
  6486. service = ArchiveService(db)
  6487. archive = await service.get_archive(archive_id)
  6488. if archive is None:
  6489. return
  6490. run = await run_of(db, archive_id, run_id) if run_id is not None else None
  6491. if run_id is not None and run is None:
  6492. logger.info("[LAYER-TL] Run %s of archive %s is gone; dropping its layer timelapse", run_id, archive_id)
  6493. return
  6494. if run is not None and await superseded(db, run):
  6495. logger.info(
  6496. "[LAYER-TL] A later print took over run %s of archive %s; dropping its layer timelapse",
  6497. run_id,
  6498. archive_id,
  6499. )
  6500. return
  6501. if run is None and archive.started_at != run_started_at:
  6502. logger.info(
  6503. "[LAYER-TL] Archive %s is printing again; dropping the previous run's layer timelapse", archive_id
  6504. )
  6505. return
  6506. holder = run if run is not None else archive
  6507. replaced = holder.timelapse_path
  6508. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  6509. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  6510. if not await service.attach_timelapse(
  6511. archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=plate_id, run_id=run_id
  6512. ):
  6513. return
  6514. attached = holder.timelapse_path
  6515. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  6516. if replaced and replaced != attached:
  6517. try:
  6518. old = safe_join_under(app_settings.base_dir, replaced, http=False)
  6519. except PathTraversalError:
  6520. return
  6521. await asyncio.to_thread(old.unlink, missing_ok=True)
  6522. logger.info("[LAYER-TL] Replaced the printer's timelapse %s on archive %s", replaced, archive_id)
  6523. finally:
  6524. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  6525. # ``run_started_at`` not given: attach whichever run the archive is on.
  6526. _ANY_RUN = object()
  6527. async def _attach_first_unclaimed_timelapse(
  6528. archive_id: int,
  6529. printer,
  6530. video_files: list[dict],
  6531. baseline_names: set[str],
  6532. claimed: set[str],
  6533. attempt: int,
  6534. logger: logging.Logger,
  6535. *,
  6536. quiet: bool = False,
  6537. require_unambiguous: bool = False,
  6538. plate_id: int | None = None,
  6539. run_started_at: datetime | None | object = _ANY_RUN,
  6540. run_id: int | None = None,
  6541. ) -> bool:
  6542. """Download and attach the one video that belongs to this print.
  6543. A candidate is any file absent from the print-start baseline. More than one
  6544. can qualify when a previous print's video landed late, after this print's
  6545. baseline was taken — those are filtered out by name, because they are
  6546. already attached to another archive. Sorting the candidates instead would
  6547. mean sorting on mtime or on the filename timestamp, both of which come from
  6548. the printer's unsynced clock.
  6549. Returns True once a video is attached. The printer's copy is deleted only
  6550. after the attach succeeds on bytes whose length matched the listing.
  6551. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  6552. already seen this exact listing — the poll runs for many rounds and only the
  6553. rounds where something changed are worth an INFO line.
  6554. """
  6555. from backend.app.services.bambu_ftp import (
  6556. DownloadDeadlineExceeded,
  6557. delete_archived_timelapse,
  6558. download_file_bytes_async,
  6559. remote_file_settled,
  6560. )
  6561. speak = logger.debug if quiet else logger.info
  6562. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  6563. if not new_files:
  6564. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  6565. return False
  6566. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  6567. if not candidates:
  6568. speak(
  6569. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  6570. attempt,
  6571. len(new_files),
  6572. )
  6573. return False
  6574. if len(candidates) > 1:
  6575. if require_unambiguous:
  6576. # The baseline is not evidence -- it was taken off a card that could
  6577. # not be read -- so "new since the baseline" does not narrow these
  6578. # down at all. Taking the first would attach an arbitrary video to
  6579. # this print and then delete it from the printer.
  6580. logger.warning(
  6581. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  6582. "leaving all of them on the printer for manual selection",
  6583. attempt,
  6584. len(candidates),
  6585. ", ".join(str(f.get("name")) for f in candidates),
  6586. )
  6587. return False
  6588. logger.warning(
  6589. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  6590. "the rest stay on the printer for manual selection",
  6591. attempt,
  6592. len(candidates),
  6593. ", ".join(str(f.get("name")) for f in candidates),
  6594. )
  6595. target = candidates[0]
  6596. file_name = str(target.get("name") or "") # every listed entry has one
  6597. remote_path = target.get("path") or f"/timelapse/{file_name}"
  6598. logger.info(
  6599. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  6600. attempt,
  6601. file_name,
  6602. archive_id,
  6603. )
  6604. # The listing always carries a size (`list_files` skips entries it can't
  6605. # parse), but read it explicitly: the delete below is destructive and must
  6606. # depend on a size we actually had, not on one we hoped was there.
  6607. expected_size = target.get("size")
  6608. try:
  6609. timelapse_data = await download_file_bytes_async(
  6610. printer.ip_address,
  6611. printer.access_code,
  6612. remote_path,
  6613. printer_model=printer.model,
  6614. expected_size=expected_size,
  6615. )
  6616. except DownloadDeadlineExceeded:
  6617. # Too slow for its size this round; the printer keeps its copy.
  6618. timelapse_data = None
  6619. if not timelapse_data:
  6620. # Short or failed transfer. The printer keeps its copy, so the next
  6621. # round can try again — which is exactly why the delete below is
  6622. # gated on a verified download.
  6623. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  6624. return False
  6625. # The length check above proves we got what the listing said, not that the
  6626. # printer had finished writing. A video still being written can be listed
  6627. # short, served short, and pass — so confirm it has stopped growing before
  6628. # committing to it and deleting the original (#2704).
  6629. if not await remote_file_settled(
  6630. printer.ip_address,
  6631. printer.access_code,
  6632. remote_path,
  6633. len(timelapse_data),
  6634. printer_model=printer.model,
  6635. ):
  6636. return False
  6637. # Write phase: attach in a fresh short-lived session. The download took a
  6638. # while: by now the archive may have its video, or be printing again for a
  6639. # newer run, whose video this is not. Then nothing is attached or deleted,
  6640. # and the poll ends (True).
  6641. async with async_session() as db:
  6642. service = ArchiveService(db)
  6643. if run_id is not None or run_started_at is not _ANY_RUN:
  6644. current = await service.get_archive(archive_id)
  6645. started = None if run_started_at is _ANY_RUN else cast("datetime | None", run_started_at)
  6646. if current is None or not await _timelapse_still_wanted(db, current, run_id, started):
  6647. logger.info(
  6648. "[TIMELAPSE] Archive %s moved on during the download (video attached or printing again); "
  6649. "%s stays on the printer",
  6650. archive_id,
  6651. file_name,
  6652. )
  6653. return True
  6654. success = await service.attach_timelapse(
  6655. archive_id, timelapse_data, file_name, plate_id=plate_id, run_id=run_id
  6656. )
  6657. if not success:
  6658. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  6659. return False
  6660. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  6661. await delete_archived_timelapse(
  6662. printer.ip_address,
  6663. printer.access_code,
  6664. remote_path,
  6665. verified=expected_size is not None,
  6666. printer_model=printer.model,
  6667. printer_name=printer.name,
  6668. )
  6669. return True
  6670. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  6671. # module-level so tests can monkeypatch them down to ~0 without timing out.
  6672. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  6673. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  6674. # How long the *background* upgrade keeps waiting after the notification has
  6675. # already gone out (#2704 follow-up). The short bound above exists so a slow
  6676. # printer can't hold up the print-complete notification; this one exists so the
  6677. # archive still ends up with the better frame afterwards.
  6678. #
  6679. # Measured across 261 attaches in the support bundles, the video lands a median
  6680. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  6681. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  6682. # was 546s. Every other model was inside 26s. The long budget is therefore
  6683. # almost entirely for P1-series users; on everything else the short wait already
  6684. # wins and this task never runs.
  6685. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  6686. async def _capture_finish_photo_from_timelapse(
  6687. archive_id: int,
  6688. archive_dir: Path,
  6689. timeout: float | None = None,
  6690. rotation: int = 0,
  6691. run_id: int | None = None,
  6692. ) -> tuple[str | None, bool]:
  6693. """Wait for the per-print timelapse to land on the archive and extract its
  6694. last frame as the finish photo (#1397).
  6695. Bambu firmware stops timelapse recording after the toolhead parks but
  6696. before the bed-drop end-gcode runs, so the last frame frames the finished
  6697. print correctly. A live camera grab at gcode_state=FINISH captures the
  6698. bed already lowered.
  6699. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  6700. ``archive.timelapse_path`` when the file lands. This function polls for
  6701. that field.
  6702. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  6703. the wait ran out with no video on the archive yet — i.e. the video may
  6704. still be coming and a later attempt could succeed. It is False when the
  6705. video landed (whether or not extraction worked), because in that case
  6706. waiting longer changes nothing. The caller uses that to decide between
  6707. falling back permanently and scheduling a background upgrade.
  6708. ``rotation`` is the printer's camera_rotation, applied to the extracted
  6709. still (#2708) so this source agrees with every other finish-photo source.
  6710. The archived video itself is the printer's own file and is left alone —
  6711. rotating it would mean re-encoding it.
  6712. ``run_id`` is the print that ended: its own video is the one waited for,
  6713. not the archive's, which can be another plate's.
  6714. """
  6715. import uuid
  6716. from backend.app.models.archive import PrintArchive
  6717. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  6718. from backend.app.services.print_log import run_of
  6719. logger = logging.getLogger(__name__)
  6720. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  6721. deadline = asyncio.get_event_loop().time() + budget
  6722. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  6723. while True:
  6724. async with async_session() as db:
  6725. if run_id is not None:
  6726. run = await run_of(db, archive_id, run_id)
  6727. timelapse_relpath = run.timelapse_path if run else None
  6728. else:
  6729. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6730. archive = result.scalar_one_or_none()
  6731. timelapse_relpath = archive.timelapse_path if archive else None
  6732. if timelapse_relpath:
  6733. video_path = app_settings.base_dir / timelapse_relpath
  6734. if video_path.exists() and video_path.stat().st_size > 0:
  6735. photos_dir = archive_dir / "photos"
  6736. photos_dir.mkdir(parents=True, exist_ok=True)
  6737. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6738. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6739. output_path = photos_dir / filename
  6740. if await extract_video_last_frame(video_path, output_path):
  6741. await apply_camera_rotation_to_file(output_path, rotation, logger)
  6742. logger.info(
  6743. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  6744. video_path.name,
  6745. archive_id,
  6746. )
  6747. return filename, False
  6748. logger.warning(
  6749. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  6750. video_path.name,
  6751. archive_id,
  6752. )
  6753. return None, False
  6754. if asyncio.get_event_loop().time() >= deadline:
  6755. logger.info(
  6756. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  6757. archive_id,
  6758. budget,
  6759. )
  6760. return None, True
  6761. await asyncio.sleep(poll_interval)
  6762. async def _upgrade_finish_photo_from_timelapse(
  6763. archive_id: int, archive_dir: Path, rotation: int = 0, run_id: int | None = None
  6764. ) -> None:
  6765. """Add the timelapse's last frame to an archive after the fact (#2704).
  6766. The print-complete notification waits only ~60s for the video, because
  6767. holding a notification for minutes is worse than sending it with a live
  6768. camera grab. On a P1-series printer the video often lands well after that,
  6769. so the archive used to be stuck with the live grab — which is taken at
  6770. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  6771. the worse photo of the two.
  6772. This keeps waiting in the background and, when the video arrives, extracts
  6773. the frame and puts it *first* in the archive's photo list, so opening the
  6774. gallery shows it. The live grab is deliberately kept: the notification that
  6775. already went out links to that exact file, and deleting it would leave a
  6776. broken image in Discord or Telegram. ``run_id`` is the print it is for,
  6777. whose list leads with it too.
  6778. """
  6779. from backend.app.services.print_log import add_run_photo, run_of
  6780. logger = logging.getLogger(__name__)
  6781. filename, _ = await _capture_finish_photo_from_timelapse(
  6782. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation, run_id=run_id
  6783. )
  6784. if not filename:
  6785. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  6786. return
  6787. try:
  6788. async with async_session() as db:
  6789. from backend.app.models.archive import PrintArchive
  6790. archive = await db.get(PrintArchive, archive_id)
  6791. if archive is None:
  6792. return
  6793. photos = list(archive.photos or [])
  6794. if filename in photos:
  6795. return
  6796. # Front of the list: PhotoGalleryModal opens at index 0.
  6797. archive.photos = [filename, *photos]
  6798. add_run_photo(await run_of(db, archive_id, run_id) if run_id is not None else None, filename, first=True)
  6799. await db.commit()
  6800. except Exception as e:
  6801. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  6802. return
  6803. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  6804. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  6805. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  6806. """Put the filament-attribution context back after a restart mid-print.
  6807. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  6808. both die with the process. The print keeps running, so at completion the
  6809. tracker would fall back to whatever the printer reports *now* — and AMS
  6810. filament backup makes "now" the substitute tray, charging the whole print
  6811. to the spool that only finished it.
  6812. The persisted row is only trusted when its print name still matches what
  6813. the printer says it is running: a row left behind by a completion we never
  6814. saw must not attach itself to the next print.
  6815. """
  6816. try:
  6817. from backend.app.api.routes.settings import get_setting
  6818. from backend.app.services.usage_tracker import (
  6819. clear_persisted_session,
  6820. get_persisted_ams_mapping,
  6821. get_persisted_print_name,
  6822. get_persisted_spool_change_log,
  6823. restore_session,
  6824. )
  6825. persisted_name = await get_persisted_print_name(db, printer_id)
  6826. current_name = (state.subtask_name or "").strip()
  6827. if persisted_name and current_name and persisted_name.strip() != current_name:
  6828. logger.info(
  6829. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  6830. printer_id,
  6831. persisted_name,
  6832. current_name,
  6833. )
  6834. await clear_persisted_session(db, printer_id)
  6835. # Fall through to seeding: the print on the printer is real, it just
  6836. # isn't the one the row described.
  6837. persisted_log = None
  6838. else:
  6839. # Spoolman users get the tray-change log back but no in-memory
  6840. # session — see ``on_print_start`` on why that dict is load-bearing
  6841. # for the remain%-sync guard.
  6842. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6843. persisted_log = await restore_session(
  6844. db,
  6845. printer_id,
  6846. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  6847. )
  6848. # The slot pills (#1762) read the mapping captured from the print
  6849. # command, which dies with the process as well. One this process
  6850. # has captured since is newer.
  6851. if state.print_ams_mapping is None:
  6852. state.print_ams_mapping = await get_persisted_ams_mapping(db, printer_id)
  6853. # Spools swapped on a tray before the restart (#3325); anything this
  6854. # process has recorded since goes after them.
  6855. persisted_swaps = await get_persisted_spool_change_log(db, printer_id)
  6856. if persisted_swaps:
  6857. seen = getattr(state, "spool_change_log", None) or []
  6858. state.spool_change_log = persisted_swaps + [item for item in seen if item not in persisted_swaps]
  6859. if persisted_log:
  6860. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  6861. # Anything this process already observed goes after the persisted
  6862. # history — the log is ordered by layer, and a fresh process can
  6863. # only have seen changes from later in the print.
  6864. for entry in state.tray_change_log or []:
  6865. if tuple(entry) not in restored:
  6866. restored.append(tuple(entry))
  6867. state.tray_change_log = restored
  6868. tray_now = state.tray_now
  6869. if 0 <= tray_now <= 254:
  6870. if not state.tray_change_log:
  6871. # No persisted history — a print that started before this build,
  6872. # or before the row existed. Seed with the tray feeding right
  6873. # now so the remainder of the print is at least attributable to
  6874. # the right spool.
  6875. state.tray_change_log = [(tray_now, state.layer_num)]
  6876. logger.info(
  6877. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  6878. printer_id,
  6879. tray_now,
  6880. state.layer_num,
  6881. )
  6882. # The tray handler updates ``last_loaded_tray`` on every push
  6883. # regardless of whether it logged a change, so re-align it to avoid
  6884. # a duplicate entry on the next push. Only ever with a real tray:
  6885. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  6886. # 255" fallback, and writing 255 into it would defeat that.
  6887. state.last_loaded_tray = tray_now
  6888. except Exception:
  6889. # Never let attribution recovery cost the caller its timelapse
  6890. # baseline — that capture has to happen before the printer uploads
  6891. # the in-flight MP4 and there is no second chance at it.
  6892. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  6893. async def on_print_running_observed(printer_id: int, data: dict):
  6894. """Restart-recovery for a print that started before Bambuddy came up.
  6895. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  6896. after Bambuddy startup (#1304 guard, prevents duplicate archive
  6897. creation). This hook restores the persisted archive into ``_active_prints``
  6898. and captures the timelapse baseline that normally hangs off print start.
  6899. Fires once per session, in lieu of on_print_start when restart-recovery
  6900. kicks in. The printer doesn't upload the timelapse until after PRINT
  6901. COMPLETE, so a baseline captured any time during the print is still
  6902. pre-upload.
  6903. """
  6904. logger = logging.getLogger(__name__)
  6905. async with async_session() as db:
  6906. from backend.app.models.printer import Printer
  6907. state = printer_manager.get_status(printer_id)
  6908. if state is not None:
  6909. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  6910. if authorization is True:
  6911. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  6912. await _restore_usage_tracking_session(printer_id, state, db, logger)
  6913. await _restore_printable_objects(printer_id, state, db, logger)
  6914. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6915. printer = result.scalar_one_or_none()
  6916. if not printer:
  6917. logger.warning(
  6918. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  6919. printer_id,
  6920. )
  6921. return
  6922. # Avoid double-capture: ownership reconciliation above must still run when
  6923. # a baseline already exists, but the camera work itself is one-shot.
  6924. if printer_id in _timelapse_baselines:
  6925. logger.debug(
  6926. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  6927. printer_id,
  6928. )
  6929. return
  6930. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  6931. class _RunOfArchive:
  6932. """An archive as one of its runs printed it: the run's job id, start and
  6933. plate, the rest the archive's. What the reconcile judges and closes."""
  6934. def __init__(self, archive, run):
  6935. self._archive = archive
  6936. self.subtask_id = run.subtask_id
  6937. self.started_at = run.started_at
  6938. self.plate_id = run.plate_id if run.plate_id is not None else archive.plate_id
  6939. def __getattr__(self, name):
  6940. return getattr(self._archive, name)
  6941. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  6942. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  6943. against the printer's current MQTT state.
  6944. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  6945. COMPLETE events, typically a print finishing during an MQTT disconnect
  6946. window followed by a smart-plug power cycle):
  6947. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  6948. provably not running anymore — only branch that should fire under
  6949. normal disconnect-then-reconnect timing.
  6950. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  6951. firmware mints a fresh ``subtask_id`` for each print, including the
  6952. ghost replay it runs after a power cycle from a leftover SD file —
  6953. so a mismatch unambiguously means the in-DB archive is no longer
  6954. the print on the printer.
  6955. 3. Printer is running but ``subtask_name`` is empty. The printer
  6956. doesn't know what it's running; the archive's reference to it is
  6957. already broken.
  6958. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  6959. with matching subtask_id+subtask_name is left alone. The cost of a false
  6960. positive is a print closed while it still runs: the reconcile takes its
  6961. ``_active_prints`` entry and the archive is no longer ``printing``, so
  6962. the real PRINT COMPLETE later finds no archive to close (#1679). The
  6963. cost of a false negative is the ghost-print loop in #1542. What the
  6964. archive is closed as is ``_reconciled_outcome``'s call.
  6965. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  6966. MQTT has connected but the first ``push_status`` response hasn't been
  6967. applied yet — ``PrinterState`` is sitting on its construction defaults.
  6968. The reconcile caller in ``on_printer_status_change`` is already gated
  6969. on a real ``state.state``, so in normal operation this branch is
  6970. unreachable; it's kept as belt-and-braces for future callers and for
  6971. the narrow window where a partial state update could arrive
  6972. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  6973. ``not stale`` on degenerate input is strictly conservative: a real
  6974. stale archive will still be caught by the next push_status arriving
  6975. with terminal state.
  6976. """
  6977. current_state = (state.state or "").upper()
  6978. if current_state in ("", "UNKNOWN"):
  6979. # No real push_status yet — PrinterState defaults are not evidence.
  6980. return False, ""
  6981. if current_state in ("IDLE", "FINISH", "FAILED"):
  6982. return True, f"printer state {current_state}"
  6983. # Below here the printer is in a running / pre-running state (RUNNING /
  6984. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  6985. current_subtask_id = (state.subtask_id or "").strip()
  6986. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  6987. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  6988. current_subtask_name = (state.subtask_name or "").strip()
  6989. if not current_subtask_name:
  6990. return True, "printer subtask_name empty"
  6991. return False, ""
  6992. async def prime_kprofile_table(printer_id: int) -> int:
  6993. """Read the printer's calibration table once per connection.
  6994. The AMS slot card shows a K value per slot (#2854). On the printers whose
  6995. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  6996. report ``cali_idx`` and nothing else -- that number can only come from
  6997. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  6998. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  6999. backup, or the printer answering a query BambuStudio made on the report
  7000. topic we share. A Bambuddy that nobody visited showed a card with no K
  7001. values at all.
  7002. Only the diameters actually fitted are asked for, which is one request on a
  7003. single-nozzle printer and two on a dual. Probing the four sizes blind is
  7004. what the backup does, and it is both wasteful and the thing that used to
  7005. blank the table.
  7006. Returns the number of nozzles whose table was read.
  7007. """
  7008. client = printer_manager.get_client(printer_id)
  7009. state = printer_manager.get_status(printer_id)
  7010. if client is None or state is None or not state.connected:
  7011. return 0
  7012. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  7013. # ask once, and both entries are empty until the first push_status lands.
  7014. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  7015. if not diameters:
  7016. logging.getLogger(__name__).debug(
  7017. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  7018. printer_id,
  7019. )
  7020. return 0
  7021. primed = 0
  7022. for diameter in diameters:
  7023. try:
  7024. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  7025. except Exception as exc: # noqa: BLE001
  7026. # A printer that won't answer costs the card its K values, nothing
  7027. # more — never the connection this runs on the back of.
  7028. logging.getLogger(__name__).warning(
  7029. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  7030. )
  7031. continue
  7032. primed += 1
  7033. logging.getLogger(__name__).info(
  7034. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  7035. )
  7036. return primed
  7037. def _sd_files_in_use(state) -> set[str]:
  7038. """Names of the SD-card files the printer may be printing right now (#3009).
  7039. The post-print cleanup works out what to delete from the finished archive,
  7040. not from the printer. When reconciliation closes an old archive because the
  7041. printer has moved on to a new job, and that job is the same file reprinted
  7042. from the printer's screen, the cleanup would delete the file mid-print.
  7043. Empty unless the printer is busy: on an ordinary completion the state is
  7044. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  7045. name, a path or a URL depending on firmware, and some report only the
  7046. plate's G-code, so the job name is matched as well, in the same spellings
  7047. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  7048. ignores case.
  7049. """
  7050. def _text(value) -> str:
  7051. return value.strip() if isinstance(value, str) else ""
  7052. if state is None:
  7053. return set()
  7054. current_state = _text(getattr(state, "state", None)).upper()
  7055. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  7056. return set()
  7057. in_use: set[str] = set()
  7058. gcode_file = _text(getattr(state, "gcode_file", None))
  7059. if gcode_file:
  7060. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  7061. # both legal in a file name, and raises on some inputs.
  7062. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  7063. if name:
  7064. in_use.add(name.lower())
  7065. subtask_name = _text(getattr(state, "subtask_name", None))
  7066. if subtask_name:
  7067. for name in (subtask_name, subtask_name.replace(" ", "_")):
  7068. for ext in (".3mf", ".gcode"):
  7069. in_use.add(f"{name}{ext}".lower())
  7070. return in_use
  7071. def _reconciled_outcome(archive, state) -> str:
  7072. """What a stale archive is closed as at reconnect (#3310).
  7073. A print that ends while Bambuddy restarts is never seen to end: the new
  7074. MQTT client's first status is already FINISH, which is not a transition.
  7075. The printer keeps reporting the finished job's ``subtask_id`` until the
  7076. next print, so a matching id proves the FINISH or FAILED is this
  7077. archive's. Anything else -- IDLE, another job, an id of "0" (a print
  7078. started outside the cloud) or none -- says only that the print is over,
  7079. not how, and stays ``aborted``.
  7080. """
  7081. current_state = (state.state or "").upper()
  7082. if current_state not in ("FINISH", "FAILED"):
  7083. return "aborted"
  7084. archive_id = (archive.subtask_id or "").strip()
  7085. current_id = str(state.subtask_id or "").strip()
  7086. if archive_id in ("", "0") or archive_id != current_id:
  7087. return "aborted"
  7088. return "completed" if current_state == "FINISH" else "failed"
  7089. def _reconciled_end_time(archive, now: datetime, plate_id: int | None = None) -> datetime | None:
  7090. """When a print reconciled as completed most likely ended, or None (#3310).
  7091. The printer does not say when it finished, and the reconnect can be hours
  7092. later. Its start plus the slicer's estimate for the plate it printed,
  7093. never later than now, is the best guess; None when either is missing,
  7094. and the run then keeps no duration, as an aborted one does.
  7095. ``plate_id`` is the plate this run printed, from its queue job: a reprint
  7096. of another plate reuses the archive without changing ``archive.plate_id``.
  7097. """
  7098. started = archive.started_at
  7099. if not started:
  7100. return None
  7101. if started.tzinfo is None:
  7102. started = started.replace(tzinfo=timezone.utc)
  7103. plate = plate_id if plate_id is not None else archive.plate_id
  7104. estimate = None
  7105. if archive.file_path:
  7106. from backend.app.utils.threemf_tools import extract_print_time_from_3mf
  7107. full_path = (
  7108. app_settings.base_dir / archive.file_path
  7109. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7110. try:
  7111. estimate = extract_print_time_from_3mf(full_path, plate)
  7112. except Exception as exc: # noqa: BLE001
  7113. logging.getLogger(__name__).debug(
  7114. "Plate estimate for reconciled archive %s unreadable: %s", archive.id, exc
  7115. )
  7116. if plate is None and estimate != archive.print_time_seconds:
  7117. # Without a plate the first plate's estimate is read. The archive
  7118. # carries the sum over all plates (#1593), so a difference means
  7119. # several plates and no telling which one printed.
  7120. estimate = None
  7121. elif plate is None:
  7122. # Nothing to read the plate from; the archive's own estimate, as for
  7123. # a single-plate file.
  7124. estimate = archive.print_time_seconds
  7125. if not estimate or estimate <= 0:
  7126. return None
  7127. return min(started + timedelta(seconds=int(estimate)), now)
  7128. async def reconcile_stale_active_prints(printer_id: int) -> int:
  7129. """Synthesise ``on_print_complete`` for archives whose print can't be
  7130. running on the printer anymore.
  7131. Called once per MQTT (re)connection (from on_printer_status_change when
  7132. the connected edge flips False → True) and at Bambuddy startup (from
  7133. the FastAPI lifespan). Without this, a print that completes during a
  7134. disconnect window — followed by a smart-plug-driven power cycle — leaves
  7135. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  7136. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  7137. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  7138. power cycle until the operator notices (#1542 follow-up). Reconciliation
  7139. closes the loop by faking the missed PRINT COMPLETE — the existing
  7140. cleanup chain handles SD-file deletion, status updates, usage tracking,
  7141. and notifications.
  7142. The status is ``_reconciled_outcome``'s: ``completed`` or ``failed``
  7143. when the printer still reports the archive's own job as finished or
  7144. failed, ``aborted`` otherwise. Nothing corrects it later: the archive is
  7145. no longer ``printing``, so a later PRINT COMPLETE finds no archive, and
  7146. after a restart the printer's FINISH is not one (#3310).
  7147. Returns the number of archives reconciled.
  7148. """
  7149. state = printer_manager.get_status(printer_id)
  7150. if not state:
  7151. return 0
  7152. # Don't reconcile while disconnected — we'd be making a decision against
  7153. # stale cached state. The connected → reconcile edge handles this.
  7154. if not state.connected:
  7155. return 0
  7156. from backend.app.models.archive import PrintArchive
  7157. from backend.app.models.print_log import INCLUDE_OPEN_RUNS, RUN_OPEN, PrintLogEntry
  7158. reconciled = 0
  7159. async with async_session() as db:
  7160. # The prints on this printer Bambuddy saw start: their runs open here.
  7161. # The archive row is shared by every plate of a file, its printer, job
  7162. # and start the latest start's, so each is judged as its run.
  7163. open_runs = (
  7164. await db.scalars(
  7165. select(PrintLogEntry)
  7166. .where(PrintLogEntry.printer_id == printer_id, PrintLogEntry.status == RUN_OPEN)
  7167. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7168. )
  7169. ).all()
  7170. by_run = {
  7171. archive.id: archive
  7172. for archive in (
  7173. await db.scalars(
  7174. select(PrintArchive).where(
  7175. PrintArchive.id.in_([run.archive_id for run in open_runs if run.archive_id is not None])
  7176. )
  7177. )
  7178. ).all()
  7179. }
  7180. active: list = [_RunOfArchive(by_run[run.archive_id], run) for run in open_runs if run.archive_id in by_run]
  7181. # And as before runs were opened at the start: a printing archive of
  7182. # this printer with no run open anywhere (printing since before).
  7183. archives_with_open_runs = select(PrintLogEntry.archive_id).where(
  7184. PrintLogEntry.status == RUN_OPEN, PrintLogEntry.archive_id.is_not(None)
  7185. )
  7186. result = await db.execute(
  7187. select(PrintArchive)
  7188. .where(
  7189. PrintArchive.printer_id == printer_id,
  7190. PrintArchive.status == "printing",
  7191. PrintArchive.id.not_in(archives_with_open_runs),
  7192. )
  7193. .execution_options(**{INCLUDE_OPEN_RUNS: True})
  7194. )
  7195. active.extend(result.scalars().all())
  7196. if not active:
  7197. return 0
  7198. # The plate each run printed, from its queue job (#3310).
  7199. from backend.app.models.print_queue import PrintQueueItem
  7200. async with async_session() as db:
  7201. plate_rows = await db.execute(
  7202. select(PrintQueueItem.archive_id, PrintQueueItem.plate_id).where(
  7203. PrintQueueItem.printer_id == printer_id,
  7204. PrintQueueItem.status == "printing",
  7205. PrintQueueItem.archive_id.in_([a.id for a in active]),
  7206. )
  7207. )
  7208. run_plates = {archive_id: plate for archive_id, plate in plate_rows.all() if plate is not None}
  7209. logger = logging.getLogger(__name__)
  7210. for archive in active:
  7211. is_stale, reason = _is_active_archive_stale(archive, state)
  7212. if not is_stale:
  7213. continue
  7214. logger.info(
  7215. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  7216. printer_id,
  7217. archive.id,
  7218. archive.filename,
  7219. reason,
  7220. )
  7221. # Synthesised payload: minimal fields the on_print_complete chain
  7222. # needs. `_reconciled` marker lets downstream code distinguish this
  7223. # from a real MQTT-driven completion if it ever needs to (e.g. for
  7224. # metrics / debug logging). raw_data is the live printer state so
  7225. # the usage tracker can compare end-of-print remain% against the
  7226. # captured start values.
  7227. outcome = _reconciled_outcome(archive, state)
  7228. payload = {
  7229. "status": outcome,
  7230. "filename": archive.filename,
  7231. "subtask_name": archive.print_name or "",
  7232. "subtask_id": archive.subtask_id or "",
  7233. "raw_data": state.raw_data or {},
  7234. "_reconciled": True,
  7235. }
  7236. if isinstance(archive, _RunOfArchive):
  7237. # The archive it closes, which its names and printer may not find:
  7238. # another printer's plate of it can have started since.
  7239. payload["_reconciled_archive_id"] = archive.id
  7240. if outcome != "aborted":
  7241. # The printer's progress and layer are this job's, so a partial
  7242. # run is charged what it printed rather than nothing.
  7243. if state.progress:
  7244. payload["last_progress"] = state.progress
  7245. if state.layer_num:
  7246. payload["last_layer_num"] = state.layer_num
  7247. if outcome == "failed":
  7248. payload["hms_errors"] = [e.completion_payload() for e in state.hms_errors or []]
  7249. if outcome == "completed":
  7250. ended = _reconciled_end_time(archive, datetime.now(timezone.utc), run_plates.get(archive.id))
  7251. if ended:
  7252. payload["_reconciled_completed_at"] = ended
  7253. try:
  7254. await on_print_complete(printer_id, payload)
  7255. reconciled += 1
  7256. except Exception as e:
  7257. # Catch-all: a reconciliation failure must not block the
  7258. # printer's normal status flow. The archive stays in
  7259. # ``status="printing"`` and the next reconnect retries.
  7260. logger.warning(
  7261. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  7262. archive.id,
  7263. e,
  7264. )
  7265. return reconciled
  7266. # #2547: clearance left between the nozzle and the top of the print when the
  7267. # plate is commanded back into camera framing. The nozzle is parked away from
  7268. # the part by then, so this is belt-and-braces against a max_z_height that
  7269. # under-reports (e.g. a slicer that excludes a final Z hop).
  7270. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  7271. # How far below the restored position to drop the plate again afterwards, so
  7272. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  7273. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  7274. # on machines with less headroom.
  7275. _PLATE_PARK_DROP_MM = 100.0
  7276. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  7277. # this axis, so it is a proven-safe speed for the full travel.
  7278. _PLATE_RESTORE_FEEDRATE = 600
  7279. # Time allowed for the plate to reach the restored position before the camera
  7280. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  7281. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  7282. # How long `_background_finish_photo` waits for this producer. Must cover the
  7283. # settle window plus a worst-case RTSP grab (15s), and stay below the
  7284. # notification path's own photo wait so a slow producer degrades to a
  7285. # photo-less notification rather than a missed one. The chamber light's
  7286. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  7287. # camera_light.MAX_DELAY_SECONDS stays below it.
  7288. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  7289. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  7290. """The ``_active_prints`` keys a finished print may be registered under.
  7291. Matching how they were registered in on_print_start. Shared by
  7292. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  7293. to find the same binding.
  7294. """
  7295. possible_keys = []
  7296. # Try subtask_name variations first (most reliable for matching)
  7297. if subtask_name:
  7298. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  7299. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  7300. possible_keys.append((printer_id, subtask_name))
  7301. # Try filename variations
  7302. if filename:
  7303. # Extract just the filename if it's a path
  7304. fname = filename.split("/")[-1] if "/" in filename else filename
  7305. if fname.endswith(".3mf"):
  7306. possible_keys.append((printer_id, fname))
  7307. elif fname.endswith(".gcode"):
  7308. base_name = fname.rsplit(".", 1)[0]
  7309. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  7310. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7311. possible_keys.append((printer_id, fname))
  7312. else:
  7313. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  7314. possible_keys.append((printer_id, f"{fname}.3mf"))
  7315. possible_keys.append((printer_id, fname))
  7316. # Also try full path versions
  7317. if filename.endswith(".3mf"):
  7318. possible_keys.append((printer_id, filename))
  7319. elif filename.endswith(".gcode"):
  7320. base_name = filename.rsplit(".", 1)[0]
  7321. possible_keys.append((printer_id, f"{base_name}.3mf"))
  7322. possible_keys.append((printer_id, filename))
  7323. else:
  7324. possible_keys.append((printer_id, f"{filename}.3mf"))
  7325. possible_keys.append((printer_id, filename))
  7326. return possible_keys
  7327. def _archive_name_forms(archive) -> set[str]:
  7328. """The names an archive could be echoed back as, in normalised form (#3240).
  7329. Its print name, and its filename with and without the 3MF extension.
  7330. """
  7331. forms = set()
  7332. if archive.print_name:
  7333. forms.add(_normalise_subtask_name(archive.print_name))
  7334. if archive.filename:
  7335. forms.add(_normalise_subtask_name(archive.filename))
  7336. for suffix in (".gcode.3mf", ".3mf"):
  7337. if archive.filename.lower().endswith(suffix):
  7338. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  7339. forms.discard("")
  7340. return forms
  7341. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  7342. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  7343. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  7344. from the plate recorded when the job was dispatched. Neither is touched:
  7345. ``on_print_complete`` pops both, which is why the finish-photo producer
  7346. calls this before its first await, while they are still there.
  7347. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  7348. archive, or that it only knows by a name -- and on any error: the producer
  7349. calls this before the ``try`` that always releases the photo consumer, so
  7350. it must not raise.
  7351. """
  7352. try:
  7353. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  7354. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  7355. if archive_id is None:
  7356. return None, None
  7357. return archive_id, _print_plate_ids.get((printer_id, archive_id))
  7358. except Exception:
  7359. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  7360. return None, None
  7361. async def _max_z_for_current_print(
  7362. printer_id: int,
  7363. data: dict,
  7364. logger,
  7365. archive_id: int | None,
  7366. plate_id: int | None = None,
  7367. ) -> float | None:
  7368. """Height of the print that just finished on ``printer_id``, or None (#2547).
  7369. This number becomes the target of a real Z move, so every step here refuses
  7370. rather than guesses. A height belonging to some *other* print is the one
  7371. failure that could drive the nozzle into the model: 20 mm carried onto a
  7372. 200 mm print would command the plate up through the part.
  7373. Three independent things therefore have to agree before a height is
  7374. returned:
  7375. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  7376. when it started (see ``_bound_print``), never one found by name. A name
  7377. is not an identity: every plate of a multi-plate file shares one, and a
  7378. reprint reuses its archive row, so the newest archive with the right
  7379. name can be another plate of the same file. Support bundles show the
  7380. old name lookup doing exactly that (archive 288 for a print bound to
  7381. 169, 313 layers against 125), stopped only by the layer check below.
  7382. No binding, no move.
  7383. 2. **Identity.** The bound archive's name still has to be the finished
  7384. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  7385. because the printer echoes spaces as underscores (#3240). Exact: not a
  7386. substring, and not the completion check's tolerance for a truncated
  7387. echo.
  7388. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  7389. match the layer count the printer itself reported over MQTT for the print
  7390. that just ended. These come from genuinely different sources, so a
  7391. mismatch means the row is not this print, whatever its name says.
  7392. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  7393. plate of a multi-plate file reuses the archive row without updating its
  7394. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  7395. ``on_print_complete`` may already have flipped the status by the time we
  7396. run.
  7397. """
  7398. subtask_name = (data.get("subtask_name") or "").strip()
  7399. if not subtask_name:
  7400. # Nothing to identify the print by — refuse rather than fall back to
  7401. # "whatever ran last on this printer".
  7402. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  7403. return None
  7404. if archive_id is None:
  7405. logger.info(
  7406. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  7407. printer_id,
  7408. subtask_name,
  7409. )
  7410. return None
  7411. try:
  7412. from backend.app.models.archive import PrintArchive
  7413. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  7414. async with async_session() as db:
  7415. result = await db.execute(
  7416. select(PrintArchive).where(
  7417. PrintArchive.id == archive_id,
  7418. PrintArchive.printer_id == printer_id,
  7419. PrintArchive.status.in_(("printing", "completed")),
  7420. PrintArchive.deleted_at.is_(None),
  7421. )
  7422. )
  7423. archive = result.scalar_one_or_none()
  7424. if archive is None or not archive.file_path:
  7425. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  7426. return None
  7427. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  7428. logger.warning(
  7429. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  7430. printer_id,
  7431. archive_id,
  7432. subtask_name,
  7433. )
  7434. return None
  7435. client = printer_manager.get_client(printer_id)
  7436. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  7437. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  7438. logger.warning(
  7439. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  7440. "— refusing to move the plate on a height that may not be this print's",
  7441. printer_id,
  7442. archive.id,
  7443. archive.total_layers,
  7444. reported_layers,
  7445. )
  7446. return None
  7447. # Stored relative to the data directory, like every other archive path
  7448. # (#3240: this read a `data_dir` setting that does not exist).
  7449. path = app_settings.base_dir / archive.file_path
  7450. plate = plate_id or archive.plate_id or 1
  7451. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  7452. except Exception as e:
  7453. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  7454. return None
  7455. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  7456. """Raise the plate back into camera framing before the finish photo (#2547).
  7457. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  7458. the time ``gcode_state`` reaches FINISH the finished print sits far below
  7459. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  7460. This commands an absolute ``G1 Z`` back to just above the last printed
  7461. layer.
  7462. Absolute, not relative, is the whole safety argument. ``max_z_height +
  7463. clearance`` is a height the toolhead was physically at seconds earlier, so
  7464. it is inside the travel limits by construction and leaves the nozzle above
  7465. the part. It is also unambiguous across model families: Z is the
  7466. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  7467. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  7468. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  7469. (#2579).
  7470. Returns True if the move was sent and waited out, False if it was skipped.
  7471. """
  7472. client = printer_manager.get_client(printer_id)
  7473. if client is None:
  7474. return False
  7475. # Re-read state immediately before commanding motion. If the queue has
  7476. # already started the next print, the printer is no longer ours to move.
  7477. state = getattr(client, "state", None)
  7478. if state is None or state.state != "FINISH":
  7479. logger.info(
  7480. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  7481. printer_id,
  7482. getattr(state, "state", "unknown"),
  7483. )
  7484. return False
  7485. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  7486. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  7487. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  7488. return False
  7489. logger.info(
  7490. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  7491. printer_id,
  7492. target_z,
  7493. max_z_height,
  7494. _PLATE_RESTORE_CLEARANCE_MM,
  7495. _PLATE_RESTORE_SETTLE_SECONDS,
  7496. )
  7497. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  7498. return True
  7499. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  7500. """Drop the plate again after the finish photo (#2547).
  7501. Without this the user walks up to a finished print sitting just under the
  7502. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  7503. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  7504. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  7505. print homes anyway.
  7506. """
  7507. client = printer_manager.get_client(printer_id)
  7508. state = getattr(client, "state", None) if client else None
  7509. if client is None or state is None or state.state != "FINISH":
  7510. return
  7511. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  7512. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  7513. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  7514. """True if a queue item is about to take this printer (#2547).
  7515. The scheduler dispatches the next job the moment a print completes, and a
  7516. plate move interleaved with a print start is not a race worth having. The
  7517. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  7518. this window; this closes the head of it.
  7519. """
  7520. try:
  7521. from backend.app.models.print_queue import PrintQueueItem
  7522. async with async_session() as db:
  7523. result = await db.execute(
  7524. select(PrintQueueItem.id)
  7525. .where(
  7526. PrintQueueItem.printer_id == printer_id,
  7527. PrintQueueItem.status.in_(("pending", "printing")),
  7528. )
  7529. .limit(1)
  7530. )
  7531. return result.scalar_one_or_none() is not None
  7532. except Exception as e:
  7533. # Fail closed: if we can't tell, don't move the plate.
  7534. logging.getLogger(__name__).debug(
  7535. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  7536. )
  7537. return True
  7538. async def on_finish_photo_moment(printer_id: int, data: dict):
  7539. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  7540. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  7541. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  7542. fallback for prints that skip stage 22 (cancel, external-spool-only,
  7543. HMS halt, firmware variants). Grabs one frame via the same
  7544. external-camera / RTSP path the post-completion fallback uses, stores
  7545. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  7546. ``_background_finish_photo`` consume the cached bytes when it runs.
  7547. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  7548. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  7549. set to Smooth (#1721). No force-on now means the user's explicit
  7550. timelapse=off in the slicer send dialog is respected.
  7551. """
  7552. logger = logging.getLogger(__name__)
  7553. trigger = data.get("trigger", "unknown")
  7554. timelapse_was_active = bool(data.get("timelapse_was_active"))
  7555. logger.info(
  7556. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  7557. printer_id,
  7558. trigger,
  7559. timelapse_was_active,
  7560. )
  7561. # If a timelapse is actively recording, skip the pre-capture — the
  7562. # post-completion path will extract the last frame from the recorded
  7563. # video, which still provides the best framing (toolhead parked,
  7564. # before bed drop) without the per-layer parking side effects.
  7565. if timelapse_was_active:
  7566. logger.info(
  7567. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  7568. printer_id,
  7569. )
  7570. return
  7571. # #1790: register the producer-done event BEFORE the first await so the
  7572. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  7573. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  7574. # The `finally` below guarantees `set()` runs on every exit, including
  7575. # early returns and exceptions, so the consumer's bounded wait can't hang.
  7576. producer_done = asyncio.Event()
  7577. _stage22_finish_in_flight[printer_id] = producer_done
  7578. # #3240: also before the first await. On the FINISH-state path
  7579. # `on_print_complete` is dispatched right behind us and pops both the
  7580. # print's archive binding and its plate; read here, they are still there.
  7581. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  7582. # #2547: set once the plate has actually been raised, and read by the
  7583. # `finally` below. Declared out here so a failure anywhere after the move —
  7584. # a camera timeout, a DB error — still lowers the plate again.
  7585. restore_max_z: float | None = None
  7586. try:
  7587. async with async_session() as db:
  7588. from backend.app.api.routes.settings import get_setting
  7589. from backend.app.models.printer import Printer
  7590. capture_setting = await get_setting(db, "capture_finish_photo")
  7591. if capture_setting is not None and capture_setting.lower() != "true":
  7592. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  7593. return
  7594. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7595. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  7596. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7597. printer = result.scalar_one_or_none()
  7598. if printer is None:
  7599. logger.warning(
  7600. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  7601. printer_id,
  7602. )
  7603. return
  7604. frame_bytes: bytes | None = None
  7605. # #2708: the banked frame arrives already rotated — it comes from
  7606. # `_capture_snapshot_for_notification`, which rotates before returning.
  7607. # Every other source below is a raw grab. Tracking which lets us store
  7608. # exactly one rotation in `_stage22_finish_frames` either way.
  7609. frame_already_rotated = False
  7610. # On the FINISH-state path the End G-code has already run, and two very
  7611. # different situations arrive here needing opposite answers.
  7612. #
  7613. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  7614. # snippet may have ejected the plate — the scene in front of the camera
  7615. # is no longer the finished print, and no amount of moving the plate
  7616. # brings it back. Use the banked in-print frame instead.
  7617. #
  7618. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  7619. # than the camera frames well, and the toolhead is parked out of the
  7620. # way. That is the *best* moment available on firmware that never emits
  7621. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  7622. # back. Preferring the bank here unconditionally, as this code used to,
  7623. # is what shipped a mid-print photo with the toolhead over the part.
  7624. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  7625. banked = _inprint_frame_bank.get(printer_id)
  7626. if banked:
  7627. frame_bytes = banked
  7628. frame_already_rotated = True
  7629. logger.info(
  7630. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  7631. "frame (%d bytes) instead of a post-swap live grab",
  7632. len(banked),
  7633. )
  7634. else:
  7635. logger.warning(
  7636. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  7637. "in-print bank is empty — falling back to a live grab, which may show a "
  7638. "swapped or empty plate",
  7639. printer_id,
  7640. )
  7641. # `restore_max_z` is set only once the plate is actually up, because the
  7642. # `finally` reads it to decide whether it owes a move back down.
  7643. #
  7644. # Never on a print whose End G-code Bambuddy injected, even when the bank
  7645. # came up empty above: that machine may have just ejected its plate, and
  7646. # driving Z into whatever a swap mechanism is doing is not a risk worth
  7647. # taking for a photo of a bed we already know may be bare.
  7648. if (
  7649. frame_bytes is None
  7650. and trigger == "finish_state"
  7651. and restore_plate_enabled
  7652. and not print_dispatch_context.end_gcode_injected(printer_id)
  7653. ):
  7654. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  7655. if wants_restore is None:
  7656. logger.info(
  7657. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  7658. printer_id,
  7659. )
  7660. elif await _plate_restore_is_blocked_by_queue(printer_id):
  7661. logger.info(
  7662. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  7663. printer_id,
  7664. )
  7665. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  7666. restore_max_z = wants_restore
  7667. # Chamber light for the live capture below (#1655). The banked frame
  7668. # above was taken without it, like every in-print bank.
  7669. async with camera_light(printer if frame_bytes is None else None):
  7670. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  7671. from backend.app.api.routes.camera import live_frame_for_capture
  7672. from backend.app.services.external_camera import capture_frame
  7673. # #2707: this used to collide with the live view and fail, which is
  7674. # how finish-photo notifications went out with no image attached.
  7675. # Leaving frame_bytes None keeps the rest of the fallback chain.
  7676. defer, buffered = live_frame_for_capture(printer_id)
  7677. if defer:
  7678. frame_bytes = buffered
  7679. else:
  7680. frame_bytes = await capture_frame(
  7681. printer.external_camera_url,
  7682. printer.external_camera_type or "mjpeg",
  7683. snapshot_url=printer.external_camera_snapshot_url,
  7684. )
  7685. if frame_bytes:
  7686. logger.info(
  7687. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  7688. len(frame_bytes),
  7689. )
  7690. elif frame_bytes is None:
  7691. from backend.app.api.routes.camera import get_buffered_frame
  7692. buffered = get_buffered_frame(printer_id)
  7693. if buffered:
  7694. frame_bytes = buffered
  7695. logger.info(
  7696. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  7697. len(frame_bytes),
  7698. )
  7699. else:
  7700. from backend.app.services.camera import capture_camera_frame_bytes
  7701. frame_bytes = await capture_camera_frame_bytes(
  7702. ip_address=printer.ip_address,
  7703. access_code=printer.access_code,
  7704. model=printer.model,
  7705. timeout=15,
  7706. )
  7707. if frame_bytes:
  7708. logger.info(
  7709. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  7710. len(frame_bytes),
  7711. )
  7712. if frame_bytes:
  7713. if not frame_already_rotated:
  7714. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  7715. _stage22_finish_frames[printer_id] = frame_bytes
  7716. else:
  7717. logger.warning(
  7718. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  7719. printer_id,
  7720. )
  7721. except Exception as e:
  7722. logger.warning(
  7723. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  7724. printer_id,
  7725. e,
  7726. )
  7727. finally:
  7728. # #2547: we raised the plate, so we own lowering it — including when the
  7729. # capture above failed or threw partway through.
  7730. if restore_max_z is not None:
  7731. try:
  7732. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  7733. except Exception as e:
  7734. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7735. # #1790: always unblock the consumer's bounded wait — whether we stored
  7736. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  7737. # dict entry by the consumer doesn't affect signalling.
  7738. producer_done.set()
  7739. def _subtask_name_from_filename(filename: str) -> str:
  7740. """Recover the subtask name a print command would have carried for *filename*.
  7741. The dispatcher derives the printer-facing subtask name from the archive's
  7742. file name, so stripping the extensions back off gives the value MQTT echoes
  7743. on completion. Only the two extensions Bambuddy actually stores are removed,
  7744. and in the order they nest (``.gcode.3mf``), so a model whose own name
  7745. contains a dot -- ``My.Model.3mf`` -- keeps it.
  7746. """
  7747. name = PurePosixPath(filename).name
  7748. for suffix in (".3mf", ".gcode"):
  7749. if name.lower().endswith(suffix):
  7750. name = name[: -len(suffix)]
  7751. return name
  7752. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  7753. """Whether the subtask name is the printed 3MF's own file name.
  7754. A print started from the printer's screen reports the same full name, with
  7755. its extension, as both subtask and file (#3009). A dispatched print reports
  7756. a bare subtask name; one that merely ends in ".3mf" can be a model named
  7757. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  7758. """
  7759. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  7760. return False
  7761. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  7762. # How the printer marks a subtask name it had to cut short. Observed on real
  7763. # hardware at ~100 characters, but the cut-off is not a fixed character count
  7764. # (a name with multibyte characters came back at 98), so match the marker
  7765. # rather than a length.
  7766. _SUBTASK_TRUNCATION_MARKER = "..."
  7767. def _normalise_subtask_name(name: str) -> str:
  7768. """Canonical form for comparing a dispatched name against MQTT's echo.
  7769. The printer does not echo the name back verbatim: it substitutes
  7770. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  7771. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  7772. The 3MF lookup in this module has always known that -- it builds
  7773. space-to-underscore variants of every candidate filename, and its
  7774. directory search normalises both sides before comparing. This exists so
  7775. the completion check reads the same rule from the same place instead of
  7776. growing its own, which is exactly how it came to disagree (#2829).
  7777. A space at either end is substituted too: ``Part .gcode.3mf`` is
  7778. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  7779. are dropped after the substitution so both sides agree (#3241).
  7780. """
  7781. return name.strip().replace(" ", "_").strip("_").casefold()
  7782. def _3mf_files_for_print(paths: list[str], search_term: str) -> list[str]:
  7783. """The 3MF files of the printer's folder listings that are this print's.
  7784. A file of the print's own name wins, in whichever folder. Only without one
  7785. is a file that merely contains the name taken, and then only when it is
  7786. the one such file: "Cube_large.3mf" is not "Cube"'s file, and of several
  7787. candidates none can be told apart. Paths keep the listings' order.
  7788. """
  7789. threemf = [path for path in paths if path.lower().endswith(".3mf")]
  7790. exact = [path for path in threemf if _subtask_names_match(_subtask_name_from_filename(path), search_term)]
  7791. if exact:
  7792. return exact
  7793. term = _normalise_subtask_name(search_term)
  7794. partial = [path for path in threemf if term in _normalise_subtask_name(PurePosixPath(path).name)]
  7795. if len(partial) > 1:
  7796. logging.getLogger(__name__).info(
  7797. "Several 3MF files contain %r and none is named for it: %s", search_term, partial
  7798. )
  7799. return []
  7800. return partial
  7801. def _subtask_names_match(expected: str, observed: str) -> bool:
  7802. """Whether two subtask names describe the same print.
  7803. Beyond the space/underscore substitution, the printer truncates long names
  7804. and marks the cut with ``...``. A truncated echo has to count as a match or
  7805. every print with a long name strands its queue item the same way.
  7806. """
  7807. expected_n = _normalise_subtask_name(expected)
  7808. observed_n = _normalise_subtask_name(observed)
  7809. if expected_n == observed_n:
  7810. return True
  7811. # Either side can be the truncated one: the printer truncates what it
  7812. # echoes, and an archive whose own filename was recorded from a previous
  7813. # truncated echo carries the marker too.
  7814. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  7815. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  7816. continue
  7817. # The full side has lost its edge underscores; a cut that lands right
  7818. # after one keeps it, so drop it here too (#3241). Nothing left before
  7819. # the marker is no evidence of anything, and must not match every name.
  7820. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  7821. if kept and full.startswith(kept):
  7822. return True
  7823. return False
  7824. async def _queue_item_dispatched_name(db, item) -> str:
  7825. """The subtask name *item* was dispatched under, or "" when unknowable.
  7826. A row with no archive, or an archive with no file name, is unverifiable
  7827. rather than wrong; every caller answers that with its permissive branch.
  7828. """
  7829. if item.archive_id is None:
  7830. return ""
  7831. from backend.app.models.archive import PrintArchive
  7832. archive = await db.get(PrintArchive, item.archive_id)
  7833. if archive is None or not archive.filename:
  7834. return ""
  7835. return _subtask_name_from_filename(archive.filename)
  7836. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  7837. """Whether this completion event is plausibly about *item*'s print.
  7838. The caller finds its queue row by printer and ``status='printing'`` alone,
  7839. which is all a completion event gives it -- there is no run identifier in
  7840. the MQTT payload to match on. That makes the lookup indiscriminate: any
  7841. completion delivered for this printer closes whichever row happens to be
  7842. printing, however unrelated. Comparing the subtask name against the archive
  7843. the row was dispatched with costs one primary-key load and rules that out.
  7844. Deliberately permissive: it answers False only on a positive disagreement
  7845. between two names we actually have. A row with no archive, an archive with
  7846. no file name, or an event with no subtask name is unverifiable rather than
  7847. wrong, and refusing those would strand the item in ``printing`` and wedge
  7848. the printer's queue -- a worse failure than the one being prevented.
  7849. """
  7850. observed = (data.get("subtask_name") or "").strip()
  7851. if not observed or item.archive_id is None:
  7852. return True
  7853. from backend.app.models.archive import PrintArchive
  7854. archive = await db.get(PrintArchive, item.archive_id)
  7855. if archive is None or not archive.filename:
  7856. return True
  7857. expected = _subtask_name_from_filename(archive.filename)
  7858. if not expected or _subtask_names_match(expected, observed):
  7859. return True
  7860. logging.getLogger(__name__).warning(
  7861. "Ignoring print completion for queue item %s: it was dispatched as %r "
  7862. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  7863. "printing rather than closing a run this event is not about.",
  7864. item.id,
  7865. expected,
  7866. archive.id,
  7867. archive.filename,
  7868. observed,
  7869. )
  7870. return False
  7871. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  7872. """Spend the 3MF download cache on a still-empty fallback archive.
  7873. ``on_print_complete`` drops the cache as its first act, which deletes the
  7874. file. If the cover endpoint (or anything else) pulled the 3MF while the
  7875. print ran and the archive never got one, this is the last moment those bytes
  7876. exist (#2957).
  7877. """
  7878. logger = logging.getLogger(__name__)
  7879. names = [
  7880. n
  7881. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  7882. if n
  7883. ]
  7884. for name in names:
  7885. try:
  7886. cached = get_cached_3mf(printer_id, name)
  7887. # The print has ended: its completion prices the archive, so no
  7888. # print-start estimate is scheduled to race it.
  7889. if cached and await try_recover_fallback_archive(printer_id, name, cached, price=False):
  7890. return
  7891. except Exception as e:
  7892. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  7893. # Longest the print's end waits for its file to be deleted from the SD card
  7894. _SD_CLEANUP_BUDGET_SECONDS = 45.0
  7895. async def _cleanup_sd_card_after_print(
  7896. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  7897. ) -> None:
  7898. """Delete a finished print's file from the printer's SD card."""
  7899. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  7900. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  7901. # auto-start files found in root on power cycle, causing ghost prints.
  7902. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  7903. try:
  7904. if subtask_name:
  7905. archive_filename: str | None = None
  7906. async with async_session() as db:
  7907. from backend.app.models.archive import PrintArchive
  7908. from backend.app.models.printer import Printer
  7909. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7910. printer = result.scalar_one_or_none()
  7911. if archive_id:
  7912. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  7913. archive_filename = archive_row.scalar_one_or_none()
  7914. if printer:
  7915. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  7916. from backend.app.utils.filename import derive_remote_filename
  7917. # Primary candidate: the exact path the dispatcher uploaded to
  7918. # (derived from archive.filename via the same rule as upload).
  7919. # Without it, a library row that ended up with a doubled
  7920. # .gcode.3mf (#1542) leaves the real file behind because the
  7921. # subtask_name + ext fallbacks below don't match what's on the
  7922. # SD card. Fallbacks remain for archive-less prints (subtask
  7923. # never resolved to an archive) and for older naming variants.
  7924. candidate_paths: list[str] = []
  7925. if archive_filename:
  7926. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  7927. for ext in (".3mf", ".gcode"):
  7928. fallback = f"/{subtask_name}{ext}"
  7929. if fallback not in candidate_paths:
  7930. candidate_paths.append(fallback)
  7931. # Three outcomes track across all candidates so the final log
  7932. # line reflects what actually happened. The A1 in #1721 always
  7933. # ends here with ``any_not_found=True`` and the others False
  7934. # — its firmware auto-cleans the SD card before our cleanup
  7935. # runs, every candidate FTP-DELE returns 550, and the old
  7936. # code burned 3 retries × 2 s × 3 candidates per print
  7937. # logging a misleading "may linger" WARNING on a successful
  7938. # print.
  7939. any_deleted = False
  7940. any_real_failure = False
  7941. any_not_found = False
  7942. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  7943. for remote_path in candidate_paths:
  7944. if PurePosixPath(remote_path).name.lower() in files_in_use:
  7945. logger.info(
  7946. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  7947. remote_path,
  7948. printer.name,
  7949. )
  7950. continue
  7951. # Retry only the FAILED case — 550 NOT_FOUND will never
  7952. # recover by waiting, so a "file isn't here" answer
  7953. # advances immediately to the next candidate without
  7954. # consuming the retry budget.
  7955. for attempt in range(1, 4):
  7956. try:
  7957. delete_result = await delete_file_async(
  7958. printer.ip_address,
  7959. printer.access_code,
  7960. remote_path,
  7961. printer_model=printer.model,
  7962. )
  7963. except Exception as e:
  7964. delete_result = DeleteResult.FAILED
  7965. logger.warning(
  7966. "SD card cleanup attempt %d/3 raised for %s: %s",
  7967. attempt,
  7968. remote_path,
  7969. e,
  7970. )
  7971. if delete_result == DeleteResult.DELETED:
  7972. any_deleted = True
  7973. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  7974. break
  7975. if delete_result == DeleteResult.NOT_FOUND:
  7976. any_not_found = True
  7977. break # 550 will not recover; try next candidate
  7978. # FAILED: real error — retry with backoff, then give up
  7979. if attempt < 3:
  7980. await asyncio.sleep(2)
  7981. else:
  7982. any_real_failure = True
  7983. logger.warning(
  7984. "SD card cleanup failed after 3 attempts for %s "
  7985. "(network/auth/transient error — file may linger on SD card)",
  7986. remote_path,
  7987. )
  7988. if not any_deleted and not any_real_failure and any_not_found:
  7989. # Every candidate said "not here." Either the printer
  7990. # firmware swept the SD card itself (common on A1) or the
  7991. # dispatcher's upload path doesn't match our candidate
  7992. # rule. Either way: nothing to clean up, no warning.
  7993. logger.debug(
  7994. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  7995. "(printer likely self-cleaned)",
  7996. printer.name,
  7997. )
  7998. except Exception as e:
  7999. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  8000. async def on_print_complete(printer_id: int, data: dict):
  8001. """Handle print completion - update the archive status.
  8002. The printer counts as printing until the print's usage is booked (or this
  8003. ends), so the AMS remain% weight sync can't charge it a second time while
  8004. the usage tracker works (WU-3). Marked before the first await.
  8005. """
  8006. from backend.app.services.usage_tracker import done_completing, mark_completing
  8007. mark_completing(printer_id)
  8008. try:
  8009. await _close_out_print(printer_id, data)
  8010. finally:
  8011. done_completing(printer_id)
  8012. async def _close_out_print(printer_id: int, data: dict):
  8013. import time
  8014. logger = logging.getLogger(__name__)
  8015. start_time = time.time()
  8016. def log_timing(section: str):
  8017. elapsed = time.time() - start_time
  8018. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  8019. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  8020. # A kill-switch stop sends its provider notification immediately. Keep the
  8021. # task so the later notification path can await it and avoid a duplicate;
  8022. # if that immediate attempt failed, the regular completion path retries.
  8023. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  8024. # Last chance before the bytes go: if this print's archive is still an empty
  8025. # fallback and something downloaded the 3MF while it ran, fill the archive in
  8026. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  8027. # below deletes the file (#2957).
  8028. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  8029. # A pending cool-off retry has nothing left to recover for — the cache is
  8030. # about to be dropped and the print is over.
  8031. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  8032. if retry_task and not retry_task.done():
  8033. retry_task.cancel()
  8034. # Drop the 3MF download cache for this printer (#972). The print is over,
  8035. # nothing else legitimately needs the bytes; keeping them would only risk
  8036. # handing a stale file to the next print if it reuses the same name.
  8037. clear_3mf_cache(printer_id)
  8038. try:
  8039. ws_data = {
  8040. "status": data.get("status"),
  8041. "filename": data.get("filename"),
  8042. "subtask_name": data.get("subtask_name"),
  8043. "timelapse_was_active": data.get("timelapse_was_active"),
  8044. }
  8045. await ws_manager.send_print_complete(printer_id, ws_data)
  8046. log_timing("WebSocket send_print_complete")
  8047. except Exception as e:
  8048. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  8049. # Capture user info before clearing (needed for print log entry)
  8050. _print_user_info = printer_manager.get_current_print_user(printer_id)
  8051. # Clear current print user tracking (Issue #206)
  8052. printer_manager.clear_current_print_user(printer_id)
  8053. # If the user explicitly stopped this print from the queue UI the printer will
  8054. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  8055. # correct "print stopped" notification/email is sent instead of a failure alert.
  8056. _raw_status = data.get("status", "completed")
  8057. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  8058. logger.info(
  8059. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  8060. _raw_status,
  8061. printer_id,
  8062. )
  8063. data = {**data, "status": "cancelled"}
  8064. elif printer_id in _kill_switch_stopped and _raw_status in ("failed", "aborted"):
  8065. logger.info(
  8066. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (stopped by the printer kill switch)",
  8067. _raw_status,
  8068. printer_id,
  8069. )
  8070. data = {**data, "status": "cancelled", "_kill_switch": True}
  8071. _user_stopped_printers.discard(printer_id)
  8072. _kill_switch_stopped.discard(printer_id)
  8073. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  8074. # may have left material on the bed: a user can cancel ten hours into a
  8075. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  8076. # touchscreen-stop reports `aborted` rather than `cancelled` because
  8077. # `_user_stopped_printers` is only populated when the user stops via the
  8078. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  8079. # which auto-dispatched the next queued print onto a fouled bed two seconds
  8080. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  8081. # Auto Off power cycles and Bambuddy restarts.
  8082. try:
  8083. notify_live_activities.print_finished(printer_id, data)
  8084. except Exception:
  8085. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  8086. _final_status = data.get("status", "completed")
  8087. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  8088. printer_manager.set_awaiting_plate_clear(printer_id, True)
  8089. # MQTT relay - publish print complete
  8090. try:
  8091. printer_info = printer_manager.get_printer(printer_id)
  8092. if printer_info:
  8093. await mqtt_relay.on_print_complete(
  8094. printer_id,
  8095. printer_info.name,
  8096. printer_info.serial_number,
  8097. data.get("filename", ""),
  8098. data.get("subtask_name", ""),
  8099. data.get("status", "completed"),
  8100. )
  8101. except Exception:
  8102. pass # Don't fail print complete callback if MQTT fails
  8103. filename = data.get("filename", "")
  8104. subtask_name = data.get("subtask_name", "")
  8105. if not filename and not subtask_name:
  8106. # Which print ended can't be told: the printer reported no name since
  8107. # Bambuddy started (a print that failed while preparing, a calibration).
  8108. # Charge nothing, but close the print session, which otherwise kept the
  8109. # AMS weight sync off until the next print (AS-5). A print archived as
  8110. # running is closed and charged by the reconnect reconcile.
  8111. logger.warning("Print complete without filename or subtask_name")
  8112. try:
  8113. from backend.app.services.usage_tracker import discard_session
  8114. async with async_session() as db:
  8115. await discard_session(db, printer_id)
  8116. except Exception as e:
  8117. logger.warning("Failed to clear print session for printer %s: %s", printer_id, e)
  8118. return
  8119. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  8120. # Build list of possible keys to try (matching how they were registered in on_print_start)
  8121. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  8122. # Find the archive for this print
  8123. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  8124. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  8125. archive_id = None
  8126. for key in possible_keys:
  8127. archive_id = _active_prints.pop(key, None)
  8128. if archive_id:
  8129. _owned_print_archive_ids.discard(archive_id)
  8130. logger.info("Found archive %s with key %s", archive_id, key)
  8131. # Also clean up the printer's other keys pointing to this archive;
  8132. # another printer's are a plate of it still printing there.
  8133. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id and k[0] == printer_id]
  8134. for k in keys_to_remove:
  8135. _active_prints.pop(k, None)
  8136. break
  8137. # The archive bound when the print started, before the name search below.
  8138. # Only this one may give the finish-photo plate restore a height (#3240):
  8139. # the search matches names by substring.
  8140. bound_archive_id = archive_id
  8141. if not archive_id and data.get("_reconciled") and data.get("_reconciled_archive_id"):
  8142. # The reconcile names the archive whose run on this printer it
  8143. # closes. Only while that run is open: the print's real end may have
  8144. # closed it meanwhile, or closed the print without managing to write
  8145. # it, and either way there is nothing left to end twice.
  8146. if await _archive_of_open_run(printer_id) != data["_reconciled_archive_id"]:
  8147. logger.info(
  8148. "[RECONCILE] Archive %s has no run open on printer %s any more; nothing to close",
  8149. data["_reconciled_archive_id"],
  8150. printer_id,
  8151. )
  8152. return
  8153. archive_id = data["_reconciled_archive_id"]
  8154. ending_job = str(data.get("subtask_id") or "").strip()
  8155. if not archive_id and ending_job not in ("", "0"):
  8156. # Not bound (a restart since the start): this job's run, open on the
  8157. # printer. Only by its job id: a run open there can be of the print
  8158. # running now, while the end is of an earlier one closed late (the
  8159. # restart's reconcile of a missed end).
  8160. archive_id = await _archive_of_open_run(printer_id, subtask_id=ending_job)
  8161. if archive_id:
  8162. logger.info("Found archive %s by the run of job %s open on printer %s", archive_id, ending_job, printer_id)
  8163. if not archive_id:
  8164. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  8165. async with async_session() as db:
  8166. from backend.app.models.archive import PrintArchive
  8167. # Try matching by subtask_name (stored as print_name) first. The
  8168. # same name rule as the queue's completion check: a name inside
  8169. # another ("Clip" in "Cable Clip") is a different print, and the
  8170. # printer's underscores for spaces and truncation still match.
  8171. if subtask_name:
  8172. printing = await db.scalars(
  8173. select(PrintArchive)
  8174. .where(PrintArchive.printer_id == printer_id)
  8175. .where(PrintArchive.status == "printing")
  8176. .order_by(PrintArchive.created_at.desc())
  8177. )
  8178. # A print started from the printer's screen reports its file
  8179. # name, extensions included, as the subtask (#3009).
  8180. reported = {subtask_name, _subtask_name_from_filename(subtask_name)}
  8181. archive = next(
  8182. (
  8183. candidate
  8184. for candidate in printing
  8185. if any(
  8186. (candidate.print_name and _subtask_names_match(candidate.print_name, name))
  8187. or (
  8188. candidate.filename
  8189. and _subtask_names_match(_subtask_name_from_filename(candidate.filename), name)
  8190. )
  8191. for name in reported
  8192. )
  8193. ),
  8194. None,
  8195. )
  8196. if archive:
  8197. archive_id = archive.id
  8198. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  8199. # Also try by filename
  8200. if not archive_id and filename:
  8201. result = await db.execute(
  8202. select(PrintArchive)
  8203. .where(PrintArchive.printer_id == printer_id)
  8204. .where(PrintArchive.filename == filename)
  8205. .where(PrintArchive.status == "printing")
  8206. .order_by(PrintArchive.created_at.desc())
  8207. .limit(1)
  8208. )
  8209. archive = result.scalar_one_or_none()
  8210. if archive:
  8211. archive_id = archive.id
  8212. # Bounded: a printer whose FTP hangs on DELE took up to 3 candidates x 3
  8213. # attempts x a 60 s timeout, about nine minutes, before the queue item was
  8214. # closed below. The stranded-job closer gives up after five and closed it
  8215. # first, so the job's auto-off and its billing never ran. Inline rather
  8216. # than in the background, so the next job of the same file isn't released
  8217. # (and uploaded under the name being deleted) while the cleanup still
  8218. # works on it. A delete already sent may still finish in its FTP thread
  8219. # after the cutoff, as one past delete_file_async's own timeout always did.
  8220. try:
  8221. await asyncio.wait_for(
  8222. _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger),
  8223. timeout=_SD_CLEANUP_BUDGET_SECONDS,
  8224. )
  8225. except TimeoutError:
  8226. logger.warning(
  8227. "SD card cleanup on printer %s took over %ss; leaving the file there and closing the print",
  8228. printer_id,
  8229. _SD_CLEANUP_BUDGET_SECONDS,
  8230. )
  8231. log_timing("SD card cleanup")
  8232. # Update queue item status early — must run before the archive_id early-return
  8233. # so queue items don't get stuck in "printing" when archive lookup fails.
  8234. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  8235. queue_item_id = None
  8236. billing_run_id: str | None = None
  8237. billing_user_id: int | None = None
  8238. billing_cost_center_id: int | None = None
  8239. billing_plate_id: int | None = None
  8240. queue_status = None
  8241. queue_auto_off = False
  8242. try:
  8243. from backend.app.core.database import run_with_retry
  8244. from backend.app.models.print_queue import PrintQueueItem
  8245. async def _update_queue_status(db):
  8246. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  8247. nonlocal queue_item_id, queue_status, queue_auto_off
  8248. result = await db.execute(
  8249. select(PrintQueueItem)
  8250. .where(PrintQueueItem.printer_id == printer_id)
  8251. .where(PrintQueueItem.status == "printing")
  8252. )
  8253. printing_items = list(result.scalars().all())
  8254. if len(printing_items) > 1:
  8255. logger.warning(
  8256. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  8257. printer_id,
  8258. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  8259. )
  8260. item = printing_items[0] if printing_items else None
  8261. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  8262. return
  8263. if item:
  8264. queue_status = data.get("status", "completed")
  8265. # MQTT sends "aborted" for cancelled prints; normalise to
  8266. # "cancelled" so it matches the queue schema Literal.
  8267. if queue_status == "aborted":
  8268. queue_status = "cancelled"
  8269. item.status = queue_status
  8270. item.completed_at = datetime.now(timezone.utc)
  8271. if queue_status == "failed" and not item.error_message:
  8272. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  8273. # Bump usage counters on the source library file so admins can
  8274. # sort by "last printed" and (eventually) auto-purge stale
  8275. # files — #1008.
  8276. await _bump_library_file_usage_if_completed(db, item, queue_status)
  8277. await db.commit()
  8278. queue_item_id = item.id
  8279. billing_run_id = item.billing_run_id
  8280. billing_user_id = item.created_by_id
  8281. billing_cost_center_id = item.cost_center_id
  8282. billing_plate_id = item.plate_id
  8283. queue_auto_off = item.auto_off_after
  8284. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  8285. await run_with_retry(_update_queue_status, label="queue status update")
  8286. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  8287. # their own sessions and have their own error handling — no retry needed.
  8288. if queue_item_id is not None:
  8289. # Batch orders (#342): this run may have been the last one an order
  8290. # owed. Re-evaluate here rather than lazily on read, so a finished
  8291. # order reports itself complete without someone opening the page.
  8292. try:
  8293. from backend.app.services.print_batch import refresh_batch_status_for_item
  8294. async with async_session() as db:
  8295. await refresh_batch_status_for_item(db, queue_item_id)
  8296. await db.commit()
  8297. except Exception as e:
  8298. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  8299. # MQTT relay - publish queue job completed
  8300. try:
  8301. printer_info = printer_manager.get_printer(printer_id)
  8302. await mqtt_relay.on_queue_job_completed(
  8303. job_id=queue_item_id,
  8304. filename=filename or subtask_name,
  8305. printer_id=printer_id,
  8306. printer_name=printer_info.name if printer_info else "Unknown",
  8307. status=queue_status,
  8308. )
  8309. except Exception:
  8310. pass # Don't fail if MQTT fails
  8311. # Check if queue is now empty and send notification
  8312. try:
  8313. from sqlalchemy import func as sa_func
  8314. async with async_session() as db:
  8315. count_result = await db.execute(
  8316. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  8317. )
  8318. pending_count = count_result.scalar() or 0
  8319. if pending_count == 0:
  8320. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  8321. completed_result = await db.execute(
  8322. select(sa_func.count(PrintQueueItem.id)).where(
  8323. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  8324. PrintQueueItem.completed_at >= today_start,
  8325. )
  8326. )
  8327. completed_count = completed_result.scalar() or 1
  8328. await notification_service.on_queue_completed(
  8329. completed_count=completed_count,
  8330. db=db,
  8331. )
  8332. except Exception:
  8333. pass # Don't fail if notification fails
  8334. # Handle auto_off_after - power off printer if the queue item opted
  8335. # in. Delegates to the smart-plug manager so the off honours each
  8336. # plug's configured strategy (time delay or temperature threshold),
  8337. # is cancelled if the printer starts printing again, and never cuts
  8338. # power on a loaded print (#1890). Previously an inline block here
  8339. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  8340. # timeout regardless of print state — cutting a touchscreen reprint.
  8341. if queue_auto_off:
  8342. try:
  8343. async with async_session() as db:
  8344. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  8345. except Exception as e:
  8346. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  8347. except Exception as e:
  8348. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  8349. log_timing("Queue item update")
  8350. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  8351. # Must run before archive_id early-return so it fires for all prints (including
  8352. # prints started from BambuStudio/touchscreen that have no archive).
  8353. if data.get("status") == "completed":
  8354. try:
  8355. from backend.app.api.routes.settings import get_setting
  8356. async with async_session() as db:
  8357. threshold_str = await get_setting(db, "bed_cooled_threshold")
  8358. threshold = float(threshold_str) if threshold_str else 35.0
  8359. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  8360. async with async_session() as db:
  8361. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  8362. if providers:
  8363. _bed_cool_waiters[printer_id] = {
  8364. "threshold": threshold,
  8365. "filename": filename or subtask_name or "",
  8366. "registered_at": time.time(),
  8367. }
  8368. logger.info(
  8369. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  8370. printer_id,
  8371. threshold,
  8372. )
  8373. else:
  8374. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  8375. except Exception as e:
  8376. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  8377. # Capture the slicer estimate before usage tracking runs. The tracker may
  8378. # update archive.cost with this run's measured cost; billing partial runs
  8379. # against that already-partial value would discount the charge twice.
  8380. billing_planned_grams: float | None = None
  8381. billing_base_cost: float | None = None
  8382. if archive_id:
  8383. try:
  8384. async with async_session() as db:
  8385. from backend.app.models.archive import PrintArchive
  8386. billing_archive = await db.get(PrintArchive, archive_id)
  8387. if billing_archive:
  8388. billing_path = (
  8389. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  8390. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8391. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  8392. billing_archive,
  8393. billing_path,
  8394. billing_plate_id
  8395. if billing_plate_id is not None
  8396. else _get_start_plate_id(printer_id, archive_id),
  8397. )
  8398. except Exception as e:
  8399. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  8400. # --- Track filament consumption (must run before archive_id early-return so usage
  8401. # is recorded even when auto-archive is disabled) ---
  8402. usage_results: list[dict] = []
  8403. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  8404. stored_ams_mapping = data.get("ams_mapping")
  8405. # Fallback to _print_ams_mappings for queue/reprint (set before print starts).
  8406. # Drained either way, like the plate below: left over, it would be read by
  8407. # the archive's next run, dispatched without a mapping.
  8408. registered_ams_mapping = _print_ams_mappings.pop((printer_id, archive_id), None) if archive_id else None
  8409. if not stored_ams_mapping:
  8410. stored_ams_mapping = registered_ams_mapping
  8411. # Always drain the plate_id register on completion — the session already
  8412. # consumed it at print-start injection; leaving it would leak into the next
  8413. # print on the same archive_id (rare but possible with reprints) (#1697).
  8414. # Capture the popped value so the completion notification can scope the
  8415. # archive-level (summed-across-plates per #1593) filament + time totals
  8416. # down to the single plate that was actually printed (#1785).
  8417. notify_plate_id: int | None = None
  8418. if archive_id:
  8419. notify_plate_id = _print_plate_ids.pop((printer_id, archive_id), None)
  8420. # The start estimate must not outlive the real cost written below (COST-4).
  8421. if archive_id:
  8422. await _settle_archive_cost_estimate(archive_id)
  8423. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  8424. try:
  8425. async with async_session() as db:
  8426. from backend.app.api.routes.settings import get_setting
  8427. _spoolman_on = await get_setting(db, "spoolman_enabled")
  8428. if not _spoolman_on or _spoolman_on.lower() != "true":
  8429. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  8430. async with async_session() as db:
  8431. usage_results = await usage_on_print_complete(
  8432. printer_id,
  8433. data,
  8434. printer_manager,
  8435. db,
  8436. archive_id=archive_id,
  8437. ams_mapping=stored_ams_mapping,
  8438. )
  8439. if usage_results:
  8440. await ws_manager.broadcast(
  8441. {
  8442. "type": "spool_usage_logged",
  8443. "printer_id": printer_id,
  8444. "usage": usage_results,
  8445. }
  8446. )
  8447. log_timing("Usage tracker")
  8448. except Exception as e:
  8449. logger.warning("Usage tracker on_print_complete failed: %s", e)
  8450. # Drop the print-start context unconditionally — the Spoolman branch above
  8451. # skips the internal tracker entirely, so nothing else would clear what
  8452. # print start captured, and a row surviving its print would be restored
  8453. # onto the next one after a restart.
  8454. try:
  8455. from backend.app.services.usage_tracker import discard_session
  8456. async with async_session() as db:
  8457. await discard_session(db, printer_id)
  8458. except Exception as e:
  8459. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  8460. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  8461. # A partial run's cost from the Spoolman spools it was charged to; the
  8462. # built-in inventory's comes in usage_results.
  8463. spoolman_run_cost: float | None = None
  8464. if archive_id:
  8465. if data.get("status") == "completed":
  8466. try:
  8467. await _report_spoolman_usage(printer_id, archive_id)
  8468. log_timing("Spoolman usage report")
  8469. except Exception as e:
  8470. logger.warning("Spoolman usage reporting failed: %s", e)
  8471. else:
  8472. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  8473. try:
  8474. async with async_session() as db:
  8475. spoolman_run_cost = await _cleanup_spoolman_tracking(
  8476. printer_id,
  8477. archive_id,
  8478. db,
  8479. last_layer_num=data.get("last_layer_num"),
  8480. last_progress=data.get("last_progress"),
  8481. status=data.get("status") or "failed",
  8482. )
  8483. except Exception as e:
  8484. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  8485. await _release_archived_spoolman_slots(printer_id)
  8486. log_timing("Filament usage tracking")
  8487. if not archive_id:
  8488. # The printer's own calibration run has no archive by design, so this
  8489. # arrives here every time one finishes. Returning before the no-archive
  8490. # notification keeps a calibration from being announced as a finished
  8491. # print. Everything above this point has already run — the plate-clear
  8492. # gate, the queue reconciliation, the SD-card cleanup — so only the
  8493. # notification is skipped.
  8494. if is_internal_printer_job(filename, subtask_name):
  8495. logger.info(
  8496. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  8497. filename,
  8498. subtask_name,
  8499. )
  8500. return
  8501. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  8502. # Still send print-complete/failed/stopped notifications even without an archive.
  8503. # Try to enrich with queue/library-file data so user-specific emails work too.
  8504. async def _notify_no_archive():
  8505. try:
  8506. async with async_session() as db:
  8507. from backend.app.models.library import LibraryFile
  8508. from backend.app.models.print_queue import PrintQueueItem
  8509. from backend.app.models.printer import Printer
  8510. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8511. printer_obj = result.scalar_one_or_none()
  8512. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  8513. # Only the queue item this completion itself closed (the
  8514. # reconciliation above, which checks the run belongs to it).
  8515. # A print started outside Bambuddy closed none, and must not
  8516. # borrow an earlier job's owner, email or times.
  8517. no_archive_data: dict | None = None
  8518. try:
  8519. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  8520. if queue_item:
  8521. no_archive_data = {"created_by_id": queue_item.created_by_id}
  8522. # How long it really ran, as the archive path reports it (#1198).
  8523. started = to_naive_utc(queue_item.started_at)
  8524. ended = to_naive_utc(queue_item.completed_at)
  8525. # Not for a completion reconciled at reconnect: it
  8526. # ended at an unknown time while the printer was
  8527. # offline, and "now" is the reconnect (DB-C9).
  8528. if (
  8529. not data.get("_reconciled")
  8530. and started
  8531. and ended
  8532. and (ended - started).total_seconds() > 0
  8533. ):
  8534. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  8535. # Estimated time: the queue item caches it from its
  8536. # archive or library file; otherwise read the library
  8537. # file's metadata (LibraryFile has no column for it).
  8538. if queue_item.print_time_seconds:
  8539. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  8540. elif queue_item.library_file_id:
  8541. lib_result = await db.execute(
  8542. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  8543. )
  8544. lib_file = lib_result.scalar_one_or_none()
  8545. estimate = (
  8546. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  8547. )
  8548. if estimate:
  8549. no_archive_data["print_time_seconds"] = estimate
  8550. except Exception as lookup_err:
  8551. logger.debug(
  8552. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  8553. )
  8554. # Enrich with usage tracker results (captured in enclosing scope)
  8555. if usage_results:
  8556. if no_archive_data is None:
  8557. no_archive_data = {}
  8558. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8559. if total_from_usage > 0:
  8560. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8561. no_archive_data["usage_results"] = usage_results
  8562. # Try MQTT remaining_time for print duration when no queue/library data
  8563. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  8564. mqtt_remaining = data.get("remaining_time")
  8565. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  8566. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  8567. ps = data.get("status", "completed")
  8568. logger.info(
  8569. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  8570. )
  8571. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8572. await notification_service.on_print_complete(
  8573. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  8574. )
  8575. else:
  8576. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8577. # Send user-specific email if we have a created_by_id
  8578. if no_archive_data and no_archive_data.get("created_by_id"):
  8579. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8580. await _dispatch_user_print_email(
  8581. ps,
  8582. no_archive_data["created_by_id"],
  8583. p_name,
  8584. raw_filename,
  8585. db,
  8586. )
  8587. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  8588. except Exception as e:
  8589. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  8590. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  8591. return
  8592. log_timing("Archive lookup")
  8593. # Update archive status
  8594. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  8595. try:
  8596. async with async_session() as db:
  8597. service = ArchiveService(db)
  8598. status = data.get("status", "completed")
  8599. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  8600. if hms_errors:
  8601. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  8602. failure_reason = derive_failure_reason(status, hms_errors)
  8603. if data.get("_reconciled") and (status == "aborted" or (status == "failed" and not failure_reason)):
  8604. # A reconciled completion closes out a stale archive at
  8605. # reconnect — it is not a user action, so don't mislabel it
  8606. # "userCancelled". It shares the stale-cleanup path's key
  8607. # (issue #2974) and records that the real end time is unknown,
  8608. # which is also why its logged duration is 0 (#2592). A failed
  8609. # one the printer's errors explain keeps their reason (#3310).
  8610. failure_reason = "noStatusUpdate"
  8611. elif data.get("_kill_switch"):
  8612. # Not the user's cancel: the kill switch stopped a print that did
  8613. # not come from Bambuddy.
  8614. failure_reason = "killSwitch"
  8615. if failure_reason:
  8616. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  8617. elif status == "failed" and hms_errors:
  8618. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  8619. await service.update_archive_status(
  8620. archive_id,
  8621. status=status,
  8622. completed_at=(
  8623. # A reconciled completed print ended at an estimated time,
  8624. # not at the reconnect (#3310).
  8625. data.get("_reconciled_completed_at") or datetime.now(timezone.utc)
  8626. if status in ("completed", "failed", "aborted", "cancelled")
  8627. else None
  8628. ),
  8629. failure_reason=failure_reason,
  8630. )
  8631. logger.info(
  8632. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  8633. )
  8634. await ws_manager.send_archive_updated(
  8635. {
  8636. "id": archive_id,
  8637. "status": status,
  8638. }
  8639. )
  8640. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  8641. # MQTT relay - publish archive updated
  8642. try:
  8643. await mqtt_relay.on_archive_updated(
  8644. archive_id=archive_id,
  8645. print_name=filename or subtask_name,
  8646. status=status,
  8647. )
  8648. except Exception:
  8649. pass # Don't fail if MQTT fails
  8650. except Exception as e:
  8651. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  8652. # Continue with other operations even if archive update fails
  8653. log_timing("Archive status update")
  8654. # Apply finance wallet charge or release reservations once. For all partial
  8655. # terminal states (failed, aborted at the printer display, or cancelled via
  8656. # Bambuddy) use this run's measured spool delta, falling back to the last
  8657. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  8658. # estimate and therefore cannot represent an interrupted run.
  8659. try:
  8660. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  8661. async with async_session() as db:
  8662. from backend.app.models.archive import PrintArchive
  8663. from backend.app.services.finance_billing import apply_print_charge_for_archive
  8664. from backend.app.services.print_log import run_being_ended
  8665. archive = await db.get(PrintArchive, archive_id)
  8666. # The run this end fills in below: charged as its own, not as
  8667. # the archive's latest dispatch (another plate of it, maybe).
  8668. charged_run = await run_being_ended(db, archive_id, printer_id, archive.started_at) if archive else None
  8669. if archive and billing_run_id is None and charged_run is None:
  8670. billing_run_id = getattr(archive, "billing_run_id", None)
  8671. if archive and archive.created_by_id is None and _print_user_info:
  8672. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  8673. await db.flush()
  8674. run_status = data.get("status", "completed")
  8675. last_progress = data.get("last_progress")
  8676. if last_progress is None:
  8677. last_progress = data.get("progress")
  8678. actual_run_grams = _compute_run_filament_grams(
  8679. run_status,
  8680. billing_planned_grams,
  8681. last_progress,
  8682. usage_results,
  8683. )
  8684. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  8685. in_memory_cost_center_id = _print_cost_center_ids.pop((printer_id, archive_id), None)
  8686. charged = await apply_print_charge_for_archive(
  8687. db,
  8688. archive_id,
  8689. charged_user_id=billing_user_id,
  8690. cost_center_id=(
  8691. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  8692. ),
  8693. print_queue_id=queue_item_id,
  8694. print_run_id=billing_run_id,
  8695. base_cost_override=billing_base_cost,
  8696. filament_usage=filament_usage,
  8697. run_entry_id=charged_run.id if charged_run is not None else None,
  8698. run_status=run_status,
  8699. )
  8700. await db.commit()
  8701. if charged:
  8702. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  8703. except Exception as e:
  8704. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  8705. printer_info = printer_manager.get_printer(printer_id)
  8706. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  8707. billing_filename = filename or subtask_name or "Unknown"
  8708. billing_error = str(e)
  8709. try:
  8710. await ws_manager.broadcast(
  8711. {
  8712. "type": "billing_charge_failed",
  8713. "printer_id": printer_id,
  8714. "printer_name": billing_printer_name,
  8715. "filename": billing_filename,
  8716. "archive_id": archive_id,
  8717. }
  8718. )
  8719. except Exception as notification_error:
  8720. logger.error(
  8721. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  8722. archive_id,
  8723. notification_error,
  8724. )
  8725. async def _notify_billing_charge_failed() -> None:
  8726. try:
  8727. async with async_session() as notification_db:
  8728. await notification_service.on_billing_charge_failed(
  8729. printer_id,
  8730. billing_printer_name,
  8731. billing_filename,
  8732. archive_id,
  8733. billing_error,
  8734. notification_db,
  8735. )
  8736. except Exception as provider_error:
  8737. logger.error(
  8738. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  8739. archive_id,
  8740. provider_error,
  8741. exc_info=True,
  8742. )
  8743. spawn_background_task(
  8744. _notify_billing_charge_failed(),
  8745. name=f"billing-charge-failed-{archive_id}",
  8746. )
  8747. log_timing("Finance charge update")
  8748. # Write independent print log entry (separate table, never touches archives)
  8749. # The run's id, for the energy work below: the archive's newest run is
  8750. # the one started last, which with plates of it on two printers need not
  8751. # be the one that just ended.
  8752. completed_run_id: int | None = None
  8753. async def _write_run(db):
  8754. # Retried on a locked SQLite database: a run left open here would be
  8755. # closed again by the next reconnect's reconcile.
  8756. nonlocal completed_run_id
  8757. from backend.app.models.archive import PrintArchive
  8758. from backend.app.services.print_log import discard_open_runs, record_archive_wear, write_log_entry
  8759. archive = await db.get(PrintArchive, archive_id)
  8760. if archive is None:
  8761. # Deleted while it printed: its run has nothing left to end on.
  8762. discarded = await discard_open_runs(db, printer_id)
  8763. await db.commit()
  8764. await _announce_discarded_runs(discarded, printer_id)
  8765. if archive:
  8766. # Back-fill created_by_id on reprint (#730): reprint reuses the
  8767. # source archive row rather than creating a new one, so an
  8768. # archive that was auto-created from a printer-initiated
  8769. # print (created_by_id=NULL) would otherwise stay unattributed
  8770. # forever. When we have a print-session user AND the archive
  8771. # has no attribution yet, credit the current user. Never
  8772. # overwrite an existing attribution — the original uploader
  8773. # keeps ownership.
  8774. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  8775. if archive.created_by_id is None and _print_user_id is not None:
  8776. archive.created_by_id = _print_user_id
  8777. p_info = printer_manager.get_printer(printer_id)
  8778. # Per-run actuals — written to PrintLogEntry so stats reflect
  8779. # what THIS print actually used, not the source archive's
  8780. # first-run values (#1378). Helper handles the partial-print
  8781. # math (failed / cancelled / stopped get scaled to progress
  8782. # or to tracked spool deltas).
  8783. _run_status = data.get("status", "completed")
  8784. # #2614: scope the per-run estimate to the printed plate. For a
  8785. # multi-plate 3MF dispatched one plate at a time, the archive's
  8786. # filament/cost are the whole-file totals; the PrintLogEntry must
  8787. # reflect only this plate. No effect on single-plate archives (the
  8788. # plate estimate equals the whole-file value) or on the tracker
  8789. # path (measured spool deltas win in _compute_run_filament_grams).
  8790. _est_full_path = (
  8791. app_settings.base_dir / archive.file_path if archive.file_path else None
  8792. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8793. # The plate that printed, as billing reads it: a reprint of
  8794. # another plate must not log the archive's first plate.
  8795. _run_plate_id = billing_plate_id if billing_plate_id is not None else notify_plate_id
  8796. _est_grams, _est_cost = _plate_scoped_run_estimate(archive, _est_full_path, _run_plate_id)
  8797. if _run_plate_id is None:
  8798. _run_plate_id = archive.plate_id
  8799. _run_grams = _compute_run_filament_grams(
  8800. _run_status,
  8801. _est_grams,
  8802. data.get("last_progress", data.get("progress")),
  8803. usage_results,
  8804. )
  8805. # Per-run cost — prefer usage_results sum. For partial prints
  8806. # we deliberately skip the topup-to-estimate logic in
  8807. # usage_tracker (which assumes the print completed); the raw
  8808. # tracked-spool sum is closer to what THIS run actually cost.
  8809. _run_cost: float | None = None
  8810. if usage_results:
  8811. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  8812. if _run_cost is None and _run_status != "completed":
  8813. _run_cost = spoolman_run_cost
  8814. if _run_cost is None and _run_status == "completed":
  8815. _run_cost = _est_cost
  8816. from backend.app.models.printer import Printer as _Printer
  8817. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  8818. run_entry = await write_log_entry(
  8819. db,
  8820. archive_id=archive.id,
  8821. # Captured by _update_queue_status above; None for
  8822. # printer-initiated prints with no queue row. Batch
  8823. # cost/energy roll-up joins on it (#342).
  8824. queue_item_id=queue_item_id,
  8825. status=_run_status,
  8826. print_name=archive.print_name,
  8827. # The plate this run printed, as the estimate above takes
  8828. # it; the archive's own is the latest run's.
  8829. plate_id=_run_plate_id,
  8830. printer_name=p_info.name if p_info else None,
  8831. printer_id=printer_id,
  8832. started_at=archive.started_at,
  8833. completed_at=archive.completed_at,
  8834. filament_type=archive.filament_type,
  8835. filament_color=archive.filament_color,
  8836. filament_used_grams=_run_grams,
  8837. cost=_run_cost,
  8838. wear_cost_per_hour=_wear_rate,
  8839. failure_reason=archive.failure_reason,
  8840. thumbnail_path=archive.thumbnail_path,
  8841. created_by_id=archive.created_by_id,
  8842. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  8843. # Reconciled completions have an unknown real end time —
  8844. # log 0 duration instead of the whole disconnect gap (#2592),
  8845. # unless it was estimated (#3310).
  8846. reconciled=bool(data.get("_reconciled")) and not data.get("_reconciled_completed_at"),
  8847. # Its time is the estimate or nothing, never measured (#3310).
  8848. duration_unmeasured=bool(data.get("_reconciled")),
  8849. # The real end of a print stopped while its printer was offline.
  8850. replaces_offline_stop=True,
  8851. )
  8852. await record_archive_wear(db, archive, run_entry)
  8853. await db.commit()
  8854. completed_run_id = run_entry.id
  8855. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  8856. try:
  8857. from backend.app.core.database import run_with_retry
  8858. await run_with_retry(_write_run, label="print log entry")
  8859. except Exception as e:
  8860. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  8861. await _publish_run_completed(completed_run_id, printer_id)
  8862. log_timing("Print log entry")
  8863. # Run slow operations as background tasks to avoid blocking the event loop
  8864. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  8865. async def _background_energy_calculation():
  8866. """Calculate and save energy usage in background.
  8867. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  8868. backend restart no longer loses per-print energy data).
  8869. """
  8870. try:
  8871. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  8872. async with async_session() as db:
  8873. from backend.app.models.archive import PrintArchive
  8874. from backend.app.models.print_log import PrintLogEntry
  8875. from backend.app.services.print_log import energy_start_of
  8876. archive = await db.get(PrintArchive, archive_id)
  8877. if archive is None:
  8878. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  8879. return
  8880. # The ended run's own start reading: the archive's is its
  8881. # latest start's, maybe another plate's on another printer.
  8882. run_row = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  8883. start = energy_start_of(run_row, archive)
  8884. if start is None:
  8885. logger.info("[ENERGY-BG] No start kWh recorded for archive %s's run", archive_id)
  8886. return
  8887. starting_kwh = start.kwh
  8888. candidates = await energy_plug_candidates(db, printer_id)
  8889. if not candidates:
  8890. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  8891. return
  8892. # Same ordering as the start reading, so the delta below is
  8893. # against the counter that produced `starting_kwh` (#2859).
  8894. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  8895. if selected is None:
  8896. logger.warning(
  8897. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  8898. printer_id,
  8899. ", ".join(plug.name for plug in candidates),
  8900. )
  8901. return
  8902. plug, energy = selected
  8903. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  8904. energy_used = round(energy["total"] - starting_kwh, 4)
  8905. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  8906. if energy_used < 0:
  8907. logger.warning(
  8908. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  8909. archive_id,
  8910. starting_kwh,
  8911. energy["total"],
  8912. )
  8913. return
  8914. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  8915. # Each hour of the print at the price of that hour (#1251). If
  8916. # that fails, the last price known, as before, rather than no
  8917. # energy at all. Read first: the session may be unusable after.
  8918. last_price = await stored_price(db)
  8919. try:
  8920. energy_cost_value = round(
  8921. await print_energy_cost(
  8922. db,
  8923. plug_id=start.plug_id,
  8924. start_at=start.at,
  8925. start_kwh=starting_kwh,
  8926. start_price=start.price,
  8927. end_kwh=energy["total"],
  8928. end_plug_id=plug.id,
  8929. price_now=await current_price(db),
  8930. ),
  8931. 3,
  8932. )
  8933. except Exception as e:
  8934. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  8935. energy_cost_value = round(energy_used * last_price, 3)
  8936. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  8937. # reprint doesn't visually clobber the source archive's energy data
  8938. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  8939. from sqlalchemy import func
  8940. existing_runs = await db.scalar(
  8941. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  8942. )
  8943. if (existing_runs or 0) <= 1:
  8944. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  8945. # we just wrote for THIS print. Either way it's the first run.
  8946. archive.energy_kwh = energy_used
  8947. archive.energy_cost = energy_cost_value
  8948. # The ended run's energy (write_log_entry above ran before this
  8949. # background task, so its energy fields are still NULL). With
  8950. # no run written, none: the archive's newest is another print's.
  8951. if run_row is not None:
  8952. run_row.energy_kwh = energy_used
  8953. run_row.energy_cost = energy_cost_value
  8954. await db.commit()
  8955. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  8956. except Exception as e:
  8957. logger.warning("[ENERGY-BG] Failed: %s", e)
  8958. async def _background_finish_photo() -> str | None:
  8959. """Capture finish photo in background. Returns photo filename if captured."""
  8960. # #2547: set once this function has raised the plate itself (the
  8961. # timelapse path, where the moment producer returned without doing it).
  8962. # Declared out here so the `finally` can lower it again no matter where
  8963. # the capture below fails.
  8964. plate_restored_z: float | None = None
  8965. try:
  8966. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  8967. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  8968. # Read phase: settings + printer + archive in a short session, released
  8969. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  8970. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  8971. # tens of seconds; holding this session across it pinned one pooled
  8972. # connection idle-in-transaction per finishing print (issue #2572).
  8973. async with async_session() as db:
  8974. from backend.app.api.routes.settings import get_setting
  8975. from backend.app.models.archive import PrintArchive
  8976. from backend.app.models.printer import Printer
  8977. capture_enabled = await get_setting(db, "capture_finish_photo")
  8978. if capture_enabled is not None and capture_enabled.lower() != "true":
  8979. return None
  8980. if not archive_id:
  8981. return None
  8982. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  8983. archive = (
  8984. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8985. ).scalar_one_or_none()
  8986. if not printer or not archive:
  8987. return None
  8988. import uuid
  8989. from datetime import datetime
  8990. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  8991. if not archive.file_path:
  8992. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  8993. archive_dir = resolve_archive_dir(archive)
  8994. photo_filename = None
  8995. # Prefer the timelapse last-frame source when a timelapse was
  8996. # recording — it captures the moment after the toolhead parks
  8997. # but before the bed drops, which the live-camera grab below
  8998. # would miss (#1397). Skipped for external cameras (those have
  8999. # their own framing and don't see a Bambu timelapse). Only
  9000. # runs when the USER explicitly enabled timelapse for this
  9001. # print — #1721 removed Bambuddy's force-on at dispatch
  9002. # because it caused per-layer nozzle parking on Smooth-mode
  9003. # slicer profiles.
  9004. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  9005. printer.external_camera_enabled and printer.external_camera_url
  9006. )
  9007. timelapse_still_pending = False
  9008. if prefer_timelapse_source:
  9009. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  9010. archive_id=archive_id,
  9011. archive_dir=archive_dir,
  9012. rotation=getattr(printer, "camera_rotation", 0),
  9013. run_id=completed_run_id,
  9014. )
  9015. # #1721: replacement framing path — on_finish_photo_moment
  9016. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  9017. # parked, bed not yet dropped) and cached the JPEG bytes in
  9018. # _stage22_finish_frames. Consume them now so the saved photo
  9019. # has the better framing instead of the post-bed-drop angle
  9020. # the live-camera fallback below would give.
  9021. if not photo_filename:
  9022. # #1790: on the FINISH-state fallback path the producer
  9023. # task is dispatched back-to-back with this consumer, so
  9024. # a bare pop would race past with an empty result and
  9025. # the RTSP fallback below would collide with the
  9026. # producer's still-in-flight grab (single-client RTSP
  9027. # on Bambu printers). Wait for the producer to finish
  9028. # or give up before touching the cache.
  9029. #
  9030. # #2547: 20s was enough when the producer only ever grabbed a
  9031. # frame. It now also raises the plate first, which costs the
  9032. # settle window before the grab even starts — so the budget has
  9033. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  9034. # under the notification's own photo wait below.
  9035. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  9036. if in_flight is not None:
  9037. try:
  9038. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  9039. except TimeoutError:
  9040. logger.warning(
  9041. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  9042. printer_id,
  9043. )
  9044. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  9045. if cached_frame:
  9046. # Already rotated by the producer (#2708) — rotating again
  9047. # here would undo the fix on the banked-frame path, whose
  9048. # bytes reach the cache having been rotated once already.
  9049. photos_dir = archive_dir / "photos"
  9050. photos_dir.mkdir(parents=True, exist_ok=True)
  9051. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9052. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9053. photo_path = photos_dir / photo_filename
  9054. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  9055. logger.info(
  9056. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  9057. photo_filename,
  9058. len(cached_frame),
  9059. )
  9060. # #2547: the timelapse path reaches the live grab below whenever the
  9061. # video hasn't landed in time — the documented usual outcome on
  9062. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  9063. # returned early for those prints without raising the plate, so
  9064. # without this the photo that actually ships in the notification is
  9065. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  9066. # asked us to fix. The archive still gets the better video frame
  9067. # later; this is about the image the user is sent.
  9068. #
  9069. # Gated on `timelapse_was_active` precisely because that is the
  9070. # condition under which the producer skipped. On every other path it
  9071. # has already raised and lowered the plate, and repeating that here
  9072. # would be a second pointless round trip.
  9073. if (
  9074. not photo_filename
  9075. and data.get("timelapse_was_active")
  9076. and not print_dispatch_context.end_gcode_injected(printer_id)
  9077. ):
  9078. try:
  9079. async with async_session() as db:
  9080. from backend.app.api.routes.settings import get_setting
  9081. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  9082. if restore_setting is None or restore_setting.lower() == "true":
  9083. max_z = await _max_z_for_current_print(
  9084. printer_id, data, logger, bound_archive_id, notify_plate_id
  9085. )
  9086. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  9087. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  9088. plate_restored_z = max_z
  9089. except Exception as e:
  9090. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  9091. # Fallback chain: external camera → buffered live frame →
  9092. # fresh RTSP capture. Only runs if the timelapse path above
  9093. # didn't already produce a photo.
  9094. # Chamber light for the live capture below (#1655).
  9095. async with camera_light(printer if not photo_filename else None):
  9096. if not photo_filename:
  9097. if printer.external_camera_enabled and printer.external_camera_url:
  9098. logger.info("[PHOTO-BG] Using external camera")
  9099. from backend.app.api.routes.camera import live_frame_for_capture
  9100. from backend.app.services.external_camera import capture_frame
  9101. # #2707: the second half of the finish-photo failure — the
  9102. # pre-capture and this fallback both collided with the live
  9103. # view. None here continues down the fallback chain.
  9104. defer, buffered = live_frame_for_capture(printer_id)
  9105. if defer:
  9106. frame_data = buffered
  9107. else:
  9108. frame_data = await capture_frame(
  9109. printer.external_camera_url,
  9110. printer.external_camera_type or "mjpeg",
  9111. snapshot_url=printer.external_camera_snapshot_url,
  9112. )
  9113. if frame_data:
  9114. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  9115. photos_dir = archive_dir / "photos"
  9116. photos_dir.mkdir(parents=True, exist_ok=True)
  9117. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9118. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9119. photo_path = photos_dir / photo_filename
  9120. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  9121. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  9122. else:
  9123. # Check if camera stream is active - use buffered frame to avoid freeze
  9124. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  9125. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  9126. active_chamber_for_printer = [
  9127. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  9128. ]
  9129. buffered_frame = get_buffered_frame(printer_id)
  9130. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  9131. # Use frame from active stream
  9132. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  9133. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  9134. photos_dir = archive_dir / "photos"
  9135. photos_dir.mkdir(parents=True, exist_ok=True)
  9136. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  9137. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  9138. photo_path = photos_dir / photo_filename
  9139. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  9140. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  9141. else:
  9142. # No active stream - capture new frame
  9143. from backend.app.services.camera import capture_finish_photo
  9144. photo_filename = await capture_finish_photo(
  9145. printer_id=printer_id,
  9146. ip_address=printer.ip_address,
  9147. access_code=printer.access_code,
  9148. model=printer.model,
  9149. archive_dir=archive_dir,
  9150. rotation=getattr(printer, "camera_rotation", 0),
  9151. )
  9152. # Write phase: attach the photo in a fresh short-lived session.
  9153. if photo_filename:
  9154. async with async_session() as db:
  9155. from backend.app.models.archive import PrintArchive
  9156. from backend.app.services.print_log import add_run_photo, run_of
  9157. arch = await db.get(PrintArchive, archive_id)
  9158. # The ended print's own list takes it too: the archive's
  9159. # holds every print's.
  9160. run = await run_of(db, archive_id, completed_run_id) if completed_run_id is not None else None
  9161. if arch is not None:
  9162. photos = arch.photos or []
  9163. photos.append(photo_filename)
  9164. arch.photos = photos
  9165. add_run_photo(run, photo_filename)
  9166. await db.commit()
  9167. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  9168. # The short wait above is bounded so a slow printer can't hold up
  9169. # the print-complete notification, which is what the caller is
  9170. # blocking on. When it ran out with the video still on its way,
  9171. # keep waiting off to the side and add the better frame to the
  9172. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  9173. # users, whose videos routinely take minutes to transfer, never get
  9174. # the pre-bed-drop framing this path exists to provide.
  9175. #
  9176. # Spawned here rather than at the point the wait gave up: both this
  9177. # function and the upgrade do a read-modify-write on `photos`, and
  9178. # the live-camera fallback above can take tens of seconds. Starting
  9179. # the upgrade before that write means the two can interleave and one
  9180. # silently drops the other's entry, leaving a JPEG on disk that the
  9181. # gallery never lists.
  9182. if timelapse_still_pending:
  9183. from backend.app.services import archive_work
  9184. spawn_background_task(
  9185. archive_work.held_while(
  9186. archive_id,
  9187. _upgrade_finish_photo_from_timelapse(
  9188. archive_id,
  9189. archive_dir,
  9190. rotation=getattr(printer, "camera_rotation", 0),
  9191. run_id=completed_run_id,
  9192. ),
  9193. ),
  9194. name=f"finish-photo-upgrade-{archive_id}",
  9195. )
  9196. return photo_filename
  9197. except Exception as e:
  9198. logger.warning("[PHOTO-BG] Failed: %s", e)
  9199. return None
  9200. finally:
  9201. # #2547: we raised the plate, so we owe the move back down — even if
  9202. # the capture in between threw. Otherwise the user finds the print
  9203. # pinned under the nozzle.
  9204. if plate_restored_z is not None:
  9205. try:
  9206. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  9207. except Exception as e:
  9208. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  9209. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  9210. # Photo capture task - result will be used by notifications
  9211. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  9212. log_timing("Background tasks scheduled (energy, photo)")
  9213. # Also run smart plug, notifications, and maintenance as background tasks
  9214. print_status = data.get("status", "completed")
  9215. async def _background_smart_plug():
  9216. """Handle smart plug automation in background."""
  9217. try:
  9218. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  9219. async with async_session() as db:
  9220. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  9221. logger.info("[AUTO-OFF-BG] Completed")
  9222. except Exception as e:
  9223. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  9224. async def _background_notifications(finish_photo_filename: str | None = None):
  9225. """Send print complete notifications in background."""
  9226. try:
  9227. logger.info(
  9228. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  9229. )
  9230. async with async_session() as db:
  9231. from backend.app.models.archive import PrintArchive
  9232. from backend.app.models.printer import Printer
  9233. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9234. printer = result.scalar_one_or_none()
  9235. printer_name = printer.name if printer else f"Printer {printer_id}"
  9236. archive_data = None
  9237. if archive_id:
  9238. from backend.app.models.print_log import PrintLogEntry
  9239. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  9240. archive = archive_result.scalar_one_or_none()
  9241. # The run that ended: the archive shows its latest, which
  9242. # with another plate of it printing elsewhere is not this.
  9243. run = await db.get(PrintLogEntry, completed_run_id) if completed_run_id is not None else None
  9244. run_started = run.started_at if run is not None else archive.started_at if archive else None
  9245. run_completed = run.completed_at if run is not None else archive.completed_at if archive else None
  9246. if archive:
  9247. # Actual elapsed time from started_at/completed_at when both are
  9248. # populated (every terminal status sets completed_at after #1198).
  9249. # Falls back to None so the notification path can decide whether to
  9250. # render the slicer estimate as a last resort.
  9251. actual_time_seconds = None
  9252. # Unknown for a completion reconciled at reconnect: the
  9253. # print ended while the printer was offline and
  9254. # completed_at is the reconnect, so the gap would read
  9255. # as the duration -- 14 h for a night offline (DB-C9).
  9256. # An estimated end (#3310) gives the estimate.
  9257. if (
  9258. run_started
  9259. and run_completed
  9260. and (not data.get("_reconciled") or data.get("_reconciled_completed_at"))
  9261. ):
  9262. elapsed = (run_completed - run_started).total_seconds()
  9263. if elapsed > 0:
  9264. actual_time_seconds = int(elapsed)
  9265. archive_data = {
  9266. "print_time_seconds": archive.print_time_seconds,
  9267. "actual_time_seconds": actual_time_seconds,
  9268. "actual_filament_grams": archive.filament_used_grams,
  9269. "failure_reason": run.failure_reason if run is not None else archive.failure_reason,
  9270. "created_by_id": archive.created_by_id,
  9271. }
  9272. # Scale filament usage for partial prints
  9273. if print_status != "completed" and archive.filament_used_grams:
  9274. progress = data.get("progress") or 0
  9275. scale = _partial_progress_scale(progress)
  9276. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  9277. archive_data["progress"] = progress
  9278. # Pass per-slot data from archive.extra_data
  9279. if archive.extra_data and archive.extra_data.get("filament_slots"):
  9280. slots = archive.extra_data["filament_slots"]
  9281. if print_status != "completed":
  9282. scale = _partial_progress_scale(data.get("progress"))
  9283. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  9284. archive_data["filament_slots"] = slots
  9285. # Scope project-summed totals down to the plate that was
  9286. # actually printed — see _scope_notification_archive_data_to_plate
  9287. # for the why (#1785).
  9288. archive_data = _scope_notification_archive_data_to_plate(
  9289. archive_data,
  9290. archive.file_path,
  9291. notify_plate_id,
  9292. print_status,
  9293. data.get("progress"),
  9294. app_settings.base_dir,
  9295. )
  9296. # Enrich filament_grams from usage_results when archive has no 3MF data
  9297. if not archive_data.get("actual_filament_grams") and usage_results:
  9298. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  9299. if total_from_usage > 0:
  9300. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  9301. # Pass usage tracker results for AMS slot info in notifications
  9302. if usage_results:
  9303. archive_data["usage_results"] = usage_results
  9304. # Which archive and print it was (archive redesign).
  9305. archive_data["archive_id"] = archive_id
  9306. archive_data["run_id"] = completed_run_id
  9307. # Add finish photo URL and image bytes if available
  9308. if finish_photo_filename:
  9309. photo_url, photo_bytes = await _finish_photo_for_notification(
  9310. db, archive, archive_id, finish_photo_filename
  9311. )
  9312. if photo_url:
  9313. archive_data["finish_photo_url"] = photo_url
  9314. if photo_bytes:
  9315. archive_data["image_data"] = photo_bytes
  9316. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  9317. await notification_service.on_print_complete(
  9318. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  9319. )
  9320. else:
  9321. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  9322. # Post-print outcome confirmation (#1898). Runs in this
  9323. # background task so the finish photo fetched above rides
  9324. # along with the prompt.
  9325. if print_status == "completed" and archive_id:
  9326. await _dispatch_outcome_confirmation_safely(
  9327. db, printer_id, printer_name, data, archive_id, archive_data, run_id=completed_run_id
  9328. )
  9329. # Send user-specific email notification
  9330. if archive_data:
  9331. created_by_id = archive_data.get("created_by_id")
  9332. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  9333. await _dispatch_user_print_email(
  9334. print_status,
  9335. created_by_id,
  9336. printer_name,
  9337. raw_filename,
  9338. db,
  9339. image_data=archive_data.get("image_data"),
  9340. finish_photo_url=archive_data.get("finish_photo_url"),
  9341. )
  9342. logger.info("[NOTIFY-BG] Completed")
  9343. except Exception as e:
  9344. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  9345. async def _background_maintenance_check():
  9346. """Check for maintenance due in background."""
  9347. if print_status != "completed":
  9348. return
  9349. try:
  9350. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  9351. async with async_session() as db:
  9352. from backend.app.models.printer import Printer
  9353. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9354. printer = result.scalar_one_or_none()
  9355. printer_name = printer.name if printer else f"Printer {printer_id}"
  9356. await ensure_default_types(db)
  9357. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  9358. attention = [
  9359. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  9360. ]
  9361. items_needing_attention = [
  9362. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  9363. for item in attention
  9364. ]
  9365. if items_needing_attention:
  9366. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  9367. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  9368. # MQTT relay - publish maintenance alerts
  9369. for item in attention:
  9370. current_value, threshold, unit = maintenance_alert_values(item)
  9371. try:
  9372. await mqtt_relay.on_maintenance_alert(
  9373. printer_id=printer_id,
  9374. printer_name=printer_name,
  9375. maintenance_type=item.maintenance_type_name,
  9376. current_value=current_value,
  9377. threshold=threshold,
  9378. unit=unit,
  9379. )
  9380. except Exception:
  9381. pass # Don't fail if MQTT fails
  9382. else:
  9383. logger.info("[MAINT-BG] Completed (no items need attention)")
  9384. except Exception as e:
  9385. logger.warning("[MAINT-BG] Failed: %s", e)
  9386. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  9387. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  9388. # Notification task waits for photo capture to complete first (with timeout).
  9389. # When a timelapse was recording, photo sourcing polls the per-print
  9390. # timelapse for up to 60s (#1397) — extend the budget so the notification
  9391. # carries the correct bed-up photo instead of falling through to the
  9392. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  9393. #
  9394. # #2547: both budgets now have to cover a plate restore as well.
  9395. #
  9396. # Without timelapse, the wait is on the moment producer, which raises the
  9397. # plate before its grab — so this has to outlast that producer's own budget.
  9398. #
  9399. # With timelapse, the capture polls up to
  9400. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  9401. # falls back to a live grab, which is the case that raises the plate. At the
  9402. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  9403. # restore would have moved the plate for a photo nobody waited for.
  9404. photo_wait_timeout = (
  9405. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  9406. if data.get("timelapse_was_active")
  9407. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  9408. )
  9409. async def _photo_then_notify():
  9410. """Wait for photo capture, then send notification with photo URL."""
  9411. finish_photo = None
  9412. try:
  9413. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  9414. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  9415. except TimeoutError:
  9416. logger.warning(
  9417. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  9418. photo_wait_timeout,
  9419. )
  9420. except Exception as e:
  9421. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  9422. try:
  9423. await _background_notifications(finish_photo)
  9424. except Exception as e:
  9425. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  9426. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  9427. # Stitch external camera layer timelapse if session was active
  9428. print_status = data.get("status", "completed")
  9429. async def _background_layer_timelapse():
  9430. """Stitch layer timelapse and attach to archive."""
  9431. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  9432. try:
  9433. if print_status == "completed":
  9434. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  9435. # The run the frames belong to, read before the stitch: it can
  9436. # take long enough for the archive to start printing again.
  9437. run_started_at = None
  9438. if archive_id:
  9439. async with async_session() as db:
  9440. run_archive = await ArchiveService(db).get_archive(archive_id)
  9441. run_started_at = run_archive.started_at if run_archive else None
  9442. timelapse_path = await tl_complete(printer_id)
  9443. if timelapse_path and archive_id:
  9444. await _attach_layer_timelapse(
  9445. archive_id, timelapse_path, notify_plate_id, run_started_at, run_id=completed_run_id
  9446. )
  9447. elif timelapse_path:
  9448. # Timelapse created but no archive - just clean up
  9449. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  9450. else:
  9451. # Print failed or cancelled - cancel timelapse session
  9452. cancel_session(printer_id)
  9453. logger.info(
  9454. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  9455. )
  9456. except Exception as e:
  9457. logger.warning("[LAYER-TL] Failed: %s", e)
  9458. # A completed print's session left _active_sessions when its stitch
  9459. # began: the one there now belongs to the next print, which may have
  9460. # started during the stitch, and must not lose its frames.
  9461. if print_status != "completed":
  9462. try:
  9463. cancel_session(printer_id)
  9464. except Exception:
  9465. pass # Best-effort timelapse session cancellation on error
  9466. from backend.app.services import archive_work
  9467. # Held through the stitch, which can take longer than a merge waits after
  9468. # a print (archive redesign P2).
  9469. layer_timelapse = _background_layer_timelapse()
  9470. if archive_id:
  9471. layer_timelapse = archive_work.held_while(archive_id, layer_timelapse)
  9472. spawn_background_task(layer_timelapse, name="background-layer-timelapse")
  9473. log_timing("All background tasks scheduled")
  9474. # Auto-scan for timelapse if recording was active during the print
  9475. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  9476. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  9477. # Schedule timelapse scan as background task with retries
  9478. # The printer needs time to encode the video after print completion
  9479. _schedule_timelapse_scan(archive_id, printer_id, plate_id=notify_plate_id, run_id=completed_run_id)
  9480. log_timing("Timelapse scan scheduled")
  9481. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  9482. # AMS sensor history recording
  9483. _ams_history_task: asyncio.Task | None = None
  9484. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  9485. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  9486. def _retention_days(stored: str | None, default: int) -> int:
  9487. """A history retention setting as days to keep: at least 1, the default
  9488. when unset or unreadable. A stored 0 or less (the API took one before it
  9489. had a minimum) would put the cutoff at now and delete all history."""
  9490. try:
  9491. return max(1, int(stored)) if stored is not None else default
  9492. except (TypeError, ValueError):
  9493. return default
  9494. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  9495. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  9496. _ams_alarm_cooldown: dict[str, datetime] = {}
  9497. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  9498. # (printer_id, ams_id) already reported as sending the drop index and no
  9499. # percentage. Logged once each so a supported printer that turns out to do this
  9500. # shows up in a support bundle rather than as a user wondering where the
  9501. # humidity reading went -- see the note at the read site below (#3140).
  9502. _ams_index_only_logged: set[tuple[int, int]] = set()
  9503. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  9504. """Temperature at which the AMS alarm fires, falling back to the display band.
  9505. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  9506. when a notification was sent as well, which is why a room above it made the
  9507. alarm fire once an hour for as long as the weather lasted -- and the only way
  9508. to stop that was to raise the display band and lose the colour that says the
  9509. unit is warm (#2905).
  9510. Unset resolves to the fair threshold, so an install that never sets one is
  9511. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  9512. so that arrives here as a string and is handled by the same branch as any
  9513. other unparseable value -- there is no separate sentinel to keep in sync.
  9514. A non-positive value is refused rather than honoured: zero would alarm
  9515. permanently, and it is far more likely to be a cleared field than a
  9516. deliberate choice.
  9517. """
  9518. if raw_alarm_value is None:
  9519. return fair_threshold
  9520. try:
  9521. value = float(raw_alarm_value)
  9522. except (TypeError, ValueError):
  9523. return fair_threshold
  9524. if not math.isfinite(value) or value <= 0:
  9525. return fair_threshold
  9526. return value
  9527. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  9528. # through a cycle and the cool-down after it (#1802). Stored in the settings
  9529. # table rather than alongside _ams_alarm_cooldown above, because a restart
  9530. # partway through a cool-down would otherwise resume alarming about heat the
  9531. # user asked for — the same internal-timestamp-row pattern as
  9532. # support.py's debug_logging_enabled_at.
  9533. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  9534. # Upper bound on that suppression. The latch normally clears as soon as the unit
  9535. # reads at or below the threshold; see utils.ams_drying for why this cap only
  9536. # matters when it never does.
  9537. AMS_DRYING_GRACE_MINUTES = 120
  9538. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  9539. """Read the persisted per-AMS drying latch, dropping entries out of window.
  9540. Anything older than the grace cap would expire on its next visit anyway, so
  9541. discarding it here costs nothing and stops rows for deleted printers from
  9542. accumulating.
  9543. Stamps ahead of now get two defences, because a box whose clock jumps
  9544. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  9545. ones are discarded outright, and the rest are clamped to now. Without the
  9546. clamp the cap would measure from a moment that has not happened yet and hold
  9547. the alarm quiet for the skew on top of the cap. One unnecessary notification
  9548. after a clock jump is a far better failure than an alarm silently disabled
  9549. for hours.
  9550. """
  9551. from backend.app.models.settings import Settings
  9552. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9553. setting = result.scalar_one_or_none()
  9554. if not setting or not setting.value:
  9555. return {}
  9556. try:
  9557. raw = json.loads(setting.value)
  9558. except (ValueError, TypeError):
  9559. return {} # Corrupted row → no latch, alarms behave as they did before
  9560. if not isinstance(raw, dict):
  9561. return {}
  9562. now = datetime.now(timezone.utc)
  9563. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  9564. latch: dict[str, datetime] = {}
  9565. for key, value in raw.items():
  9566. try:
  9567. stamp = datetime.fromisoformat(str(value))
  9568. except (ValueError, TypeError):
  9569. continue
  9570. if stamp.tzinfo is None:
  9571. stamp = stamp.replace(tzinfo=timezone.utc)
  9572. if not (now - window <= stamp <= now + window):
  9573. continue
  9574. # Nothing may sit in the future: suppression is measured as now minus
  9575. # the stamp, so a stamp ahead of now would extend it by the skew on top
  9576. # of the cap. Clamping the survivors keeps the cap an actual cap.
  9577. latch[str(key)] = min(stamp, now)
  9578. return latch
  9579. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  9580. """Persist the latch, writing only when it actually changed.
  9581. Adds the session change but does not commit — the caller's own commit
  9582. carries it, so the latch lands in the same transaction as the sensor rows
  9583. that produced it.
  9584. """
  9585. from backend.app.models.settings import Settings
  9586. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  9587. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  9588. setting = result.scalar_one_or_none()
  9589. if setting is None:
  9590. # Don't create the row on installs that never dry anything.
  9591. if payload != "{}":
  9592. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  9593. elif setting.value != payload:
  9594. setting.value = payload
  9595. def _ams_has_filament(ams_data: dict) -> bool:
  9596. """True if this AMS unit has at least one tray slot holding filament.
  9597. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  9598. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  9599. still report sensor readings, but those readings are ambient and not
  9600. actionable: no filament to dry, no humidity to push down. #1619 — gate
  9601. humidity/temperature alarms on this check so empty units don't generate
  9602. hourly noise. Sensor history still records regardless so the UI charts
  9603. stay continuous.
  9604. Fallback path inspects the `tray` array's `tray_type` fields for setups
  9605. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  9606. """
  9607. bits = ams_data.get("tray_exist_bits")
  9608. if isinstance(bits, str) and bits.strip():
  9609. try:
  9610. return int(bits, 16) > 0
  9611. except ValueError:
  9612. pass
  9613. trays = ams_data.get("tray")
  9614. if isinstance(trays, list):
  9615. return any(
  9616. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  9617. )
  9618. return False
  9619. async def record_ams_history():
  9620. """Background task to record AMS humidity and temperature data."""
  9621. logger = logging.getLogger(__name__)
  9622. # Wait a short time for MQTT connections to establish on startup
  9623. await asyncio.sleep(10)
  9624. while True:
  9625. try:
  9626. from backend.app.models.ams_history import AMSSensorHistory
  9627. from backend.app.models.printer import Printer
  9628. from backend.app.models.settings import Settings
  9629. async with async_session() as db:
  9630. # Get all active printers
  9631. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9632. printers = result.scalars().all()
  9633. # Get alarm thresholds from settings
  9634. humidity_threshold = 60.0 # Default: fair threshold
  9635. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  9636. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  9637. setting = result.scalar_one_or_none()
  9638. if setting:
  9639. try:
  9640. humidity_threshold = float(setting.value)
  9641. except (ValueError, TypeError):
  9642. pass # Keep default threshold if stored value is invalid
  9643. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  9644. setting = result.scalar_one_or_none()
  9645. if setting:
  9646. try:
  9647. temp_fair_threshold = float(setting.value)
  9648. except (ValueError, TypeError):
  9649. pass # Keep default threshold if stored value is invalid
  9650. # The alarm gets its own threshold, seeded from the resolved fair
  9651. # value so an install that has never set one behaves exactly as
  9652. # it did before (#2905). ams_temp_fair decides when the card turns
  9653. # amber; 35 C is a reasonable place to change a colour and not a
  9654. # reasonable place to page someone. A room above it makes the
  9655. # alarm fire once an hour for as long as the weather lasts, and
  9656. # the only way to stop it was to raise the display band and lose
  9657. # the colour that says the unit is warm.
  9658. #
  9659. # An unset value is stored as the literal "None", which the except
  9660. # below swallows the same way it swallows garbage -- so the
  9661. # fallback costs nothing and needs no sentinel of its own.
  9662. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  9663. setting = result.scalar_one_or_none()
  9664. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  9665. temp_fair_threshold, setting.value if setting else None
  9666. )
  9667. # Per-filament humidity threshold overrides (#1605) — resolved
  9668. # per-AMS below from the loaded tray types. Reuses the same
  9669. # resolver as the auto-drying scheduler so behavior stays in
  9670. # lockstep across both consumers.
  9671. from backend.app.services.print_scheduler import PrintScheduler
  9672. per_type_humidity_thresholds: dict[str, int] = {}
  9673. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  9674. setting = result.scalar_one_or_none()
  9675. if setting and setting.value:
  9676. try:
  9677. raw = json.loads(setting.value)
  9678. if isinstance(raw, dict):
  9679. for k, v in raw.items():
  9680. try:
  9681. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  9682. v
  9683. )
  9684. except (TypeError, ValueError):
  9685. continue
  9686. except (ValueError, TypeError):
  9687. pass # Invalid JSON → no overrides, fall through to global threshold
  9688. # Per-AMS drying latch (#1802), loaded once per pass and written
  9689. # back below only if a unit changed it.
  9690. drying_latch = await _load_ams_drying_latch(db)
  9691. drying_latch_before = dict(drying_latch)
  9692. recorded_count = 0
  9693. for printer in printers:
  9694. # Get current state from printer manager
  9695. state = printer_manager.get_status(printer.id)
  9696. if not state or not state.connected or not state.raw_data:
  9697. continue # Skip disconnected printers - don't use stale data
  9698. raw_data = state.raw_data
  9699. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  9700. continue
  9701. # Record data for each AMS unit
  9702. for ams_data in raw_data["ams"]:
  9703. ams_id = int(ams_data.get("id", 0))
  9704. # Percentage only. The 1-5 index is inverted, so
  9705. # charting it as a percentage drew the wettest units as
  9706. # the driest (#3140); a unit that reports no percentage
  9707. # leaves a gap in the chart instead. See
  9708. # utils/ams_humidity.
  9709. humidity = ams_humidity_percent(ams_data)
  9710. # No supported printer is known to send the index
  9711. # alone -- the report came from unsupported firmware,
  9712. # and no install has been seen using the old fallback.
  9713. # "Known" is doing work there, so say so once per unit:
  9714. # the alternative is a silent blank card.
  9715. if humidity is None and ams_data.get("humidity") is not None:
  9716. unit_key = (printer.id, ams_id)
  9717. if unit_key not in _ams_index_only_logged:
  9718. _ams_index_only_logged.add(unit_key)
  9719. logger.info(
  9720. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  9721. "percentage. The index is inverted and is not shown as a percentage "
  9722. "(#3140), so this unit has no humidity reading, chart or alarm. "
  9723. "Please report this with the printer and AMS firmware versions.",
  9724. printer.name,
  9725. ams_id,
  9726. )
  9727. # Get temperature
  9728. temperature = None
  9729. temp_str = ams_data.get("temp")
  9730. if temp_str is not None:
  9731. try:
  9732. temperature = float(temp_str)
  9733. except (ValueError, TypeError):
  9734. pass # Skip unparseable temperature value
  9735. # Skip if no data
  9736. if humidity is None and temperature is None:
  9737. continue
  9738. # Record the data point
  9739. history = AMSSensorHistory(
  9740. printer_id=printer.id,
  9741. ams_id=ams_id,
  9742. humidity=humidity,
  9743. # Both columns hold the same reading now that the
  9744. # index can no longer reach ``humidity``. Writing it
  9745. # through the same value also stops a genuine 0%
  9746. # from being stored as NULL, which the old truthiness
  9747. # test did.
  9748. humidity_raw=humidity,
  9749. temperature=temperature,
  9750. )
  9751. db.add(history)
  9752. recorded_count += 1
  9753. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  9754. is_ams_ht = ams_id >= 128
  9755. if is_ams_ht:
  9756. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  9757. else:
  9758. ams_label = f"AMS-{chr(65 + ams_id)}"
  9759. # Skip alarm dispatch for empty AMS units — humidity /
  9760. # temperature readings are ambient with no filament to
  9761. # protect, and the hourly notification just becomes
  9762. # noise. Sensor history was already recorded above so
  9763. # the UI charts stay continuous (#1619). Per-AMS check
  9764. # so a multi-AMS setup with one loaded + one empty
  9765. # still alarms on the loaded unit.
  9766. if not _ams_has_filament(ams_data):
  9767. continue
  9768. # Resolve per-filament humidity threshold for this AMS
  9769. # unit (#1605). Falls back to the global ams_humidity_fair
  9770. # when no per-type overrides are configured.
  9771. trays = ams_data.get("tray", []) or []
  9772. effective_humidity_threshold = float(
  9773. PrintScheduler.resolve_humidity_threshold(
  9774. trays, per_type_humidity_thresholds, int(humidity_threshold)
  9775. )
  9776. )
  9777. # Check humidity alarm (only if above threshold)
  9778. if humidity is not None and humidity > effective_humidity_threshold:
  9779. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  9780. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9781. now = datetime.now(timezone.utc)
  9782. if (
  9783. last_alarm is None
  9784. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9785. ):
  9786. _ams_alarm_cooldown[cooldown_key] = now
  9787. logger.info(
  9788. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  9789. )
  9790. try:
  9791. # Call different notification method based on AMS type
  9792. if is_ams_ht:
  9793. await notification_service.on_ams_ht_humidity_high(
  9794. printer.id,
  9795. printer.name,
  9796. ams_label,
  9797. humidity,
  9798. effective_humidity_threshold,
  9799. db,
  9800. )
  9801. else:
  9802. await notification_service.on_ams_humidity_high(
  9803. printer.id,
  9804. printer.name,
  9805. ams_label,
  9806. humidity,
  9807. effective_humidity_threshold,
  9808. db,
  9809. )
  9810. except Exception as e:
  9811. logger.warning("Failed to send humidity alarm: %s", e)
  9812. # A drying cycle heats the unit far past ams_temp_fair on
  9813. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  9814. # AMS-HT, against a 35 C default — so the alarm fired
  9815. # once an hour for the whole cycle and kept firing while
  9816. # the unit cooled back down (#1802). Latch on the
  9817. # firmware's own drying state and hold until the reading
  9818. # returns to normal. Humidity is deliberately left alone:
  9819. # it falls during drying, which is the whole point.
  9820. latch_key = f"{printer.id}:{ams_id}"
  9821. # The latch releases at `threshold`, so it takes the alarm
  9822. # number too. Handing it the display band would strand the
  9823. # latch on any unit that settles back above it -- a room
  9824. # where the AMS rests at 37.7 C never returns under a 35 C
  9825. # band, so the latch could only expire on the grace cap
  9826. # rather than releasing when the unit had actually cooled.
  9827. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  9828. drying_active=is_drying_active(ams_data),
  9829. temperature=temperature,
  9830. threshold=temp_alarm_threshold,
  9831. latched_at=drying_latch.get(latch_key),
  9832. now=datetime.now(timezone.utc),
  9833. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  9834. )
  9835. if new_latch is None:
  9836. drying_latch.pop(latch_key, None)
  9837. else:
  9838. drying_latch[latch_key] = new_latch
  9839. # Check temperature alarm (only if above threshold)
  9840. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  9841. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  9842. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9843. now = datetime.now(timezone.utc)
  9844. if (
  9845. last_alarm is None
  9846. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9847. ):
  9848. _ams_alarm_cooldown[cooldown_key] = now
  9849. logger.info(
  9850. f"Sending temperature alarm for {printer.name} {ams_label}: "
  9851. f"{temperature}°C > {temp_alarm_threshold}°C"
  9852. )
  9853. try:
  9854. # Call different notification method based on AMS type
  9855. if is_ams_ht:
  9856. # The reported threshold has to be the one
  9857. # that fired, or the message says "> 35 °C"
  9858. # while firing at 45.
  9859. await notification_service.on_ams_ht_temperature_high(
  9860. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9861. )
  9862. else:
  9863. await notification_service.on_ams_temperature_high(
  9864. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9865. )
  9866. except Exception as e:
  9867. logger.warning("Failed to send temperature alarm: %s", e)
  9868. if drying_latch != drying_latch_before:
  9869. await _save_ams_drying_latch(db, drying_latch)
  9870. await db.commit()
  9871. if recorded_count > 0:
  9872. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  9873. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  9874. global _ams_cleanup_counter
  9875. _ams_cleanup_counter += 1
  9876. if _ams_cleanup_counter >= 288:
  9877. _ams_cleanup_counter = 0
  9878. # Get retention days from settings
  9879. from backend.app.models.settings import Settings
  9880. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  9881. setting = result.scalar_one_or_none()
  9882. retention_days = _retention_days(setting.value if setting else None, AMS_HISTORY_RETENTION_DAYS)
  9883. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9884. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  9885. await db.commit()
  9886. if result.rowcount > 0:
  9887. logger.info(
  9888. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  9889. )
  9890. # Wait until next recording interval
  9891. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  9892. except asyncio.CancelledError:
  9893. break
  9894. except Exception as e:
  9895. logger.warning("AMS history recording failed: %s", e)
  9896. await asyncio.sleep(60) # Wait a bit before retrying
  9897. def start_ams_history_recording():
  9898. """Start the AMS history recording background task."""
  9899. global _ams_history_task
  9900. if _ams_history_task is None:
  9901. _ams_history_task = asyncio.create_task(record_ams_history())
  9902. logging.getLogger(__name__).info("AMS history recording started")
  9903. def stop_ams_history_recording():
  9904. """Stop the AMS history recording background task."""
  9905. global _ams_history_task
  9906. if _ams_history_task:
  9907. _ams_history_task.cancel()
  9908. _ams_history_task = None
  9909. logging.getLogger(__name__).info("AMS history recording stopped")
  9910. # Printer sensor history recording (nozzle / bed / chamber)
  9911. _printer_sensor_history_task: asyncio.Task | None = None
  9912. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  9913. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  9914. _printer_sensor_cleanup_counter = 0
  9915. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  9916. # MQTT parser writes, so we don't need to handle per-model field aliases here
  9917. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  9918. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  9919. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  9920. _SENSOR_TARGET_KEYS = {
  9921. "nozzle": "nozzle_target",
  9922. "nozzle_2": "nozzle_2_target",
  9923. "bed": "bed_target",
  9924. "chamber": "chamber_target",
  9925. }
  9926. async def record_printer_sensor_history():
  9927. """Background task to record nozzle / bed / chamber readings.
  9928. Pulls from `state.temperatures` (already normalised across all printer
  9929. models by the MQTT parser) rather than re-parsing raw_data, so we get
  9930. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  9931. """
  9932. logger = logging.getLogger(__name__)
  9933. await asyncio.sleep(10)
  9934. while True:
  9935. try:
  9936. from backend.app.models.printer import Printer
  9937. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  9938. from backend.app.models.settings import Settings
  9939. async with async_session() as db:
  9940. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9941. printers = result.scalars().all()
  9942. recorded_count = 0
  9943. for printer in printers:
  9944. state = printer_manager.get_status(printer.id)
  9945. if not state or not state.connected:
  9946. continue
  9947. temps = getattr(state, "temperatures", None) or {}
  9948. if not isinstance(temps, dict):
  9949. continue
  9950. for kind in _SENSOR_KINDS:
  9951. if kind not in temps:
  9952. continue
  9953. try:
  9954. value = float(temps[kind])
  9955. except (ValueError, TypeError):
  9956. continue
  9957. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  9958. target_val: float | None = None
  9959. if target_raw is not None:
  9960. try:
  9961. target_val = float(target_raw)
  9962. except (ValueError, TypeError):
  9963. target_val = None
  9964. db.add(
  9965. PrinterSensorHistory(
  9966. printer_id=printer.id,
  9967. sensor_kind=kind,
  9968. value=value,
  9969. target=target_val,
  9970. )
  9971. )
  9972. recorded_count += 1
  9973. await db.commit()
  9974. if recorded_count > 0:
  9975. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  9976. # Periodic cleanup — once every ~24h at this interval.
  9977. global _printer_sensor_cleanup_counter
  9978. _printer_sensor_cleanup_counter += 1
  9979. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  9980. if _printer_sensor_cleanup_counter >= cleanup_every:
  9981. _printer_sensor_cleanup_counter = 0
  9982. result = await db.execute(
  9983. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  9984. )
  9985. setting = result.scalar_one_or_none()
  9986. retention_days = _retention_days(
  9987. setting.value if setting else None, PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  9988. )
  9989. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9990. cleanup = await db.execute(
  9991. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  9992. )
  9993. await db.commit()
  9994. if cleanup.rowcount > 0:
  9995. logger.info(
  9996. "Cleaned up %s old printer sensor history entries (older than %s days)",
  9997. cleanup.rowcount,
  9998. retention_days,
  9999. )
  10000. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  10001. except asyncio.CancelledError:
  10002. break
  10003. except Exception as e:
  10004. logger.warning("Printer sensor history recording failed: %s", e)
  10005. await asyncio.sleep(60)
  10006. def start_printer_sensor_history_recording():
  10007. global _printer_sensor_history_task
  10008. if _printer_sensor_history_task is None:
  10009. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  10010. logging.getLogger(__name__).info("Printer sensor history recording started")
  10011. def stop_printer_sensor_history_recording():
  10012. global _printer_sensor_history_task
  10013. if _printer_sensor_history_task:
  10014. _printer_sensor_history_task.cancel()
  10015. _printer_sensor_history_task = None
  10016. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  10017. # Printer runtime tracking
  10018. _runtime_tracking_task: asyncio.Task | None = None
  10019. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  10020. # Printers the runtime tracker has seen connected since startup. One of them
  10021. # going offline clears its timestamp, so the time it was away is not counted
  10022. # when it comes back printing (DB-C5). A printer not yet seen -- still
  10023. # connecting after a restart -- keeps it for a grace period: a print that ran
  10024. # on through a Bambuddy restart is counted from the stored timestamp, as before.
  10025. _runtime_seen_connected: set[int] = set()
  10026. # A printer never seen connected this long after the tracker started is
  10027. # offline, not still connecting: its stored timestamp predates a gap too.
  10028. RUNTIME_STARTUP_GRACE_SECONDS = 120
  10029. async def track_printer_runtime():
  10030. """Background task to track printer active runtime (RUNNING state only).
  10031. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  10032. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  10033. which track mechanical wear. Pause time has no motion and no wear, so
  10034. counting it inflates maintenance warnings (#1521).
  10035. """
  10036. logger = logging.getLogger(__name__)
  10037. # Wait for MQTT connections to establish on startup
  10038. await asyncio.sleep(15)
  10039. started = time.monotonic()
  10040. while True:
  10041. try:
  10042. from backend.app.models.printer import Printer
  10043. # Fetch printer IDs in a short-lived read-only session
  10044. async with async_session() as db:
  10045. result = await db.execute(
  10046. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  10047. Printer.is_active.is_(True)
  10048. )
  10049. )
  10050. printer_rows = result.all()
  10051. now = datetime.now(timezone.utc)
  10052. updated_count = 0
  10053. # Update each printer in its own short session to minimise write-lock
  10054. # hold time and avoid blocking critical commits like queue status
  10055. # updates (#897).
  10056. for pid, pname, runtime_secs, last_update in printer_rows:
  10057. state = printer_manager.get_status(pid)
  10058. if not state:
  10059. logger.debug("[%s] Runtime tracking: no state available", pname)
  10060. continue
  10061. if not state.connected:
  10062. logger.debug("[%s] Runtime tracking: not connected", pname)
  10063. offline = pid in _runtime_seen_connected or (
  10064. time.monotonic() - started > RUNTIME_STARTUP_GRACE_SECONDS
  10065. )
  10066. if offline and last_update is not None:
  10067. try:
  10068. async with async_session() as db:
  10069. printer = await db.get(Printer, pid)
  10070. if printer:
  10071. printer.last_runtime_update = None
  10072. await db.commit()
  10073. except Exception as e:
  10074. # Still marked: the next offline tick tries again.
  10075. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  10076. continue
  10077. _runtime_seen_connected.discard(pid)
  10078. continue
  10079. _runtime_seen_connected.add(pid)
  10080. needs_commit = False
  10081. new_runtime = runtime_secs
  10082. new_last_update = last_update
  10083. if state.state == "RUNNING":
  10084. if last_update:
  10085. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  10086. elapsed = (now - lu).total_seconds()
  10087. if elapsed > 0:
  10088. new_runtime = runtime_secs + int(elapsed)
  10089. updated_count += 1
  10090. needs_commit = True
  10091. logger.debug(
  10092. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  10093. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  10094. )
  10095. else:
  10096. needs_commit = True
  10097. logger.debug("[%s] Runtime tracking: first active detection", pname)
  10098. new_last_update = now
  10099. else:
  10100. if last_update is not None:
  10101. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  10102. new_last_update = None
  10103. needs_commit = True
  10104. if needs_commit:
  10105. try:
  10106. async with async_session() as db:
  10107. result = await db.execute(select(Printer).where(Printer.id == pid))
  10108. printer = result.scalar_one_or_none()
  10109. if printer:
  10110. printer.runtime_seconds = new_runtime
  10111. printer.last_runtime_update = new_last_update
  10112. await db.commit()
  10113. except Exception as e:
  10114. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  10115. if updated_count > 0:
  10116. logger.debug("Updated runtime for %s printer(s)", updated_count)
  10117. except asyncio.CancelledError:
  10118. logger.info("Runtime tracking cancelled")
  10119. break
  10120. except Exception as e:
  10121. logger.warning("Runtime tracking failed: %s", e)
  10122. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  10123. def start_runtime_tracking():
  10124. """Start the printer runtime tracking background task."""
  10125. global _runtime_tracking_task
  10126. if _runtime_tracking_task is None:
  10127. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  10128. logging.getLogger(__name__).info("Printer runtime tracking started")
  10129. def stop_runtime_tracking():
  10130. """Stop the printer runtime tracking background task."""
  10131. global _runtime_tracking_task
  10132. if _runtime_tracking_task:
  10133. _runtime_tracking_task.cancel()
  10134. _runtime_tracking_task = None
  10135. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  10136. # SpoolBuddy device watchdog
  10137. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  10138. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  10139. async def _spoolbuddy_watchdog_loop():
  10140. """Periodic check for SpoolBuddy devices that have gone offline."""
  10141. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  10142. while True:
  10143. try:
  10144. await spoolbuddy_watchdog()
  10145. except asyncio.CancelledError:
  10146. break
  10147. except Exception as e:
  10148. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  10149. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  10150. def start_spoolbuddy_watchdog():
  10151. global _spoolbuddy_watchdog_task
  10152. if _spoolbuddy_watchdog_task is None:
  10153. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  10154. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  10155. def stop_spoolbuddy_watchdog():
  10156. global _spoolbuddy_watchdog_task
  10157. if _spoolbuddy_watchdog_task:
  10158. _spoolbuddy_watchdog_task.cancel()
  10159. _spoolbuddy_watchdog_task = None
  10160. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  10161. # Dead-MQTT-session recovery
  10162. #
  10163. # check_staleness() covers the "connected but silent" half-broken session. It
  10164. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  10165. # is the only thing left watching at that point. When paho stops making
  10166. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  10167. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  10168. # offline with the UI open the whole time, recovered only when something
  10169. # happened to nudge it.
  10170. #
  10171. # This loop is that backstop. It only touches printers that had a working
  10172. # session and lost it, and only when the MQTT port still answers — a printer
  10173. # that is simply switched off is left to paho, since rebuilding a client
  10174. # against an unreachable host achieves nothing and would fill the log every
  10175. # night.
  10176. _connection_watchdog_task: asyncio.Task | None = None
  10177. CONNECTION_WATCHDOG_INTERVAL = 60
  10178. # How long a printer must have been silent before we stop trusting paho.
  10179. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  10180. # so a session that is recovering on its own is never interrupted.
  10181. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  10182. # Per-printer floor between rebuild attempts.
  10183. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  10184. _connection_watchdog_last_attempt: dict[int, float] = {}
  10185. async def _recover_dead_printer_sessions() -> int:
  10186. """Rebuild MQTT clients that have been offline too long to still be trying.
  10187. Returns the number of printers a rebuild was attempted for (for tests and
  10188. for the caller's logging). Never raises: one unreachable printer must not
  10189. stop the sweep for the rest of the farm.
  10190. """
  10191. logger = logging.getLogger(__name__)
  10192. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  10193. now = time.monotonic()
  10194. recovered = 0
  10195. for printer_id, client in list(printer_manager._clients.items()):
  10196. try:
  10197. if client.state.connected:
  10198. _connection_watchdog_last_attempt.pop(printer_id, None)
  10199. continue
  10200. # Time since the last inbound message is the age of the last known
  10201. # good session — no extra bookkeeping needed, and it is the same
  10202. # clock is_stale() reads. 0 means this client has never had one:
  10203. # that is the initial-connect path, where paho retrying is the
  10204. # correct and only behaviour, so leave it be.
  10205. last_msg = client._last_message_time
  10206. if not last_msg:
  10207. continue
  10208. offline_for = time.time() - last_msg
  10209. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  10210. continue
  10211. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  10212. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  10213. continue
  10214. if not await check_port(client.ip_address, PORT_MQTT):
  10215. # Switched off, unplugged, or off the network. Paho's retry is
  10216. # the right handler; say so at debug level and move on.
  10217. logger.debug(
  10218. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  10219. "— leaving the reconnect to paho",
  10220. printer_id,
  10221. offline_for,
  10222. )
  10223. _connection_watchdog_last_attempt[printer_id] = now
  10224. continue
  10225. _connection_watchdog_last_attempt[printer_id] = now
  10226. recovered += 1
  10227. logger.warning(
  10228. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  10229. "rebuilding the client with a fresh session (last connect error: %s)",
  10230. printer_id,
  10231. offline_for,
  10232. PORT_MQTT,
  10233. client.last_connect_error or "none recorded",
  10234. )
  10235. # Async context, so this takes the hard-reset path: fresh client_id,
  10236. # paho's QoS 1 queue dropped. That matters — a project_file left
  10237. # unacked on the dead session would otherwise replay into the new
  10238. # one and trip 0500_4003 on the printer (#1136).
  10239. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  10240. except Exception as e:
  10241. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  10242. return recovered
  10243. async def _connection_watchdog_loop():
  10244. logger = logging.getLogger(__name__)
  10245. # Let the initial connects settle before judging anyone offline.
  10246. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  10247. while True:
  10248. try:
  10249. await _recover_dead_printer_sessions()
  10250. except asyncio.CancelledError:
  10251. break
  10252. except Exception as e:
  10253. logger.warning("Connection watchdog sweep failed: %s", e)
  10254. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  10255. def start_connection_watchdog():
  10256. global _connection_watchdog_task
  10257. if _connection_watchdog_task is None:
  10258. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  10259. logging.getLogger(__name__).info("Printer connection watchdog started")
  10260. def stop_connection_watchdog():
  10261. global _connection_watchdog_task
  10262. if _connection_watchdog_task:
  10263. _connection_watchdog_task.cancel()
  10264. _connection_watchdog_task = None
  10265. _connection_watchdog_last_attempt.clear()
  10266. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  10267. # Camera stream orphan cleanup
  10268. _camera_cleanup_task: asyncio.Task | None = None
  10269. CAMERA_CLEANUP_INTERVAL = 60
  10270. # Every this many camera cleanups (about an hour), the timelapse janitor too:
  10271. # kept frames of a failed stitch go after a day, not at the next restart.
  10272. TIMELAPSE_CLEANUP_EVERY = 60
  10273. async def _camera_cleanup_loop():
  10274. """Periodically clean up orphaned ffmpeg processes and timelapse leftovers."""
  10275. from backend.app.api.routes.camera import cleanup_orphaned_streams
  10276. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10277. rounds = 0
  10278. while True:
  10279. try:
  10280. rounds += 1
  10281. await cleanup_orphaned_streams()
  10282. except asyncio.CancelledError:
  10283. break
  10284. except Exception as e:
  10285. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  10286. try:
  10287. if rounds % TIMELAPSE_CLEANUP_EVERY == 0:
  10288. await asyncio.to_thread(cleanup_orphaned_timelapse_sessions)
  10289. except asyncio.CancelledError:
  10290. break
  10291. except Exception as e:
  10292. logging.getLogger(__name__).warning("Timelapse frames cleanup failed: %s", e)
  10293. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  10294. def start_camera_cleanup():
  10295. global _camera_cleanup_task
  10296. if _camera_cleanup_task is None:
  10297. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  10298. logging.getLogger(__name__).info("Camera stream cleanup started")
  10299. def stop_camera_cleanup():
  10300. global _camera_cleanup_task
  10301. if _camera_cleanup_task:
  10302. _camera_cleanup_task.cancel()
  10303. _camera_cleanup_task = None
  10304. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  10305. # ---------------------------------------------------------------------------
  10306. # Expected-print TTL eviction
  10307. # ---------------------------------------------------------------------------
  10308. def _evict_stale_expected_prints() -> None:
  10309. """Remove entries from _expected_prints / _expected_print_creators that are
  10310. older than _EXPECTED_PRINT_TTL_SECONDS.
  10311. This prevents unbounded growth when a print is registered (via
  10312. register_expected_print) but on_print_start never fires — e.g. because the
  10313. printer disconnects, the app restarts, or the print is started directly from
  10314. the printer panel without going through the queue.
  10315. """
  10316. # Use monotonic time so the TTL is unaffected by system clock adjustments
  10317. # (e.g. NTP sync, DST changes).
  10318. # A print that ended without its archive being found at completion leaves
  10319. # its id here; only running prints are owned.
  10320. _owned_print_archive_ids.intersection_update(_active_prints.values())
  10321. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  10322. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  10323. if not stale_keys:
  10324. return
  10325. evicted: set[tuple[int, int]] = set()
  10326. for key in stale_keys:
  10327. archive_id = _expected_prints.pop(key, None)
  10328. if archive_id is not None:
  10329. evicted.add((key[0], archive_id))
  10330. _expected_print_creators.pop(key, None)
  10331. _expected_print_registered_at.pop(key, None)
  10332. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  10333. # that have no remaining live keys in _expected_prints (all variants
  10334. # were just evicted) and are not printing right now. Print start pops
  10335. # only the names the printer reported, so the "<base>.gcode" variant
  10336. # outlives it; without the printing check its eviction two hours after
  10337. # dispatch threw away a running print's plate, AMS mapping and cost
  10338. # centre, which completion still reads (#3275).
  10339. for printer_id, archive_id in evicted:
  10340. if not _expected_or_printing_here(printer_id, archive_id):
  10341. _drop_dispatch(printer_id, archive_id)
  10342. logging.getLogger(__name__).info(
  10343. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  10344. )
  10345. async def _expected_prints_cleanup_loop() -> None:
  10346. """Background task: periodically evict stale expected-print entries."""
  10347. while True:
  10348. try:
  10349. _evict_stale_expected_prints()
  10350. except asyncio.CancelledError:
  10351. raise
  10352. except Exception as e:
  10353. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  10354. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  10355. def start_expected_prints_cleanup() -> None:
  10356. global _expected_prints_cleanup_task
  10357. if _expected_prints_cleanup_task is None:
  10358. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  10359. logging.getLogger(__name__).info("Expected prints cleanup started")
  10360. def stop_expected_prints_cleanup() -> None:
  10361. global _expected_prints_cleanup_task
  10362. if _expected_prints_cleanup_task:
  10363. _expected_prints_cleanup_task.cancel()
  10364. _expected_prints_cleanup_task = None
  10365. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  10366. # ---------------------------------------------------------------------------
  10367. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  10368. # ---------------------------------------------------------------------------
  10369. _auth_cleanup_task: asyncio.Task | None = None
  10370. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  10371. async def _run_auth_cleanup() -> None:
  10372. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  10373. from backend.app.core.database import async_session
  10374. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  10375. from backend.app.models.user_totp import UserTOTP
  10376. now = datetime.now(timezone.utc)
  10377. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  10378. try:
  10379. async with async_session() as db:
  10380. stale_cutoff = now - timedelta(hours=1)
  10381. result = await db.execute(
  10382. select(UserTOTP).where(
  10383. UserTOTP.is_enabled.is_(False),
  10384. UserTOTP.created_at < stale_cutoff,
  10385. )
  10386. )
  10387. stale_records = result.scalars().all()
  10388. if stale_records:
  10389. for rec in stale_records:
  10390. await db.delete(rec)
  10391. await db.commit()
  10392. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  10393. except Exception as e:
  10394. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  10395. # Remove expired revoked-JTI entries (they are no longer needed once the
  10396. # original token's exp has passed — the token would be rejected by JWT
  10397. # signature verification regardless).
  10398. try:
  10399. async with async_session() as db:
  10400. await db.execute(
  10401. delete(AuthEphemeralToken).where(
  10402. AuthEphemeralToken.token_type == "revoked_jti",
  10403. AuthEphemeralToken.expires_at < now,
  10404. )
  10405. )
  10406. await db.commit()
  10407. except Exception as e:
  10408. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  10409. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  10410. # Events outside this window can never affect rate-limit decisions — they only
  10411. # consume DB space. Use the same window constant as the rate limiter so the
  10412. # two are always in sync.
  10413. try:
  10414. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  10415. async with async_session() as db:
  10416. await db.execute(
  10417. delete(AuthRateLimitEvent).where(
  10418. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  10419. )
  10420. )
  10421. await db.commit()
  10422. except Exception as e:
  10423. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  10424. async def _auth_cleanup_loop() -> None:
  10425. """Periodic background task: run auth cleanup every hour."""
  10426. while True:
  10427. try:
  10428. await _run_auth_cleanup()
  10429. except asyncio.CancelledError:
  10430. break
  10431. except Exception as e:
  10432. logging.warning("Auth cleanup loop error: %s", e)
  10433. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  10434. def start_auth_cleanup() -> None:
  10435. global _auth_cleanup_task
  10436. if _auth_cleanup_task is None:
  10437. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  10438. logging.getLogger(__name__).info("Auth periodic cleanup started")
  10439. def stop_auth_cleanup() -> None:
  10440. global _auth_cleanup_task
  10441. if _auth_cleanup_task:
  10442. _auth_cleanup_task.cancel()
  10443. _auth_cleanup_task = None
  10444. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  10445. @asynccontextmanager
  10446. async def lifespan(app: FastAPI):
  10447. # Startup
  10448. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  10449. # anything else can spawn tasks that might trip it.
  10450. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  10451. install_proactor_reset_filter()
  10452. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  10453. # what turned descriptor exhaustion into a corrupted database (#2883).
  10454. from backend.app.core.fd_limit import raise_open_file_limit
  10455. raise_open_file_limit()
  10456. # Before init_db, so the warning is near the top of the log rather than
  10457. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  10458. warn_if_running_on_uvloop()
  10459. await init_db()
  10460. # Browser download tokens expire after five minutes. Remove abandoned
  10461. # prepared ZIPs at startup as well as before each new preparation so a
  10462. # quiet appliance cannot retain an unusable bundle indefinitely.
  10463. try:
  10464. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  10465. await prune_stale_printer_file_bundles()
  10466. except Exception as exc:
  10467. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  10468. # After migrations, so the is_env_managed column exists. Never raises --
  10469. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  10470. # startup (see apply_env_oidc_provider).
  10471. from backend.app.core.oidc_env import apply_env_oidc_provider
  10472. async with async_session() as oidc_db:
  10473. await apply_env_oidc_provider(oidc_db)
  10474. # Close out batches that finished before `completed` was a reachable status
  10475. # (#342). Without this the Batches tab opens on every batch created since
  10476. # the feature shipped, all still marked active. Never blocks startup.
  10477. try:
  10478. from backend.app.services.print_batch import backfill_batch_statuses
  10479. async with async_session() as batch_db:
  10480. await backfill_batch_statuses(batch_db)
  10481. except Exception as exc:
  10482. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  10483. # Each plate's estimate of archives made before they were kept (#3375),
  10484. # read from their 3MFs in the background: the readers use the whole
  10485. # file's figures until then.
  10486. global _plate_estimates_task
  10487. _plate_estimates_task = asyncio.create_task(_fill_plate_estimates())
  10488. # Register an app-scoped httpx client for Bambu Cloud services so
  10489. # per-request BambuCloudService instances reuse the same connection pool
  10490. # (important for routes like /cloud/filament-info that chain many
  10491. # get_setting_detail calls). The shared client stores no region/token
  10492. # state, so the per-request ownership pattern that fixed the region-bleed
  10493. # bug is preserved.
  10494. import httpx as _httpx
  10495. from backend.app.services.bambu_cloud import set_shared_http_client
  10496. from backend.app.services.model_providers.makerworld.service import (
  10497. set_shared_http_client as set_shared_makerworld_http_client,
  10498. )
  10499. from backend.app.services.orca_cloud import (
  10500. set_shared_http_client as set_shared_orca_http_client,
  10501. )
  10502. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  10503. set_shared_http_client(_shared_cloud_http_client)
  10504. # Reuse the same connection pool for MakerWorld — different host, same
  10505. # keep-alive pool saves a TLS handshake per request.
  10506. set_shared_makerworld_http_client(_shared_cloud_http_client)
  10507. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  10508. # each spun up (and never closed) its own client, leaking sockets.
  10509. set_shared_orca_http_client(_shared_cloud_http_client)
  10510. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  10511. # This can happen when a print was cancelled mid-print on versions before this fix.
  10512. try:
  10513. async with async_session() as db:
  10514. from backend.app.models.print_queue import PrintQueueItem
  10515. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  10516. aborted_items = result.scalars().all()
  10517. if aborted_items:
  10518. for item in aborted_items:
  10519. item.status = "cancelled"
  10520. await db.commit()
  10521. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  10522. except Exception as e:
  10523. logging.warning("Failed to fix aborted queue items: %s", e)
  10524. # Restore debug logging state from previous session
  10525. await init_debug_logging()
  10526. # Set up printer manager callbacks
  10527. loop = asyncio.get_event_loop()
  10528. printer_manager.set_event_loop(loop)
  10529. printer_manager.set_status_change_callback(on_printer_status_change)
  10530. printer_manager.set_print_start_callback(on_print_start)
  10531. printer_manager.set_print_complete_callback(on_print_complete)
  10532. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  10533. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  10534. printer_manager.set_ams_change_callback(on_ams_change)
  10535. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  10536. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  10537. await printer_manager.load_awaiting_plate_clear_from_db()
  10538. # Layer change callback for external camera timelapse
  10539. async def on_layer_change(printer_id: int, layer_num: int):
  10540. """Capture timelapse frame on layer change + first layer notification."""
  10541. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  10542. await tl_layer_change(printer_id, layer_num)
  10543. # #1867: bank a recent in-print frame so the finish-photo path has a
  10544. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  10545. # #2547 added `on_print_progress` as a second driver — this one alone
  10546. # stops firing once the final layer begins.
  10547. await _maybe_bank_inprint_frame(printer_id, layer_num)
  10548. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  10549. # Gate on actual printing state — Bambu firmware ticks layer_num during
  10550. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  10551. # nozzle clean), so a bare layer_num check can fire minutes before the
  10552. # first real extrusion. We require gcode_state == RUNNING and
  10553. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  10554. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  10555. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  10556. # edge fires later; _first_layer_notified stays clear until we actually send
  10557. # so a deferred re-evaluation can win. See issue #1837.
  10558. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  10559. client = printer_manager.get_client(printer_id)
  10560. state = client.state if client else None
  10561. if not state or state.state != "RUNNING":
  10562. return
  10563. if state.mc_print_sub_stage not in (None, 0):
  10564. return
  10565. _first_layer_notified[printer_id] = True
  10566. try:
  10567. async with async_session() as db:
  10568. from backend.app.models.printer import Printer
  10569. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  10570. printer = result.scalar_one_or_none()
  10571. if not printer:
  10572. return
  10573. printer_name = printer.name
  10574. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  10575. total_layers = state.total_layers if state else 0
  10576. image_data = await _capture_snapshot_for_notification(
  10577. printer_id, printer, logging.getLogger(__name__)
  10578. )
  10579. await notification_service.on_first_layer_complete(
  10580. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  10581. )
  10582. except Exception as e:
  10583. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  10584. printer_manager.set_layer_change_callback(on_layer_change)
  10585. async def on_print_progress(printer_id: int, percent: int):
  10586. """#2547: keep the in-print frame bank fresh through the final layer.
  10587. `on_layer_change` stops the moment the last layer starts, which on the
  10588. H2C capture that closed #2547 left the bank stale for the three minutes
  10589. that layer took. Progress is the only field that keeps advancing there,
  10590. and it freezes before the End G-code runs — so banking on it stays
  10591. inside the print and never sees a swapped plate.
  10592. """
  10593. client = printer_manager.get_client(printer_id)
  10594. state = client.state if client else None
  10595. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  10596. printer_manager.set_print_progress_callback(on_print_progress)
  10597. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  10598. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  10599. waiter = _bed_cool_waiters.get(printer_id)
  10600. if not waiter:
  10601. return
  10602. threshold = waiter["threshold"]
  10603. if bed_temp > threshold:
  10604. return
  10605. # Bed is at or below threshold — fire notification and remove waiter
  10606. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  10607. if not waiter_info:
  10608. return # Another callback already handled it
  10609. bed_cool_logger = logging.getLogger(__name__)
  10610. bed_cool_logger.info(
  10611. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  10612. bed_temp,
  10613. printer_id,
  10614. threshold,
  10615. )
  10616. try:
  10617. printer_info = printer_manager.get_printer(printer_id)
  10618. p_name = printer_info.name if printer_info else "Unknown"
  10619. async with async_session() as db:
  10620. await notification_service.on_bed_cooled(
  10621. printer_id=printer_id,
  10622. printer_name=p_name,
  10623. bed_temp=bed_temp,
  10624. threshold=threshold,
  10625. filename=waiter_info["filename"],
  10626. db=db,
  10627. )
  10628. except Exception as e:
  10629. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  10630. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  10631. async def on_drying_complete(printer_id: int, ams_id: int):
  10632. """Smart-plug auto-off-after-drying trigger (#1349).
  10633. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  10634. manager walks all plugs linked to this printer and turns off only
  10635. the ones with ``auto_off_after_drying`` enabled, after their
  10636. per-plug delay. Multiple AMS units finishing close together (e.g. a
  10637. dual-AMS dry that ends within the same MQTT push) call this once
  10638. per unit — the manager's ``_cancel_pending_off`` collapses
  10639. repeated scheduling on the same plug to one timer, so duplicate
  10640. fires are safe.
  10641. """
  10642. try:
  10643. async with async_session() as db:
  10644. await smart_plug_manager.on_drying_complete(printer_id, db)
  10645. except Exception as e:
  10646. logging.getLogger(__name__).warning(
  10647. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  10648. printer_id,
  10649. ams_id,
  10650. e,
  10651. )
  10652. printer_manager.set_drying_complete_callback(on_drying_complete)
  10653. async def on_drying_cycle_end(printer_id: int, cycle):
  10654. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  10655. from backend.app.services.spool_drying import record_drying_cycle
  10656. try:
  10657. async with async_session() as db:
  10658. await record_drying_cycle(db, printer_id, cycle)
  10659. except Exception as e:
  10660. logging.getLogger(__name__).warning(
  10661. "Failed to record drying for printer %d (AMS %d): %s",
  10662. printer_id,
  10663. cycle.ams_id,
  10664. e,
  10665. )
  10666. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  10667. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  10668. """Surface the read-back result of a spool assignment to the UI (#2582).
  10669. The MQTT client confirms (or fails to confirm) that the tray telemetry
  10670. echoed back the filament id we pushed. We relay that as a websocket
  10671. event so the frontend can toast "loaded" / "assignment didn't take"
  10672. instead of the historic silent fire-and-forget, which made the
  10673. AMS→Studio hand-off feel random to users.
  10674. """
  10675. try:
  10676. from backend.app.services.spool_assignment_notifications import (
  10677. _slot_label_from_global_tray,
  10678. )
  10679. if ams_id == 255:
  10680. global_id = 254 + tray_id
  10681. elif ams_id >= 128:
  10682. global_id = ams_id
  10683. else:
  10684. global_id = ams_id * 4 + tray_id
  10685. slot_label = _slot_label_from_global_tray(global_id)
  10686. printer_info = printer_manager.get_printer(printer_id)
  10687. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  10688. await ws_manager.broadcast(
  10689. {
  10690. "type": "spool_assignment_verified",
  10691. "printer_id": printer_id,
  10692. "printer_name": printer_name,
  10693. "ams_id": ams_id,
  10694. "tray_id": tray_id,
  10695. "slot": slot_label,
  10696. "verified": verified,
  10697. # Present on success: False means the filament setting landed
  10698. # but the K-profile (cali_idx) did not — the reporter's exact
  10699. # "loaded but no flow profile" symptom.
  10700. "kprofile_applied": detail.get("kprofile_applied", True),
  10701. }
  10702. )
  10703. except Exception as e:
  10704. logging.getLogger(__name__).warning(
  10705. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  10706. printer_id,
  10707. ams_id,
  10708. tray_id,
  10709. e,
  10710. )
  10711. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  10712. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  10713. """Persist a mid-print tray change for completion-time attribution.
  10714. AMS filament backup switches trays without telling the slicer, so the
  10715. tray-change log is the only record of which spool fed which layers.
  10716. Keeping it only in memory meant a restart mid-print charged everything
  10717. to the tray that finished the job.
  10718. """
  10719. try:
  10720. from backend.app.services.usage_tracker import record_tray_change
  10721. async with async_session() as db:
  10722. await record_tray_change(db, printer_id, tray_global, layer_num)
  10723. except Exception as e:
  10724. logging.getLogger(__name__).warning(
  10725. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  10726. printer_id,
  10727. tray_global,
  10728. layer_num,
  10729. e,
  10730. )
  10731. printer_manager.set_tray_change_callback(on_tray_change)
  10732. # Initialize MQTT relay from settings
  10733. async with async_session() as db:
  10734. from backend.app.api.routes.settings import get_setting
  10735. mqtt_settings = {
  10736. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  10737. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  10738. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  10739. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  10740. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  10741. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  10742. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  10743. }
  10744. await mqtt_relay.configure(mqtt_settings)
  10745. # Restore MQTT smart plug subscriptions
  10746. if mqtt_settings.get("mqtt_enabled"):
  10747. from backend.app.models.smart_plug import SmartPlug
  10748. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  10749. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  10750. mqtt_plugs = result.scalars().all()
  10751. restored = 0
  10752. for plug in mqtt_plugs:
  10753. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  10754. restored += 1
  10755. if restored:
  10756. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  10757. # Connect to all active printers
  10758. async with async_session() as db:
  10759. await init_printer_connections(db)
  10760. # Auto-connect to Spoolman if enabled
  10761. async with async_session() as db:
  10762. from backend.app.api.routes.settings import get_setting
  10763. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  10764. spoolman_url = await get_setting(db, "spoolman_url")
  10765. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  10766. try:
  10767. client = await init_spoolman_client(spoolman_url)
  10768. if await client.health_check():
  10769. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  10770. # Ensure the 'tag' extra field exists for RFID/UUID storage
  10771. field_ok = await client.ensure_tag_extra_field()
  10772. if not field_ok:
  10773. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  10774. # Register the BambuStudio slicer-preset fields used by the
  10775. # spool-edit / assign flow. Spoolman rejects PATCHes with
  10776. # unknown extra keys, so these must exist before any update
  10777. # that touches them.
  10778. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  10779. if not await client.ensure_extra_field(field_name):
  10780. logging.warning(
  10781. "Spoolman extra field %r registration failed — "
  10782. "spool slicer-preset edits will return 502",
  10783. field_name,
  10784. )
  10785. else:
  10786. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  10787. except Exception as e:
  10788. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  10789. # Start the print scheduler
  10790. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  10791. # Start the smart plug scheduler for time-based on/off
  10792. smart_plug_manager.start_scheduler()
  10793. # Start the Home Assistant sensor poller (#1148)
  10794. ha_sensor_manager.start()
  10795. location_ha_sensor_manager.start()
  10796. # Resume any pending auto-offs that were interrupted by restart
  10797. await smart_plug_manager.resume_pending_auto_offs()
  10798. # Start the notification digest scheduler
  10799. notification_service.start_digest_scheduler()
  10800. notify_live_activities.start()
  10801. notify_widgets.start()
  10802. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  10803. # provider in reactions/both mode; the notification routes resync them.
  10804. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  10805. # until the next provider save, not the whole startup.
  10806. try:
  10807. await telegram_reaction_poller.start()
  10808. except Exception as e:
  10809. logging.warning("Telegram reaction poller did not start: %s", e)
  10810. # Start the GitHub backup scheduler
  10811. await github_backup_service.start_scheduler()
  10812. # Start the local backup scheduler
  10813. await local_backup_service.start_scheduler()
  10814. await obico_detection_service.start()
  10815. # Start the library trash sweeper (#1008)
  10816. await library_trash_service.start_scheduler()
  10817. # Start the archive auto-purge sweeper (#1008 follow-up)
  10818. await archive_purge_service.start_scheduler()
  10819. # Start AMS history recording
  10820. start_ams_history_recording()
  10821. # Start printer sensor (nozzle / bed / chamber) history recording
  10822. start_printer_sensor_history_recording()
  10823. # Start printer runtime tracking
  10824. start_runtime_tracking()
  10825. # Start SpoolBuddy device watchdog
  10826. start_spoolbuddy_watchdog()
  10827. # Start camera stream orphan cleanup
  10828. start_camera_cleanup()
  10829. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  10830. start_connection_watchdog()
  10831. # One-shot sweep for timelapse session directories orphaned by a crash
  10832. # or restart that happened mid-print (in-memory session tracking can't
  10833. # survive that, and nothing else reaps the leftover frames/output file)
  10834. try:
  10835. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10836. removed = cleanup_orphaned_timelapse_sessions()
  10837. if removed:
  10838. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  10839. except Exception as e:
  10840. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  10841. # Start expected-print TTL eviction (prevents memory leak when prints are
  10842. # registered but on_print_start never fires)
  10843. start_expected_prints_cleanup()
  10844. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  10845. start_auth_cleanup()
  10846. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  10847. from backend.app.services import announcements as announcements_service
  10848. announcements_service.start()
  10849. from backend.app.services.printer_media import start_printer_download_cleanup
  10850. start_printer_download_cleanup()
  10851. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  10852. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  10853. from backend.app.services.loop_watchdog import start_loop_watchdog
  10854. start_loop_watchdog()
  10855. # Initialize virtual printer manager and sync from DB
  10856. from backend.app.services.virtual_printer import virtual_printer_manager
  10857. virtual_printer_manager.set_session_factory(async_session)
  10858. virtual_printer_manager.set_printer_manager(printer_manager)
  10859. try:
  10860. await virtual_printer_manager.sync_from_db()
  10861. logging.info("Virtual printer manager synced from database")
  10862. except Exception as e:
  10863. logging.warning("Failed to sync virtual printers: %s", e)
  10864. yield
  10865. # Shutdown
  10866. print_scheduler.stop()
  10867. smart_plug_manager.stop_scheduler()
  10868. ha_sensor_manager.stop()
  10869. location_ha_sensor_manager.stop()
  10870. notification_service.stop_digest_scheduler()
  10871. await notify_live_activities.close()
  10872. await notify_widgets.close()
  10873. await telegram_reaction_poller.aclose()
  10874. github_backup_service.stop_scheduler()
  10875. local_backup_service.stop_scheduler()
  10876. library_trash_service.stop_scheduler()
  10877. archive_purge_service.stop_scheduler()
  10878. obico_detection_service.stop()
  10879. stop_ams_history_recording()
  10880. stop_printer_sensor_history_recording()
  10881. stop_runtime_tracking()
  10882. stop_spoolbuddy_watchdog()
  10883. stop_camera_cleanup()
  10884. stop_connection_watchdog()
  10885. from backend.app.services.loop_watchdog import stop_loop_watchdog
  10886. stop_loop_watchdog()
  10887. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  10888. # cleanly rather than waiting on a queue that nothing will ever fill.
  10889. try:
  10890. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  10891. await shutdown_all_broadcasters()
  10892. except Exception as e:
  10893. logging.warning("Failed to shut down camera broadcasters: %s", e)
  10894. stop_expected_prints_cleanup()
  10895. stop_auth_cleanup()
  10896. if _plate_estimates_task is not None and not _plate_estimates_task.done():
  10897. _plate_estimates_task.cancel()
  10898. from backend.app.services import announcements as announcements_service
  10899. announcements_service.stop()
  10900. from backend.app.services.printer_media import stop_printer_download_cleanup
  10901. await stop_printer_download_cleanup()
  10902. # Stops a timelapse editor's ffmpeg rather than leaving it to the OS.
  10903. from backend.app.services import timelapse_jobs
  10904. await timelapse_jobs.cancel_all()
  10905. printer_manager.disconnect_all()
  10906. slot_unlink_grace.reset()
  10907. await close_spoolman_client()
  10908. # Stop all virtual printer services
  10909. await virtual_printer_manager.stop_all()
  10910. await mqtt_smart_plug_service.disconnect(timeout=2)
  10911. await mqtt_relay.disconnect(timeout=2)
  10912. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  10913. set_shared_http_client(None)
  10914. set_shared_makerworld_http_client(None)
  10915. set_shared_orca_http_client(None)
  10916. await _shared_cloud_http_client.aclose()
  10917. # Checkpoint WAL (SQLite only) and close all database connections
  10918. from backend.app.core.db_dialect import is_sqlite
  10919. if is_sqlite():
  10920. try:
  10921. async with engine.begin() as conn:
  10922. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  10923. logging.info("WAL checkpoint completed")
  10924. except Exception as e:
  10925. logging.warning("WAL checkpoint failed: %s", e)
  10926. await engine.dispose()
  10927. app = FastAPI(
  10928. title=app_settings.app_name,
  10929. description="Archive and manage Bambu Lab 3MF files",
  10930. version=APP_VERSION,
  10931. lifespan=lifespan,
  10932. )
  10933. # Added first so it sits innermost, next to the routes: a refused header's value
  10934. # (often a stored token) masked in every JSON body. See core.response_redaction.
  10935. app.add_middleware(RefusedHeaderResponseMask)
  10936. def _json_safe(value):
  10937. """The validation errors with every non-finite number written as text."""
  10938. if isinstance(value, float) and not math.isfinite(value):
  10939. return str(value)
  10940. if isinstance(value, dict):
  10941. return {key: _json_safe(item) for key, item in value.items()}
  10942. if isinstance(value, list | tuple):
  10943. return [_json_safe(item) for item in value]
  10944. return value
  10945. @app.exception_handler(RequestValidationError)
  10946. async def _validation_error(_request, exc: RequestValidationError) -> JSONResponse:
  10947. """FastAPI's own 422, except that it survives a non-finite number.
  10948. A body may carry ``Infinity`` or ``NaN`` (Python's JSON reader accepts
  10949. them), and the default handler echoes the input back in its errors,
  10950. which JSON cannot hold: the request ended in an error instead of a 422.
  10951. """
  10952. return JSONResponse(status_code=422, content={"detail": _json_safe(jsonable_encoder(exc.errors()))})
  10953. # =============================================================================
  10954. # Authentication Middleware - Secures ALL API routes by default
  10955. # =============================================================================
  10956. # Public routes that don't require authentication even when auth is enabled
  10957. PUBLIC_API_ROUTES = {
  10958. # Auth routes needed before/during login
  10959. "/api/v1/auth/status",
  10960. "/api/v1/auth/login",
  10961. "/api/v1/auth/setup", # Needed for initial setup and recovery
  10962. # Advanced auth status needed for login page
  10963. "/api/v1/auth/advanced-auth/status",
  10964. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  10965. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  10966. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  10967. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  10968. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  10969. # OIDC routes that must be reachable without a JWT
  10970. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  10971. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  10972. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  10973. # Connected apps: the app's server swaps a code for the user's identity,
  10974. # authenticated by its client secret rather than a login token.
  10975. "/api/v1/connect/token",
  10976. # Version check for updates (no sensitive data)
  10977. "/api/v1/updates/version",
  10978. # Metrics endpoint handles its own prometheus_token authentication
  10979. "/api/v1/metrics",
  10980. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  10981. # this BEFORE a JWT is available to pick up the firstboot wizard's
  10982. # hostname / timezone / locale and the chrony NTP-gate state. The
  10983. # response contains user-set defaults and a public sync flag — no
  10984. # secrets. Without this entry the global auth middleware returns 401
  10985. # before the route handler runs, regardless of the route's own
  10986. # "no auth required" intent.
  10987. "/api/v1/system/appliance",
  10988. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  10989. # authenticates with a long-lived ``camwall``-scoped token in the query
  10990. # string — exactly like the camera streams two lists below, and for the same
  10991. # reason (no header to put a JWT in). "Public" here only means the middleware
  10992. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  10993. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  10994. # plain ``camera_stream`` token does NOT open this door.
  10995. "/api/v1/camwall/printers",
  10996. # Overlay branding: the route enforces overlay-scoped token authentication.
  10997. "/api/v1/overlay-branding/logo",
  10998. }
  10999. # Route prefixes that are public (for routes with dynamic segments)
  11000. PUBLIC_API_PREFIXES = [
  11001. # WebSocket connections handle their own auth
  11002. "/api/v1/ws",
  11003. # OIDC authorize redirects — include provider_id in path
  11004. "/api/v1/auth/oidc/authorize/",
  11005. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  11006. # a phone with no session, so no header can carry a JWT — the single-use
  11007. # capability token in the path IS the credential (same reasoning as the
  11008. # /dl/ slicer downloads below). The route grants nothing beyond writing
  11009. # good/reject on the one archive the token was minted for.
  11010. "/api/v1/archives/confirm/",
  11011. ]
  11012. # Route patterns that are public (read-only display data)
  11013. # These are checked with "in path" - needed because browsers load images/videos
  11014. # via <img src> and <video src> which don't include Authorization headers
  11015. PUBLIC_API_PATTERNS = [
  11016. # Thumbnails
  11017. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  11018. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  11019. # Images and media
  11020. "/photos/", # /archives/{id}/photos/{filename}
  11021. "/project-image/", # /archives/{id}/project-image/{path}
  11022. "/qrcode", # /archives/{id}/qrcode
  11023. "/timelapse", # /archives/{id}/timelapse (video)
  11024. "/cover", # /printers/{id}/cover
  11025. "/icon", # /external-links/{id}/icon
  11026. # Camera (streams loaded via <img> tag)
  11027. "/camera/stream", # /printers/{id}/camera/stream
  11028. "/camera/snapshot", # /printers/{id}/camera/snapshot
  11029. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  11030. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  11031. # string (same reasoning as the camera streams above — no header to carry a
  11032. # JWT). "Public" only means the middleware steps aside; the route still runs
  11033. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  11034. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  11035. "/overlay-status", # /printers/{id}/overlay-status
  11036. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  11037. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  11038. # download token in the URL path instead.
  11039. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  11040. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  11041. # and these patterns match by substring. Without its own entry the middleware
  11042. # 401s the slicer's header-less request before the route's token check runs,
  11043. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  11044. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  11045. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  11046. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  11047. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  11048. ]
  11049. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  11050. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  11051. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  11052. Format: comma-separated list of ``scheme://host[:port]`` origins.
  11053. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  11054. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  11055. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  11056. Invalid entries are dropped with a warning rather than failing startup, so
  11057. a typo in one origin doesn't take the whole deployment down.
  11058. """
  11059. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  11060. if not raw:
  11061. return ()
  11062. valid: list[str] = []
  11063. for item in raw.split(","):
  11064. candidate = item.strip()
  11065. if not candidate:
  11066. continue
  11067. try:
  11068. parsed = urlparse(candidate)
  11069. except ValueError as e:
  11070. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  11071. continue
  11072. if parsed.scheme not in ("http", "https"):
  11073. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  11074. continue
  11075. if not parsed.netloc:
  11076. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  11077. continue
  11078. if parsed.path and parsed.path != "/":
  11079. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  11080. continue
  11081. if parsed.query or parsed.fragment:
  11082. _security_headers_logger.warning(
  11083. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  11084. )
  11085. continue
  11086. if "*" in parsed.netloc:
  11087. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  11088. continue
  11089. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  11090. if valid:
  11091. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  11092. return tuple(valid)
  11093. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  11094. def _frame_ancestors(default_value: str) -> str:
  11095. """Compose the ``frame-ancestors`` CSP directive (#1191).
  11096. ``default_value`` is the strict directive used when the operator has not
  11097. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  11098. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  11099. Settings URL builder's preview). When trusted origins
  11100. are configured, ``'self'`` is always included so same-origin embedding never
  11101. breaks even if an operator forgets to add their own origin to the list.
  11102. """
  11103. if _TRUSTED_FRAME_ORIGINS:
  11104. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  11105. return f"frame-ancestors {default_value};"
  11106. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  11107. # patterns are anchored on the exact emitted name so the relaxed policies
  11108. # below can never apply to any other asset.
  11109. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  11110. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  11111. # -> /assets/pdf.worker.min-<hash>.js
  11112. # Vite also emits a one-line chunk under the second name that only exports the
  11113. # worker's URL. The page imports it as a module, and a module script is run
  11114. # under the importing document's policy, never its own response's, so it
  11115. # matching as well changes nothing.
  11116. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  11117. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  11118. @app.middleware("http")
  11119. async def security_headers_middleware(request, call_next):
  11120. """Add standard HTTP security headers to every response."""
  11121. # Per-request nonce stamped into `script-src` (#1460). On its own this
  11122. # changes nothing for Bambuddy's own pages — index.html has no inline
  11123. # scripts since the SW registration moved to /sw-register.js. The reason
  11124. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  11125. # script injected into the HTML on the edge, with a fresh hash on every
  11126. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  11127. # it clones the same nonce onto its injected <script>, and the inline
  11128. # script passes the policy without us needing 'unsafe-inline'. See
  11129. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  11130. csp_nonce = secrets.token_urlsafe(16)
  11131. # Routes that render their own HTML need it too, or their inline script is
  11132. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  11133. # one that does: it submits its own form so a verdict still costs one tap.
  11134. request.state.csp_nonce = csp_nonce
  11135. response = await call_next(request)
  11136. response.headers["X-Content-Type-Options"] = "nosniff"
  11137. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  11138. # browsers honour CSP frame-ancestors instead, and the legacy
  11139. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  11140. # When operators have explicitly allowlisted trusted frame origins (#1191
  11141. # — typically Home Assistant on a different port), drop X-Frame-Options
  11142. # and let the CSP-side frame-ancestors directive govern embedding.
  11143. if not _TRUSTED_FRAME_ORIGINS:
  11144. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  11145. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  11146. # Content-Security-Policy for the React SPA.
  11147. # Notes:
  11148. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  11149. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  11150. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  11151. # - media-src blob:: timelapse video player uses Blob URLs.
  11152. # - font-src data:: some icon fonts are embedded as data URIs.
  11153. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  11154. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  11155. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  11156. # default CSP would render a blank page.
  11157. response.headers["Content-Security-Policy"] = (
  11158. "default-src 'self'; "
  11159. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  11160. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  11161. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  11162. "connect-src 'self'; "
  11163. "font-src 'self' data: https://fonts.gstatic.com; "
  11164. "worker-src 'self' blob:; "
  11165. "object-src 'none'; "
  11166. "base-uri 'self'; " + _frame_ancestors("'none'")
  11167. )
  11168. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  11169. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  11170. # its emscripten/embind glue generates invoker functions with `new
  11171. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  11172. # worker is governed by the policy delivered with the WORKER SCRIPT's
  11173. # own response — not the document's — so relaxing it here confines
  11174. # eval to that DOM-less worker context. The document policy below
  11175. # stays nonce-strict, and this response header has no effect when the
  11176. # file is merely fetched (a fetch's CSP is enforced against the
  11177. # requesting document, not the resource's own headers).
  11178. response.headers["Content-Security-Policy"] = (
  11179. "default-src 'self'; "
  11180. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  11181. "connect-src 'self'; "
  11182. "object-src 'none'; "
  11183. "base-uri 'self'; " + _frame_ancestors("'none'")
  11184. )
  11185. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  11186. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  11187. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  11188. # rule as the STEP worker above: the policy that governs a dedicated
  11189. # worker is the one delivered with its own script, so the wasm compile
  11190. # has to be permitted here rather than on the document. Unlike the STEP
  11191. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  11192. response.headers["Content-Security-Policy"] = (
  11193. "default-src 'self'; "
  11194. "script-src 'self' 'wasm-unsafe-eval'; "
  11195. "connect-src 'self'; "
  11196. "object-src 'none'; "
  11197. "base-uri 'self'; " + _frame_ancestors("'none'")
  11198. )
  11199. else:
  11200. # The streaming overlay is embedded same-origin by the URL builder's
  11201. # preview in Settings (#1422), so this branch allows 'self'.
  11202. # Embedding from anywhere else is still refused: 'self'
  11203. # only permits a framer on this origin, which is Bambuddy's own UI, so
  11204. # a clickjacking page on another host is blocked exactly as before.
  11205. # (The overlay draws status over a camera feed and its only interactive
  11206. # element is the logo link, so there is nothing to bait a click into
  11207. # even from a same-origin framer.) Cross-origin embedding of the
  11208. # overlay — Home Assistant on another port — remains what
  11209. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  11210. # allowlist in.
  11211. #
  11212. # The connected-app consent page (/connect/authorize) gets the same
  11213. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  11214. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  11215. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  11216. # requires every ancestor to be this origin, so a foreign page -- a
  11217. # sidebar link's site included -- still cannot frame the consent
  11218. # screen to bait a click.
  11219. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  11220. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  11221. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  11222. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  11223. # the policy served with their own script, so each gets it in its own
  11224. # branch above and the document policy stays as strict as it was.
  11225. response.headers["Content-Security-Policy"] = (
  11226. "default-src 'self'; "
  11227. f"script-src 'self' 'nonce-{csp_nonce}'; "
  11228. "style-src 'self' 'unsafe-inline'; "
  11229. "img-src 'self' data: blob:; "
  11230. "media-src 'self' blob:; "
  11231. "connect-src 'self' ws: wss:; "
  11232. "font-src 'self' data:; "
  11233. "object-src 'none'; "
  11234. "base-uri 'self'; "
  11235. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  11236. )
  11237. if request.url.scheme == "https":
  11238. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  11239. return response
  11240. @app.middleware("http")
  11241. async def auth_middleware(request, call_next):
  11242. """Enforce authentication on all API routes when auth is enabled.
  11243. This middleware provides defense-in-depth by checking auth at the API gateway level,
  11244. regardless of whether individual routes have auth dependencies.
  11245. """
  11246. from starlette.responses import JSONResponse
  11247. path = request.url.path
  11248. # Only apply to API routes
  11249. if not path.startswith("/api/"):
  11250. return await call_next(request)
  11251. # Allow public routes
  11252. if path in PUBLIC_API_ROUTES:
  11253. return await call_next(request)
  11254. # Allow public prefixes
  11255. for prefix in PUBLIC_API_PREFIXES:
  11256. if path.startswith(prefix):
  11257. return await call_next(request)
  11258. # Allow public patterns (read-only display data like thumbnails)
  11259. for pattern in PUBLIC_API_PATTERNS:
  11260. if pattern in path:
  11261. return await call_next(request)
  11262. # Check if auth is enabled. Fail CLOSED on any exception during the
  11263. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  11264. # an attacker who could force a DB exception (e.g. file-descriptor
  11265. # exhaustion via login flood) bypass auth on every protected endpoint.
  11266. # Only the probe is guarded: the request itself runs outside the try, so an
  11267. # error in a route surfaces as the 500 it is rather than as an auth outage.
  11268. try:
  11269. async with async_session() as db:
  11270. from backend.app.core.auth import is_auth_enabled
  11271. auth_enabled = await is_auth_enabled(db)
  11272. except Exception:
  11273. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  11274. return JSONResponse(
  11275. status_code=503,
  11276. content={"detail": "Authentication service temporarily unavailable"},
  11277. )
  11278. if not auth_enabled:
  11279. # Auth disabled, allow all requests
  11280. return await call_next(request)
  11281. # Auth is enabled - require valid token
  11282. auth_header = request.headers.get("Authorization")
  11283. x_api_key = request.headers.get("X-API-Key")
  11284. # Check for API key auth first
  11285. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  11286. # API key authentication - let the request through to be validated by route handler
  11287. # API keys are validated per-route since they have different permission levels
  11288. return await call_next(request)
  11289. # Check for JWT auth
  11290. if not auth_header or not auth_header.startswith("Bearer "):
  11291. return JSONResponse(
  11292. status_code=401,
  11293. content={"detail": "Authentication required"},
  11294. headers={"WWW-Authenticate": "Bearer"},
  11295. )
  11296. # Validate JWT token
  11297. import jwt
  11298. try:
  11299. from backend.app.core.auth import (
  11300. ALGORITHM,
  11301. SECRET_KEY,
  11302. _is_token_fresh,
  11303. get_user_by_username,
  11304. is_jti_revoked,
  11305. )
  11306. token = auth_header.replace("Bearer ", "")
  11307. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  11308. username = payload.get("sub")
  11309. if not username:
  11310. raise ValueError("No username in token")
  11311. jti = payload.get("jti")
  11312. if not jti:
  11313. raise ValueError("No jti in token")
  11314. iat = payload.get("iat")
  11315. # Verify user exists, is active, and token is still fresh (L-R8-A).
  11316. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  11317. # this session so the gateway adds a single pooled checkout, not two (#2572).
  11318. async with async_session() as db:
  11319. if await is_jti_revoked(jti, db):
  11320. return JSONResponse(
  11321. status_code=401,
  11322. content={"detail": "Token has been revoked"},
  11323. headers={"WWW-Authenticate": "Bearer"},
  11324. )
  11325. user = await get_user_by_username(db, username)
  11326. if not user or not user.is_active:
  11327. return JSONResponse(
  11328. status_code=401,
  11329. content={"detail": "User not found or inactive"},
  11330. headers={"WWW-Authenticate": "Bearer"},
  11331. )
  11332. if not _is_token_fresh(iat, user):
  11333. return JSONResponse(
  11334. status_code=401,
  11335. content={"detail": "Token no longer valid"},
  11336. headers={"WWW-Authenticate": "Bearer"},
  11337. )
  11338. except jwt.ExpiredSignatureError:
  11339. return JSONResponse(
  11340. status_code=401,
  11341. content={"detail": "Token has expired"},
  11342. headers={"WWW-Authenticate": "Bearer"},
  11343. )
  11344. except (jwt.InvalidTokenError, ValueError):
  11345. return JSONResponse(
  11346. status_code=401,
  11347. content={"detail": "Invalid token"},
  11348. headers={"WWW-Authenticate": "Bearer"},
  11349. )
  11350. except Exception:
  11351. # Not a bad token but a failure checking it (database, pool): refuse,
  11352. # as for the probe above, rather than answer 401 -- the frontend reads
  11353. # a 401 from /auth/me as final and signs the user out.
  11354. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  11355. return JSONResponse(
  11356. status_code=503,
  11357. content={"detail": "Authentication service temporarily unavailable"},
  11358. )
  11359. return await call_next(request)
  11360. @app.middleware("http")
  11361. async def trace_id_middleware(request, call_next):
  11362. """Stamp every HTTP request with a trace ID and echo it back.
  11363. Decorated AFTER auth_middleware on purpose: Starlette stacks
  11364. @app.middleware decorators LIFO, so the last-decorated runs first
  11365. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  11366. which means auth-middleware log lines (and every line emitted on the
  11367. way down to and back from the route handler) all carry the same
  11368. trace ID. If we put it before auth, auth's logs would be stamped
  11369. with the *previous* request's ID — useless for correlation.
  11370. Honours an inbound ``X-Trace-Id`` header so callers running their
  11371. own tracing can correlate their span IDs with our log lines, but
  11372. only if the value passes the whitelist gate in
  11373. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  11374. rejected (too long, contains control chars, etc.) silently triggers
  11375. a freshly minted server-side ID rather than failing the request.
  11376. The minted (or echoed) ID is set on a ContextVar so that every log
  11377. record emitted during the request — application logs *and* uvicorn's
  11378. access log — carries it via TraceIDFilter, and is also written to
  11379. the ``X-Trace-Id`` response header so clients can pin a server-side
  11380. log search to the exact request they made.
  11381. """
  11382. from backend.app.core.trace import (
  11383. generate_trace_id,
  11384. normalise_inbound_trace_id,
  11385. trace_id_var,
  11386. )
  11387. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  11388. trace_id = inbound if inbound is not None else generate_trace_id()
  11389. token = trace_id_var.set(trace_id)
  11390. try:
  11391. response = await call_next(request)
  11392. finally:
  11393. # Reset the ContextVar so a record emitted in a totally
  11394. # unrelated background task that just happens to inherit this
  11395. # context doesn't keep referencing this request's ID forever.
  11396. # In practice ContextVar.reset is best-effort under asyncio
  11397. # task-spawn semantics, but the cost is one attribute write so
  11398. # we may as well do it.
  11399. trace_id_var.reset(token)
  11400. response.headers["X-Trace-Id"] = trace_id
  11401. return response
  11402. # API routes
  11403. app.include_router(auth.router, prefix=app_settings.api_prefix)
  11404. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  11405. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  11406. app.include_router(users.router, prefix=app_settings.api_prefix)
  11407. app.include_router(groups.router, prefix=app_settings.api_prefix)
  11408. app.include_router(printers.router, prefix=app_settings.api_prefix)
  11409. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  11410. app.include_router(archives.router, prefix=app_settings.api_prefix)
  11411. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  11412. app.include_router(finance.router, prefix=app_settings.api_prefix)
  11413. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  11414. app.include_router(labels.router, prefix=app_settings.api_prefix)
  11415. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  11416. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  11417. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  11418. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  11419. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  11420. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  11421. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  11422. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  11423. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  11424. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  11425. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  11426. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  11427. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  11428. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  11429. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  11430. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  11431. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  11432. app.include_router(updates.router, prefix=app_settings.api_prefix)
  11433. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  11434. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  11435. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  11436. app.include_router(camera.router, prefix=app_settings.api_prefix)
  11437. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  11438. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  11439. app.include_router(projects.router, prefix=app_settings.api_prefix)
  11440. app.include_router(library.router, prefix=app_settings.api_prefix)
  11441. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  11442. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  11443. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  11444. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  11445. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  11446. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  11447. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  11448. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  11449. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  11450. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  11451. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  11452. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  11453. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  11454. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  11455. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  11456. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  11457. app.include_router(system.router, prefix=app_settings.api_prefix)
  11458. app.include_router(support.router, prefix=app_settings.api_prefix)
  11459. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  11460. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  11461. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  11462. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  11463. app.include_router(bulk.router, prefix=app_settings.api_prefix)
  11464. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  11465. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  11466. app.include_router(obico.router, prefix=app_settings.api_prefix)
  11467. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  11468. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  11469. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  11470. # Serve static files (React build)
  11471. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  11472. # Compressed, and cached for good where Vite hashed the name (#3175).
  11473. app.mount(
  11474. "/assets",
  11475. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  11476. name="assets",
  11477. )
  11478. if (app_settings.static_dir / "img").exists():
  11479. app.mount(
  11480. "/img",
  11481. StaticFiles(directory=app_settings.static_dir / "img"),
  11482. name="img",
  11483. )
  11484. if (app_settings.static_dir / "icons").exists():
  11485. app.mount(
  11486. "/icons",
  11487. StaticFiles(directory=app_settings.static_dir / "icons"),
  11488. name="icons",
  11489. )
  11490. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  11491. # falls through to the SPA catch-all and returns index.html, which the
  11492. # browser's font sanitizer rejects ("downloadable font: rejected by
  11493. # sanitizer").
  11494. if (app_settings.static_dir / "fonts").exists():
  11495. app.mount(
  11496. "/fonts",
  11497. StaticFiles(directory=app_settings.static_dir / "fonts"),
  11498. name="fonts",
  11499. )
  11500. @app.get("/")
  11501. async def serve_frontend():
  11502. """Serve the React frontend."""
  11503. index_file = app_settings.static_dir / "index.html"
  11504. if index_file.exists():
  11505. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11506. return {
  11507. "message": "Bambuddy API",
  11508. "docs": "/docs",
  11509. "frontend": "Build and place React app in /static directory",
  11510. }
  11511. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  11512. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  11513. # forever, but the HTML wrapping it is the only file that knows which hash
  11514. # is current. Without explicit cache-control headers Chromium decides
  11515. # heuristically (typically 10% of the time since Last-Modified) and on
  11516. # long-running kiosks happily serves stale HTML across browser restarts.
  11517. # That stale HTML references an old bundle hash, the old bundle is also
  11518. # in the disk cache, and the user ends up running pre-update JS forever
  11519. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  11520. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  11521. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  11522. @app.get("/health")
  11523. async def health_check():
  11524. """Health check endpoint."""
  11525. return {"status": "healthy"}
  11526. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  11527. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  11528. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  11529. # in deployment debugging. One decorator per method, not api_route(methods=
  11530. # [...]): api_route gives both methods the same OpenAPI operation id.
  11531. @app.get("/manifest.json")
  11532. @app.head("/manifest.json")
  11533. async def serve_manifest():
  11534. """Serve PWA manifest."""
  11535. manifest_file = app_settings.static_dir / "manifest.json"
  11536. if manifest_file.exists():
  11537. return FileResponse(manifest_file, media_type="application/manifest+json")
  11538. return {"error": "Manifest not found"}
  11539. @app.get("/sw.js")
  11540. @app.head("/sw.js")
  11541. async def serve_service_worker():
  11542. """Serve service worker."""
  11543. sw_file = app_settings.static_dir / "sw.js"
  11544. if sw_file.exists():
  11545. return FileResponse(
  11546. sw_file,
  11547. media_type="application/javascript",
  11548. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  11549. )
  11550. return {"error": "Service worker not found"}
  11551. @app.get("/sw-register.js")
  11552. @app.head("/sw-register.js")
  11553. async def serve_sw_register():
  11554. """Serve the service-worker registration bootstrap script.
  11555. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  11556. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  11557. """
  11558. reg_file = app_settings.static_dir / "sw-register.js"
  11559. if reg_file.exists():
  11560. return FileResponse(reg_file, media_type="application/javascript")
  11561. return {"error": "sw-register.js not found"}
  11562. # ── GCode viewer static files ────────────────────────────────────────────────
  11563. # Catch-all route for React Router (must be last)
  11564. @app.get("/{full_path:path}")
  11565. async def serve_spa(full_path: str):
  11566. """Serve React app for client-side routing."""
  11567. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  11568. if full_path.startswith("api/"):
  11569. from fastapi import HTTPException
  11570. raise HTTPException(status_code=404, detail="Not found")
  11571. index_file = app_settings.static_dir / "index.html"
  11572. if index_file.exists():
  11573. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  11574. return {"error": "Frontend not built"}