main.py 587 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125
  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, 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. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  465. # Used by usage tracker to map 3MF slots to physical AMS trays
  466. _print_ams_mappings: dict[int, list[int]] = {}
  467. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  468. _print_cost_center_ids: dict[int, int] = {}
  469. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  470. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  471. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  472. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  473. # for the queue path. Cleared on print completion or TTL eviction.
  474. _print_plate_ids: dict[int, int] = {}
  475. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  476. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  477. _last_progress_milestone: dict[int, int] = {}
  478. # Track whether first layer complete notification has been sent for current print
  479. _first_layer_notified: dict[int, bool] = {}
  480. # Track whether we already sent a kill-switch stop for the current unauthorized print
  481. _unauthorized_print_kill_sent: set[int] = set()
  482. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  483. # lookup briefly so an unknown active print does not query the database on
  484. # every status frame. A short TTL keeps settings changes responsive.
  485. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  486. _kill_switch_setting_cache: tuple[bool, float] | None = None
  487. # Provider notification started when the kill switch stops a print. The later
  488. # MQTT print-complete callback awaits this task and only sends its regular
  489. # provider notification when the immediate attempt failed.
  490. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  491. # HMS faults already notified, with when each was last seen:
  492. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  493. # fault that flickers beside a held notice was forgotten on every gap and
  494. # notified on every return (#3226). The window is long because the measured
  495. # gaps reach 64 s.
  496. _notified_hms_errors: dict[int, dict[str, float]] = {}
  497. _HMS_CLEAR_GRACE_SECONDS = 600.0
  498. # The print state each printer was last seen in, and the faults recorded before
  499. # it last changed, which are forgotten as soon as they are gone (see
  500. # _take_new_hms_faults).
  501. _hms_print_state: dict[int, str] = {}
  502. _hms_forget_when_gone: dict[int, set[str]] = {}
  503. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  504. # Used for snapshot-diff detection at print completion
  505. _timelapse_baselines: dict[int, set[str]] = {}
  506. # Track printers waiting for bed to cool after print completion.
  507. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  508. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  509. _bed_cool_waiters: dict[int, dict] = {}
  510. # Track printers where the user explicitly stopped the print from the queue UI.
  511. # When on_print_complete fires with status "failed" for these printers we treat it
  512. # as "cancelled" (stopped by user) so the correct notification email is sent.
  513. _user_stopped_printers: set[int] = set()
  514. # Printers whose running print the kill switch stopped. Their completion is a
  515. # cancel with the reason "killSwitch", not the "failed" the printer reports.
  516. _kill_switch_stopped: set[int] = set()
  517. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  518. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  519. # holds the previous observation so we only fire on the True → False edge (a
  520. # False → False repeat doesn't notify; an initial False at startup doesn't
  521. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  522. # holds the per-printer pending asyncio task that fires the notification
  523. # after a debounce window — cancelled if the printer reconnects before the
  524. # window elapses, so transient MQTT blips don't flood the user.
  525. _printer_last_connected: dict[int, bool] = {}
  526. # Printers whose relay offline event went out, so the reconnect publishes the
  527. # matching online event and a blip shorter than the debounce publishes neither.
  528. _printer_offline_published: set[int] = set()
  529. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  530. # Debounce: a printer must stay offline this long before we notify. Sized
  531. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  532. # so a single stale-trigger cooldown isn't enough to fire — only a real
  533. # offline that survives one reconnect attempt notifies.
  534. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  535. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  536. # when status="failed" to label the print's failure_reason in archives.
  537. #
  538. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  539. # which is wrong on two counts:
  540. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  541. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  542. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  543. # the public wiki) as part of its user-cancel sequence. Matching on the module
  544. # alone caused user-cancellations to be archived as "Layer shift" failures.
  545. # We now match by full short code only — anything not in this map leaves
  546. # failure_reason=None rather than guessing.
  547. # Values are the canonical camelCase failure-reason keys, NOT display labels
  548. # (issue #2974). The vocabulary is enforced on writes by
  549. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  550. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  551. # Statistics breakdown. Storing a label here instead put a second spelling of
  552. # the same cause into one column: the Failure Analysis widget groups on the raw
  553. # value, so a print the backend classified and an identical one a user
  554. # classified counted as two different reasons, and the label form could never
  555. # be translated because there was no key for ``t()`` to resolve.
  556. _HMS_FAILURE_REASONS: dict[str, str] = {
  557. # Layer shift / step loss
  558. "0300_4057": "layerShift",
  559. "0300_4068": "layerShift",
  560. "0300_800C": "layerShift",
  561. # Filament runout (printer-side & per-AMS-slot)
  562. "0300_8004": "filamentRunout",
  563. "0700_8011": "filamentRunout",
  564. "0701_8011": "filamentRunout",
  565. "0702_8011": "filamentRunout",
  566. "0703_8011": "filamentRunout",
  567. "0704_8011": "filamentRunout",
  568. "0705_8011": "filamentRunout",
  569. "0706_8011": "filamentRunout",
  570. "0707_8011": "filamentRunout",
  571. "07FF_8011": "filamentRunout",
  572. # Clogged nozzle / extruder
  573. "0300_4006": "cloggedNozzle",
  574. "0300_8016": "cloggedNozzle",
  575. "0300_801C": "cloggedNozzle",
  576. "0700_8003": "cloggedNozzle",
  577. "0700_8007": "cloggedNozzle",
  578. "0700_8013": "cloggedNozzle",
  579. "0701_8003": "cloggedNozzle",
  580. "0701_8007": "cloggedNozzle",
  581. "0701_8013": "cloggedNozzle",
  582. "0702_8003": "cloggedNozzle",
  583. # AI print monitoring — spaghetti / the model coming off the plate.
  584. # `spaghettiDetached` is a key the archive editor already offers for this
  585. # failure mode, not a new one, so a derived reason opens the dropdown on
  586. # that option rather than blank — and survives the next save, which clears
  587. # any value the editor does not recognise.
  588. #
  589. # A module-0x0C row is safe here despite the warning above: that warning is
  590. # about matching on the module alone, and 0C00_8042 is a full short code
  591. # with a documented meaning ("The AI print monitor has detected a spaghetti
  592. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  593. # cannot collide.
  594. #
  595. # 0300_8003's own text ends "before continuing your print", but on an X2D
  596. # it arrives with the print already paused, offering only
  597. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  598. #
  599. # Two neighbours are left out on purpose, so this does not get re-derived:
  600. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  601. # reads as a warning about a print that is still running, not a halt.
  602. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  603. # the waste chute. That is not the print failing.
  604. #
  605. # That line is drawn from the text, not from `severity`, because severity
  606. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  607. # module/error word with no level in it, and bambu_mqtt.py gives every
  608. # print_error entry a flat severity=3. Matching on the short code alone is
  609. # the right shape for derive_failure_reason, not an omission.
  610. "0300_8003": "spaghettiDetached",
  611. "0C00_8042": "spaghettiDetached",
  612. }
  613. def _hms_short_code(attr: int, code: int | str) -> str:
  614. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  615. if isinstance(code, str):
  616. code_int = int(code.replace("0x", ""), 16) if code else 0
  617. else:
  618. code_int = int(code or 0)
  619. attr_int = int(attr or 0)
  620. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  621. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  622. """Derive the failure_reason key for an archived print.
  623. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  624. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  625. no HMS code matches (don't guess — null is honest). The keys are the
  626. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  627. translated at render time.
  628. """
  629. if status in ("aborted", "cancelled"):
  630. return "userCancelled"
  631. if status != "failed":
  632. return None
  633. for err in hms_errors or []:
  634. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  635. if short_code in _HMS_FAILURE_REASONS:
  636. return _HMS_FAILURE_REASONS[short_code]
  637. return None
  638. # Track created_by_id for expected prints so the user email can be sent even when
  639. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  640. # {(printer_id, filename): created_by_id}
  641. _expected_print_creators: dict[tuple[int, str], int] = {}
  642. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  643. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  644. # tag tuple changes for the slot. Cleared when the slot is reported empty
  645. # so remove + reinsert reliably re-prompts the UI.
  646. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  647. async def _broadcast_unknown_tag(
  648. *,
  649. printer_id: int,
  650. ams_id: int,
  651. tray_id: int,
  652. tag_uid: str,
  653. tray_uuid: str,
  654. tray_type: str | None = None,
  655. tray_color: str | None = None,
  656. tray_sub_brands: str | None = None,
  657. tray_count: int | None = None,
  658. ) -> None:
  659. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  660. _logger = logging.getLogger(__name__)
  661. slot_key = (ams_id, tray_id)
  662. tag_key = (tag_uid or "", tray_uuid or "")
  663. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  664. if per_printer.get(slot_key) == tag_key:
  665. _logger.debug(
  666. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  667. printer_id,
  668. ams_id,
  669. tray_id,
  670. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  671. )
  672. return
  673. _logger.info(
  674. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  675. printer_id,
  676. ams_id,
  677. tray_id,
  678. tray_type,
  679. tray_color,
  680. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  681. )
  682. # Broadcast first; only commit the dedup if the WS write succeeds.
  683. # If broadcast raises, the next MQTT push retries instead of being
  684. # permanently silenced by a poisoned dedup entry.
  685. await ws_manager.broadcast(
  686. {
  687. "type": "unknown_tag",
  688. "printer_id": printer_id,
  689. "ams_id": ams_id,
  690. "tray_id": tray_id,
  691. "tag_uid": tag_uid,
  692. "tray_uuid": tray_uuid,
  693. "tray_type": tray_type,
  694. "tray_color": tray_color,
  695. "tray_sub_brands": tray_sub_brands,
  696. "tray_count": tray_count,
  697. }
  698. )
  699. per_printer[slot_key] = tag_key
  700. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  701. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  702. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  703. if per_printer is None:
  704. return
  705. per_printer.pop((ams_id, tray_id), None)
  706. # TTL for expected-print entries: evict registrations older than this to prevent
  707. # unbounded growth when a print is registered but never starts (e.g. printer
  708. # disconnect, app restart, print started from the printer panel).
  709. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  710. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  711. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  712. # Cleanup loop interval
  713. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  714. _expected_prints_cleanup_task: asyncio.Task | None = None
  715. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  716. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  717. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  718. possible_keys: list[tuple[int, str]] = []
  719. filename = (state.gcode_file or state.current_print or "").strip()
  720. subtask_name = (state.subtask_name or "").strip()
  721. if subtask_name:
  722. possible_keys.append((printer_id, subtask_name))
  723. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  724. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  725. if filename:
  726. base_name = filename.rsplit("/", 1)[-1]
  727. if base_name.endswith(".gcode.3mf"):
  728. root_name = base_name[: -len(".gcode.3mf")]
  729. possible_keys.append((printer_id, root_name))
  730. possible_keys.append((printer_id, base_name))
  731. possible_keys.append((printer_id, f"{root_name}.gcode"))
  732. possible_keys.append((printer_id, f"{root_name}.3mf"))
  733. elif base_name.endswith(".3mf"):
  734. root_name = base_name[: -len(".3mf")]
  735. possible_keys.append((printer_id, root_name))
  736. possible_keys.append((printer_id, base_name))
  737. elif base_name.endswith(".gcode"):
  738. root_name = base_name[: -len(".gcode")]
  739. possible_keys.append((printer_id, root_name))
  740. possible_keys.append((printer_id, f"{root_name}.3mf"))
  741. possible_keys.append((printer_id, base_name))
  742. else:
  743. possible_keys.append((printer_id, base_name))
  744. possible_keys.append((printer_id, f"{base_name}.3mf"))
  745. return possible_keys
  746. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  747. """The id of who started the print, unless that user has been deleted since.
  748. Deleting a user forgets them in printer_manager, but a print that ended a
  749. moment before still holds them.
  750. """
  751. if not print_user or print_user.get("user_id") is None:
  752. return None
  753. from backend.app.models.user import User
  754. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  755. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  756. """Check the cheap, process-local print ownership signals."""
  757. if printer_manager.get_current_print_user(printer_id):
  758. return True
  759. return any(
  760. key in _expected_prints or _active_prints.get(key) in _owned_print_archive_ids
  761. for key in _build_status_print_keys(printer_id, state)
  762. )
  763. def _bind_active_print(
  764. printer_id: int,
  765. archive_id: int,
  766. archive_filename: str | None,
  767. filename: str | None = None,
  768. subtask_name: str | None = None,
  769. ) -> None:
  770. """Track a running print under every name its completion may report.
  771. One set for every path that binds a print (new archive, expected print,
  772. restart resume, fallback): the archive's file name, the name the printer
  773. reported, and the subtask with and without ``.3mf``. Paths that registered
  774. fewer names lost the bound archive at completion, and with it the plate
  775. restore's height (#3240), whenever MQTT reported a name they had left out.
  776. """
  777. for name in {archive_filename, filename, f"{subtask_name}.3mf" if subtask_name else None, subtask_name}:
  778. if name:
  779. _active_prints[(printer_id, name)] = archive_id
  780. def _mark_owned_if_dispatched(archive) -> None:
  781. """Remember a running print's archive as Bambuddy's when it carries a
  782. dispatch marker Bambuddy writes itself: ``billing_run_id`` (minted per
  783. dispatch in the scheduler) or ``created_by_id`` (from the queue item)."""
  784. if archive.billing_run_id is not None or archive.created_by_id is not None:
  785. _owned_print_archive_ids.add(archive.id)
  786. async def _is_printer_kill_switch_enabled_cached() -> bool:
  787. """Return the kill-switch setting without querying on every MQTT frame."""
  788. global _kill_switch_setting_cache
  789. now = time.monotonic()
  790. if _kill_switch_setting_cache is not None:
  791. enabled, expires_at = _kill_switch_setting_cache
  792. if now < expires_at:
  793. return enabled
  794. async with async_session() as db:
  795. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  796. enabled = await is_printer_kill_switch_enabled(db)
  797. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  798. return enabled
  799. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  800. """Resolve whether the current print was started by Bambuddy.
  801. ``None`` means identity is not yet safe to decide. The kill switch must
  802. defer in that case: stopping a print is irreversible, and the first status
  803. frames after a restart may arrive before all subtask fields are populated.
  804. """
  805. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  806. return True
  807. # The printer's built-in calibration runs (Bambuddy's Calibrate, the
  808. # printer's screen) play gcode from its read-only system partition, where no
  809. # user file can be. Only that path counts: a calibration *name* proves
  810. # nothing, since Bambu Studio's pressure-advance print reports a user-style
  811. # path, and any print can be given that name.
  812. if str(getattr(state, "gcode_file", "") or "").startswith("/usr/"):
  813. return True
  814. # A1, A1 Mini, P1 and A2L report the same calibration as a bare file name,
  815. # which nothing distinguishes from a user's file given that name, so it is
  816. # not exempt: with the kill switch on, calibrate on those printers with the
  817. # switch off.
  818. possible_keys = _build_status_print_keys(printer_id, state)
  819. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  820. # is on disk. subtask_id is minted per print and pins the answer to the job
  821. # actually running, rather than to an unrelated one that reuses a filename.
  822. raw_subtask_id = getattr(state, "subtask_id", None)
  823. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  824. if subtask_id == "":
  825. # Not reported yet: the first frames after a restart can lack it.
  826. return None
  827. from backend.app.models.archive import PrintArchive
  828. if subtask_id == "0":
  829. # A print started outside the cloud from Bambu Studio, Handy or the
  830. # printer's screen reports "0", so there is no id to match: one of
  831. # Bambuddy's printing archives on this printer under the name the
  832. # printer reports, compared as the printer echoes names (spaces become
  833. # underscores). Nothing reported to compare yet: wait.
  834. reported = {_normalise_subtask_name(name) for _pid, name in possible_keys} - {""}
  835. if not reported:
  836. return None
  837. dispatched = await db.execute(
  838. select(PrintArchive)
  839. .where(
  840. PrintArchive.printer_id == printer_id,
  841. PrintArchive.status == "printing",
  842. or_(PrintArchive.billing_run_id.is_not(None), PrintArchive.created_by_id.is_not(None)),
  843. # An archive with a real id of its own is a print that reported
  844. # one: a "0" print is not it, even under the same name (one whose
  845. # completion was missed would otherwise cover it).
  846. or_(PrintArchive.subtask_id.is_(None), PrintArchive.subtask_id.in_(("", "0"))),
  847. )
  848. .order_by(PrintArchive.created_at.desc())
  849. )
  850. archive = next((a for a in dispatched.scalars() if _archive_name_forms(a) & reported), None)
  851. else:
  852. result = await db.execute(
  853. select(PrintArchive)
  854. .where(
  855. PrintArchive.printer_id == printer_id,
  856. PrintArchive.status == "printing",
  857. PrintArchive.subtask_id == subtask_id,
  858. )
  859. .order_by(PrintArchive.created_at.desc())
  860. .limit(1)
  861. )
  862. archive = result.scalar_one_or_none()
  863. # An archive row on its own proves nothing: `on_print_start` archives every
  864. # print it observes, including ones started from Bambu Studio or Handy, and
  865. # stamps them with the same status and subtask_id. Authorizing on its mere
  866. # existence would disable the kill switch the moment the 3MF finishes
  867. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  868. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  869. # (carried over from the queue item that started it).
  870. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  871. # Rehydrate the fast in-memory path for subsequent status frames. Include
  872. # both the archive filename and every normalized key reported by MQTT.
  873. _owned_print_archive_ids.add(archive.id)
  874. _active_prints[(printer_id, archive.filename)] = archive.id
  875. for key in possible_keys:
  876. _active_prints[key] = archive.id
  877. return True
  878. # No dispatch marker. Before calling this someone else's print, check whether
  879. # Bambuddy has a job of its own running on this printer: a library-file
  880. # dispatch has no archive at send time, and an archive created seconds later
  881. # by `on_print_start` carries neither marker. The queue row, which the
  882. # scheduler commits to status="printing" before the MQTT send, is the one
  883. # durable record every Bambuddy print has. It cannot be tied to this
  884. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  885. # print is irreversible, and refusing to act costs nothing but a log line.
  886. from backend.app.models.print_queue import PrintQueueItem
  887. dispatched_here = await db.scalar(
  888. select(PrintQueueItem.id)
  889. .where(
  890. PrintQueueItem.printer_id == printer_id,
  891. PrintQueueItem.status == "printing",
  892. )
  893. .limit(1)
  894. )
  895. if dispatched_here is not None:
  896. return None
  897. return False
  898. async def _send_kill_switch_provider_notification(
  899. printer_id: int,
  900. printer_name: str,
  901. data: dict,
  902. ) -> bool:
  903. """Send the immediate print-stopped provider notification.
  904. Returning a success flag lets the normal MQTT completion path retry when
  905. this early notification could not be delivered.
  906. """
  907. logger = logging.getLogger(__name__)
  908. try:
  909. async with async_session() as db:
  910. await notification_service.on_print_complete(
  911. printer_id,
  912. printer_name,
  913. "stopped",
  914. data,
  915. db,
  916. )
  917. return True
  918. except Exception as e:
  919. logger.warning(
  920. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  921. printer_id,
  922. e,
  923. )
  924. return False
  925. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  926. """Wait for an immediate kill-switch notification, if one was scheduled."""
  927. if task is None:
  928. return False
  929. try:
  930. return await task
  931. except Exception as e:
  932. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  933. return False
  934. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  935. """Capture the smart plug lifetime counter on the archive at print start.
  936. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  937. tracking survives a backend restart mid-print. The print-end handler reads
  938. this value back from the DB and computes the delta against the current
  939. plug counter.
  940. """
  941. _logger = logging.getLogger(__name__)
  942. try:
  943. candidates = await energy_plug_candidates(db, printer_id)
  944. if not candidates:
  945. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  946. return False
  947. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  948. if selected is None:
  949. # Naming the plugs matters here: with several linked to one printer
  950. # this is the difference between "the meter is offline" and "you
  951. # linked only accessories" (#2859).
  952. _logger.warning(
  953. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  954. printer_id,
  955. archive.id,
  956. ", ".join(plug.name for plug in candidates),
  957. )
  958. return False
  959. plug, energy = selected
  960. archive.energy_start_kwh = float(energy["total"])
  961. # With the plug's snapshots, what lets the cost follow the price over
  962. # the print rather than take the price at its end (#1251). A price that
  963. # can't be had must not cost the print its energy reading.
  964. archive.energy_start_at = utcnow_naive()
  965. archive.energy_start_plug_id = plug.id
  966. try:
  967. from backend.app.services.energy_price import current_price
  968. archive.energy_start_price = await current_price(db)
  969. except Exception as e:
  970. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  971. archive.energy_start_price = None
  972. await db.commit()
  973. _logger.info(
  974. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  975. f" ({context})" if context else "",
  976. archive.id,
  977. plug.name,
  978. energy["total"],
  979. )
  980. return True
  981. except Exception as e:
  982. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  983. return False
  984. def forget_print_creator(user_id: int) -> None:
  985. """The print-start emails of a deleted user's jobs go to nobody, not to
  986. whoever is given the id next (SQLite reuses it)."""
  987. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  988. del _expected_print_creators[key]
  989. async def forget_printer(printer_id: int) -> None:
  990. """Drop what is kept for a deleted printer's id, here and in the services.
  991. SQLite used to give the id to the next printer created, which inherited it
  992. all: the running print's owner (its prints passed the kill switch and were
  993. billed to that user), the plate-clear gate, pending and suppressed
  994. notifications, the camera feed, the plate references. Ids are no longer
  995. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  996. stay. Called after the delete is committed, and again by work that was in
  997. flight and wrote state back.
  998. Every printer-keyed map of this module is listed here or, with the reason,
  999. in tests/unit/test_forget_printer.py.
  1000. """
  1001. from backend.app.api.routes import camera
  1002. from backend.app.services import (
  1003. bambu_ftp,
  1004. kprofile_drift,
  1005. layer_timelapse,
  1006. plate_detection,
  1007. print_dispatch_context,
  1008. usage_tracker,
  1009. )
  1010. from backend.app.services.notify_live_activities import notify_live_activities
  1011. from backend.app.services.obico_detection import obico_detection_service
  1012. from backend.app.services.printer_file_cache import printer_file_cache
  1013. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  1014. archive_ids = set()
  1015. for tracked in (_active_prints, _expected_prints):
  1016. for key in [key for key in tracked if key[0] == printer_id]:
  1017. archive_ids.add(tracked.pop(key))
  1018. for archive_id in archive_ids:
  1019. _owned_print_archive_ids.discard(archive_id)
  1020. _print_ams_mappings.pop(archive_id, None)
  1021. _print_cost_center_ids.pop(archive_id, None)
  1022. _print_plate_ids.pop(archive_id, None)
  1023. for tracked in (_expected_print_creators, _expected_print_registered_at):
  1024. for key in [key for key in tracked if key[0] == printer_id]:
  1025. del tracked[key]
  1026. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  1027. _ams_index_only_logged.discard(key)
  1028. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  1029. del _ams_alarm_cooldown[key]
  1030. # Pending work that would act on the id: an offline notice, a 3MF retry.
  1031. # A kill-switch notice is about a stop that happened and is left to finish.
  1032. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  1033. task = tasks.pop(printer_id, None)
  1034. if task is not None:
  1035. task.cancel()
  1036. for keyed in (
  1037. _stage22_finish_frames,
  1038. _stage22_finish_in_flight,
  1039. _inprint_frame_bank,
  1040. _inprint_frame_bank_ts,
  1041. _printer_reconciled_since_connect,
  1042. _printer_kprofiles_primed_since_connect,
  1043. _last_progress_milestone,
  1044. _first_layer_notified,
  1045. _kill_switch_notification_tasks,
  1046. _notified_hms_errors,
  1047. _hms_print_state,
  1048. _hms_forget_when_gone,
  1049. _timelapse_baselines,
  1050. _bed_cool_waiters,
  1051. _printer_last_connected,
  1052. _unknown_tag_last_broadcast,
  1053. _last_status_broadcast,
  1054. _connection_watchdog_last_attempt,
  1055. ):
  1056. keyed.pop(printer_id, None)
  1057. for marked in (
  1058. _unauthorized_print_kill_sent,
  1059. _user_stopped_printers,
  1060. _kill_switch_stopped,
  1061. _printer_offline_published,
  1062. _nozzle_count_updated,
  1063. _runtime_seen_connected,
  1064. ):
  1065. marked.discard(printer_id)
  1066. printer_manager.forget_printer(printer_id)
  1067. printer_file_cache.forget_printer(printer_id)
  1068. print_dispatch_context.clear(printer_id)
  1069. kprofile_drift.forget_printer(printer_id, deleted=True)
  1070. layer_timelapse.cancel_session(printer_id)
  1071. usage_tracker.forget_printer(printer_id)
  1072. obico_detection_service.forget_printer(printer_id)
  1073. bambu_ftp.clear_3mf_cache(printer_id)
  1074. await camera.forget_printer(printer_id)
  1075. printers.clear_cover_cache(printer_id)
  1076. print_scheduler.forget_printer(printer_id)
  1077. notify_live_activities.forget_printer(printer_id)
  1078. plate_detection.remove_printer_references(printer_id)
  1079. def register_expected_print(
  1080. printer_id: int,
  1081. filename: str,
  1082. archive_id: int,
  1083. ams_mapping: list[int] | None = None,
  1084. created_by_id: int | None = None,
  1085. cost_center_id: int | None = None,
  1086. plate_id: int | None = None,
  1087. ):
  1088. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1089. # Store with multiple filename variations to catch different naming patterns
  1090. _expected_prints[(printer_id, filename)] = archive_id
  1091. # Also store without .3mf extension if present
  1092. if filename.endswith(".3mf"):
  1093. base = filename[:-4]
  1094. _expected_prints[(printer_id, base)] = archive_id
  1095. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1096. # Store AMS mapping for usage tracking at print completion, and plate_id for
  1097. # a single-plate dispatch from a multi-plate 3MF — without it, the direct-Print
  1098. # path attributes the whole file's filament total to the spool instead of just
  1099. # the printed plate (#1697). They describe this dispatch: one that has none
  1100. # drops what an earlier dispatch of the archive left (sent, never started),
  1101. # unless a plate of the archive is printing now and still needs them.
  1102. archive_printing = archive_id in set(_active_prints.values())
  1103. if ams_mapping is not None:
  1104. _print_ams_mappings[archive_id] = ams_mapping
  1105. elif not archive_printing:
  1106. _print_ams_mappings.pop(archive_id, None)
  1107. if cost_center_id is not None:
  1108. _print_cost_center_ids[archive_id] = cost_center_id
  1109. elif not archive_printing:
  1110. _print_cost_center_ids.pop(archive_id, None)
  1111. if plate_id is not None:
  1112. _print_plate_ids[archive_id] = plate_id
  1113. elif not archive_printing:
  1114. _print_plate_ids.pop(archive_id, None)
  1115. # Store created_by_id so the user start email can be sent even when the archive
  1116. # itself has no created_by_id (e.g. library-file-based queue prints)
  1117. if created_by_id is not None:
  1118. _expected_print_creators[(printer_id, filename)] = created_by_id
  1119. if filename.endswith(".3mf"):
  1120. base = filename[:-4]
  1121. _expected_print_creators[(printer_id, base)] = created_by_id
  1122. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1123. # Record registration time for TTL-based eviction
  1124. _registered_at = time.monotonic()
  1125. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1126. if filename.endswith(".3mf"):
  1127. base = filename[:-4]
  1128. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1129. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1130. logging.getLogger(__name__).info(
  1131. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1132. )
  1133. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1134. """Undo :func:`register_expected_print` when the print never went out.
  1135. Registration has to happen *before* the MQTT print command, because the
  1136. printer can report the print before the line after the send executes. So
  1137. every path that registers and then fails to send — a cancel winning the
  1138. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1139. between — leaves an expectation for a print that will never arrive.
  1140. The TTL sweep evicts those after two hours, which is far longer than it
  1141. takes a user to react to a failed dispatch by pressing print again: that
  1142. reprint would be folded into the *old* archive and take the stale
  1143. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1144. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1145. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1146. are keyed by archive, not by file, so they may only be dropped once no
  1147. live key still points at that archive.
  1148. """
  1149. keys = [(printer_id, filename)]
  1150. if filename.endswith(".3mf"):
  1151. base = filename[:-4]
  1152. keys.append((printer_id, base))
  1153. keys.append((printer_id, f"{base}.gcode"))
  1154. removed = False
  1155. for key in keys:
  1156. if _expected_prints.pop(key, None) is not None:
  1157. removed = True
  1158. _expected_print_creators.pop(key, None)
  1159. _expected_print_registered_at.pop(key, None)
  1160. # Still needed by another expected print of the archive, or a plate of it
  1161. # that is printing, as in the sweep.
  1162. if archive_id not in set(_expected_prints.values()) | set(_active_prints.values()):
  1163. _print_ams_mappings.pop(archive_id, None)
  1164. _print_cost_center_ids.pop(archive_id, None)
  1165. _print_plate_ids.pop(archive_id, None)
  1166. if removed:
  1167. logging.getLogger(__name__).info(
  1168. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1169. printer_id,
  1170. filename,
  1171. archive_id,
  1172. )
  1173. def _compute_run_filament_grams(
  1174. status: str,
  1175. archive_filament_used_grams: float | None,
  1176. progress: float | int | None,
  1177. usage_results: list[dict] | None,
  1178. ) -> float | None:
  1179. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1180. Priority for every status:
  1181. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1182. weight delta — same source that drives "Total Consumed" on the
  1183. Inventory page, so Stats and Inventory totals stay aligned).
  1184. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1185. back to the canonical "this print used X" value).
  1186. 3. For partial statuses: ``estimate * progress%``.
  1187. 4. ``None`` if nothing is known.
  1188. """
  1189. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1190. if tracked_grams > 0:
  1191. return round(tracked_grams, 1)
  1192. if status == "completed":
  1193. return archive_filament_used_grams
  1194. if archive_filament_used_grams:
  1195. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1196. if scale > 0:
  1197. return round(archive_filament_used_grams * scale, 1)
  1198. return None
  1199. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  1200. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1201. stored_ams_mapping = data.get("ams_mapping")
  1202. if not stored_ams_mapping and archive_id:
  1203. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  1204. return stored_ams_mapping
  1205. def _get_start_plate_id(archive_id: int | None) -> int | None:
  1206. """Resolve plate_id for print start without consuming stored direct-Print state.
  1207. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1208. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1209. read it back at print-start without popping (the entry is popped on print
  1210. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1211. """
  1212. if archive_id is None:
  1213. return None
  1214. return _print_plate_ids.get(archive_id)
  1215. def _partial_progress_scale(progress: int | float | None) -> float:
  1216. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1217. Used by every site that multiplies a "would-have-used" slicer estimate
  1218. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1219. so the three sites in ``_background_notifications`` (and the per-plate
  1220. override helper) can't drift apart on the coercion shape.
  1221. """
  1222. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1223. def _scope_notification_archive_data_to_plate(
  1224. archive_data: dict,
  1225. archive_file_path: str | None,
  1226. plate_id: int | None,
  1227. print_status: str,
  1228. progress: int | float | None,
  1229. base_dir: Path,
  1230. ) -> dict:
  1231. """Override summed-across-plates totals in ``archive_data`` with the values
  1232. for ``plate_id`` so the completion notification reports what was actually
  1233. printed, not the whole project (#1785).
  1234. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1235. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1236. the archive card's "whole project" headline, wrong for the completion
  1237. notification of a single-plate print. The queue UI already re-reads the
  1238. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1239. notification payload (filament grams, time estimate, per-slot breakdown).
  1240. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1241. no per-plate values — in every fail case the original ``archive_data`` is
  1242. returned unchanged so the notification still sends.
  1243. """
  1244. if plate_id is None or not archive_file_path:
  1245. return archive_data
  1246. from backend.app.utils.threemf_tools import (
  1247. extract_filament_usage_from_3mf,
  1248. extract_print_time_from_3mf,
  1249. )
  1250. archive_path = base_dir / archive_file_path
  1251. if not archive_path.exists():
  1252. return archive_data
  1253. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1254. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1255. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1256. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1257. if plate_time:
  1258. archive_data["print_time_seconds"] = plate_time
  1259. # Gate both the grams headline AND the per-slot breakdown on the same
  1260. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1261. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1262. # to the project-level grams the archive columns already provide rather
  1263. # than ship a project-level headline next to an all-zero per-plate
  1264. # breakdown.
  1265. if plate_grams > 0:
  1266. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1267. archive_data["filament_slots"] = [
  1268. {
  1269. "slot_id": s.get("slot_id"),
  1270. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1271. "type": s.get("type", ""),
  1272. "color": s.get("color", ""),
  1273. }
  1274. for s in plate_slots
  1275. ]
  1276. return archive_data
  1277. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1278. """Best-effort filament metadata from the MQTT print-start snapshot.
  1279. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1280. file during print, see #1533) so the fallback PrintArchive still has
  1281. enough filament info to support the inventory views and AMS-expansion
  1282. planning the operator opens it for. Returns a dict with optional
  1283. ``filament_type`` and ``filament_color`` keys in the same
  1284. comma-separated format the 3MF extractor produces, so the rest of the
  1285. codebase treats the fallback archive identically to a normal one.
  1286. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1287. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1288. entries). When supplied, only the slots actually consumed by this
  1289. print contribute. Without it the function falls back to every loaded
  1290. AMS slot — less accurate but still useful.
  1291. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1292. that the unit tests pass directly, AND the on_print_start callback
  1293. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1294. bambu_mqtt service hands to main.py at runtime. The original
  1295. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1296. handled the inner shape and silently returned ``{}`` for every real
  1297. print start, leaving fallback archives' filament fields NULL — the
  1298. exact regression the fix was meant to close. Reported with a log
  1299. proving the AMS state was right there at
  1300. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1301. """
  1302. result: dict[str, str] = {}
  1303. # Look at the on_print_start wrapper first, then the inner shape.
  1304. raw_data = (data or {}).get("raw_data")
  1305. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1306. if not isinstance(ams_root, dict):
  1307. ams_root = (data or {}).get("ams") or {}
  1308. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1309. if not isinstance(ams_units, list) or not ams_units:
  1310. return result
  1311. from backend.app.services.print_scheduler import _global_tray_id
  1312. # Map global tray id → (type, color), addressed as the print's ams_mapping
  1313. # is: unit * 4 + tray, or the bare unit id for an AMS-HT (from 128).
  1314. loaded: dict[int, tuple[str, str]] = {}
  1315. for unit in ams_units:
  1316. if not isinstance(unit, dict):
  1317. continue
  1318. try:
  1319. unit_id = int(unit.get("id", 0))
  1320. except (TypeError, ValueError):
  1321. continue
  1322. for tray in unit.get("tray") or []:
  1323. if not isinstance(tray, dict):
  1324. continue
  1325. try:
  1326. tray_id = int(tray.get("id", 0))
  1327. except (TypeError, ValueError):
  1328. continue
  1329. ttype = (tray.get("tray_type") or "").strip()
  1330. # RRGGBBAA from the printer, stored as the 3MF path stores it:
  1331. # "#RRGGBB" (the Archives page's swatches and colour filter).
  1332. hex_color = (tray.get("tray_color") or "").strip().upper()[:6]
  1333. tcolor = f"#{hex_color}" if re.fullmatch(r"[0-9A-F]{6}", hex_color) else ""
  1334. if not ttype:
  1335. continue # Empty / unloaded slot.
  1336. loaded[_global_tray_id(unit_id, tray_id)] = (ttype, tcolor)
  1337. if not loaded:
  1338. return result
  1339. if ams_mapping:
  1340. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1341. filaments = [loaded[g] for g in used_ids if g in loaded]
  1342. if not filaments:
  1343. return result # Mapping points entirely at slots we have no data for.
  1344. else:
  1345. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1346. types_joined = ",".join(f[0] for f in filaments)
  1347. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1348. # Column limits per backend/app/models/archive.py: filament_type=50,
  1349. # filament_color=200.
  1350. if types_joined:
  1351. result["filament_type"] = types_joined[:50]
  1352. if colors_joined:
  1353. result["filament_color"] = colors_joined[:200]
  1354. return result
  1355. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1356. """Start a layer-timelapse session for *archive_id* when the printer has
  1357. an external camera configured. Returns True if a session was started.
  1358. Three call sites in on_print_start (expected-archive promotion, fallback
  1359. archive creation, fresh-archive creation) used to inline this same
  1360. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1361. on the first pass). Centralising the conditional + call here makes the
  1362. contract testable in isolation and keeps the three sites locked in step.
  1363. """
  1364. if not (printer.external_camera_enabled and printer.external_camera_url):
  1365. return False
  1366. from backend.app.services.layer_timelapse import start_session
  1367. start_session(
  1368. printer_id,
  1369. archive_id,
  1370. printer.external_camera_url,
  1371. printer.external_camera_type or "mjpeg",
  1372. snapshot_url=printer.external_camera_snapshot_url,
  1373. rotation=getattr(printer, "camera_rotation", 0),
  1374. )
  1375. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1376. return True
  1377. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1378. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1379. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1380. — since #2926 — the description the parser already resolved, which is preferred
  1381. when present so the queue's failure reason reads the same as the status
  1382. response. The short code still produces the bracketed label, and still
  1383. resolves the sentence for a caller whose entries predate the field. An entry
  1384. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1385. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1386. label when no description is on file. Returns None for an empty list so
  1387. callers can leave error_message unset.
  1388. """
  1389. if not hms_errors:
  1390. return None
  1391. from backend.app.services.hms_errors import get_error_description
  1392. parts: list[str] = []
  1393. for err in hms_errors:
  1394. try:
  1395. # `_hms_short_code` rather than a local derivation: this one used to
  1396. # format the error without masking it to 16 bits, so an `hms[]` entry
  1397. # whose code carries an alert-level group produced a five-digit label
  1398. # like "0500_3000A" — not a code the user can look up, and never a
  1399. # catalogue key, so the sentence was lost with it.
  1400. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1401. except (TypeError, ValueError):
  1402. continue
  1403. description = err.get("description") or get_error_description(short_code)
  1404. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1405. # groups and is not a code anyone can look up; its full code in the
  1406. # printer screen's four groups is (#2728).
  1407. full_code = str(err.get("full_code") or "")
  1408. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1409. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1410. return "; ".join(parts) if parts else None
  1411. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1412. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1413. print completes successfully. Gated to status=='completed': failed, cancelled
  1414. and aborted prints do not count as usage. Caller is responsible for committing
  1415. the session. No-op when the queue item has no linked library file (e.g. reprints
  1416. from an archive). See #1008."""
  1417. if queue_status != "completed" or item.library_file_id is None:
  1418. return
  1419. from backend.app.models.library import LibraryFile
  1420. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1421. if lib_file is None:
  1422. return
  1423. lib_file.print_count = (lib_file.print_count or 0) + 1
  1424. lib_file.last_printed_at = datetime.now(timezone.utc)
  1425. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1426. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1427. When on_print_complete fires with status 'failed' for a printer in this set we
  1428. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1429. rather than a 'print failed' notification.
  1430. """
  1431. _user_stopped_printers.add(printer_id)
  1432. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1433. _last_status_broadcast: dict[int, str] = {}
  1434. # Track printers where we've updated nozzle_count
  1435. _nozzle_count_updated: set[int] = set()
  1436. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1437. """Wait the debounce window then fire `on_printer_offline` if the printer
  1438. is still offline.
  1439. Scheduled by `on_printer_status_change` on the connected → disconnected
  1440. edge (#1752). Cancelled by the same handler if the printer reconnects
  1441. before the window elapses, so a single MQTT blip + recovery doesn't
  1442. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1443. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1444. route through the same status-change callback, so this covers both.
  1445. """
  1446. logger = logging.getLogger(__name__)
  1447. try:
  1448. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1449. still_offline = not printer_manager.is_connected(printer_id)
  1450. logger.info(
  1451. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1452. printer_id,
  1453. still_offline,
  1454. )
  1455. if not still_offline:
  1456. return
  1457. async with async_session() as db:
  1458. from backend.app.models.printer import Printer
  1459. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1460. printer = result.scalar_one_or_none()
  1461. if not printer:
  1462. logger.warning(
  1463. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1464. printer_id,
  1465. )
  1466. return
  1467. # Recorded only when the relay can publish it, so the reconnect's
  1468. # online event always has an offline before it.
  1469. if mqtt_relay.enabled and mqtt_relay.connected:
  1470. _printer_offline_published.add(printer_id)
  1471. try:
  1472. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1473. except Exception as e:
  1474. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1475. logger.info(
  1476. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1477. printer_id,
  1478. printer.name,
  1479. )
  1480. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1481. except asyncio.CancelledError:
  1482. raise
  1483. except Exception as e:
  1484. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1485. finally:
  1486. _printer_offline_notify_tasks.pop(printer_id, None)
  1487. def _hms_notify_key(error) -> str:
  1488. """What identifies a fault for notification de-duplication.
  1489. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1490. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1491. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1492. and -0006 together) shared a key and only the first was ever notified. An
  1493. entry without a full code falls back to attr and code together.
  1494. """
  1495. full_code = getattr(error, "full_code", "") or ""
  1496. if full_code:
  1497. return full_code.upper()
  1498. return f"{error.attr:08X}:{error.code}"
  1499. def _hms_fault_counts(error) -> bool:
  1500. """Whether a fault counts as a problem: the same rule the frontend's
  1501. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1502. It counts when Bambu publishes text for it or it offers action buttons, and
  1503. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1504. no actions does not count: those are things like "the top cover is open" or
  1505. "the chamber is hot, fan speed increased", which a printer can hold through
  1506. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1507. it always has; those are prompts such as "unable to start drying" (#2728).
  1508. """
  1509. if error.severity < 1:
  1510. return False
  1511. has_actions = bool(getattr(error, "actions", None))
  1512. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1513. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1514. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1515. """The new faults that count (see ``_hms_fault_counts``).
  1516. These go to the MQTT relay; the caller also needs a description before it
  1517. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1518. used to read ``severity >= 2`` when severity held the part byte; on the real
  1519. level that would drop the task-stopping errors (#2728).
  1520. """
  1521. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1522. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1523. """The faults on this printer not notified yet, and record them as notified.
  1524. Tracking is updated before anything is sent, so concurrent status callbacks
  1525. cannot notify the same fault twice. A notified fault is forgotten once it
  1526. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1527. and on is notified once (#3226), while one that clears and comes back much
  1528. later is notified again.
  1529. When ``print_state`` changes (a print resumed, started or finished), every
  1530. fault recorded so far is forgotten the first time it is gone, without the
  1531. wait: a runout fixed before resuming must be notified if it happens again a
  1532. few minutes later, while the printer sits paused. Not only the faults gone
  1533. at the change itself, because the update that flips the state can still
  1534. carry the old fault (a ``print_error`` entry stays until a payload brings
  1535. ``hms``).
  1536. """
  1537. now = time.time()
  1538. current = {_hms_notify_key(e) for e in errors}
  1539. seen = _notified_hms_errors.setdefault(printer_id, {})
  1540. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1541. if print_state is not None:
  1542. print_state = print_state.upper()
  1543. if _hms_print_state.get(printer_id, print_state) != print_state:
  1544. forget_when_gone.update(seen)
  1545. _hms_print_state[printer_id] = print_state
  1546. for key, last_seen in list(seen.items()):
  1547. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1548. del seen[key]
  1549. forget_when_gone.discard(key)
  1550. new = current - seen.keys()
  1551. for key in current:
  1552. seen[key] = now
  1553. if not seen:
  1554. _notified_hms_errors.pop(printer_id, None)
  1555. if not forget_when_gone:
  1556. _hms_forget_when_gone.pop(printer_id, None)
  1557. return _hms_errors_to_notify(errors, new)
  1558. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1559. # "Printing", -1 and 255 are "no stage" (#3211).
  1560. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1561. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1562. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1563. Records it as notified. Called only for a printing state with progress above 0.
  1564. Progress before the first layer is not progress through the print (#3211).
  1565. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1566. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1567. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1568. 75% notification together with Print Started, and since 75 was then on
  1569. record, 25 and 50 could never fire. So nothing counts while the printer
  1570. reports a layer count but has not started layer 1.
  1571. Without a layer count -- a print whose first frame carried no
  1572. ``total_layer_num``, until the pushall that asks for it is answered
  1573. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1574. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1575. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1576. reports neither keeps the old behaviour rather than never notifying.
  1577. """
  1578. if (state.layer_num or 0) < 1:
  1579. if (state.total_layers or 0) > 0:
  1580. return None
  1581. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1582. return None
  1583. progress = state.progress or 0
  1584. current_milestone = 0
  1585. if progress >= 75:
  1586. current_milestone = 75
  1587. elif progress >= 50:
  1588. current_milestone = 50
  1589. elif progress >= 25:
  1590. current_milestone = 25
  1591. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1592. _last_progress_milestone[printer_id] = current_milestone
  1593. return current_milestone
  1594. return None
  1595. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1596. """Handle printer status changes - broadcast via WebSocket."""
  1597. try:
  1598. notify_live_activities.observe(printer_id, state)
  1599. except Exception:
  1600. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1601. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1602. # transitions disconnected → connected — which covers both Bambuddy
  1603. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1604. # `reconcile_stale_active_prints` exactly once for this connection so
  1605. # any archive still in `status="printing"` that can't actually be
  1606. # running anymore (printer IDLE / different subtask / empty subtask)
  1607. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1608. # finished during a disconnect window + a smart-plug power cycle
  1609. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1610. # next boot. Reconciliation runs concurrently — it must not block the
  1611. # WebSocket dedup / broadcast logic below, and the connected edge is
  1612. # marked True BEFORE the await so concurrent status updates inside
  1613. # the same connection don't re-trigger reconciliation.
  1614. #
  1615. # Wait for a real push_status before reconciling (#1679): MQTT
  1616. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1617. # the connection, BEFORE `_request_push_all` round-trips. At that
  1618. # instant the `PrinterState` is still on construction defaults — most
  1619. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1620. # If reconcile spawns here, every in-flight archive falls through to
  1621. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1622. # creates a duplicate archive on the real PRINT COMPLETE and
  1623. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1624. # keeps the #1542 mechanism intact: once the first real push_status
  1625. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1626. # fires again with the flag still False — reconcile then runs against
  1627. # actual evidence.
  1628. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1629. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1630. _printer_reconciled_since_connect[printer_id] = True
  1631. spawn_background_task(
  1632. reconcile_stale_active_prints(printer_id),
  1633. name=f"reconcile-stale-prints-{printer_id}",
  1634. )
  1635. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1636. # Re-arm so the next reconnect triggers reconciliation again.
  1637. _printer_reconciled_since_connect[printer_id] = False
  1638. # Same edge, for the calibration table the AMS card reads its K values from.
  1639. #
  1640. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1641. # tables to ask for. A `state_known` gate alone is not enough: the first
  1642. # real push_status is what makes the state known, and the nozzle fields do
  1643. # not always arrive in it. Latching there would spend this connection's one
  1644. # attempt on a printer that could not yet say what was fitted.
  1645. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1646. if (
  1647. state.connected
  1648. and state_known
  1649. and nozzle_known
  1650. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1651. ):
  1652. _printer_kprofiles_primed_since_connect[printer_id] = True
  1653. spawn_background_task(
  1654. prime_kprofile_table(printer_id),
  1655. name=f"prime-kprofiles-{printer_id}",
  1656. )
  1657. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1658. _printer_kprofiles_primed_since_connect[printer_id] = False
  1659. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1660. # else in the AMS report changing -- a power cycle does it to every slot --
  1661. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1662. # while the printer is idle; needs_check is cheap and throttled per slot.
  1663. # Guarded: nothing here may stop the status broadcast below.
  1664. try:
  1665. if not state.connected:
  1666. kprofile_drift.forget_printer(printer_id)
  1667. elif kprofile_drift.needs_check(printer_id, state):
  1668. spawn_background_task(
  1669. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1670. name=f"reapply-kprofiles-{printer_id}",
  1671. )
  1672. except Exception:
  1673. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1674. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1675. # connected → disconnected. The "back online" channel is already covered
  1676. # by the print-failure notification (firmware reports gcode_state=FAILED
  1677. # on reconnect of an interrupted print), so there is no online
  1678. # notification. The MQTT relay gets both: offline after the debounce, and
  1679. # online on the reconnect that follows a published offline.
  1680. prev_connected = _printer_last_connected.get(printer_id)
  1681. _printer_last_connected[printer_id] = state.connected
  1682. if prev_connected is True and not state.connected:
  1683. existing = _printer_offline_notify_tasks.get(printer_id)
  1684. if existing is None or existing.done():
  1685. logging.getLogger(__name__).info(
  1686. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1687. printer_id,
  1688. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1689. )
  1690. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1691. _maybe_notify_printer_offline(printer_id),
  1692. name=f"printer-offline-notify-{printer_id}",
  1693. )
  1694. elif state.connected:
  1695. # Kept until the relay can actually send online: with its broker down
  1696. # now, the next status update after the reconnect sends it.
  1697. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1698. _printer_offline_published.discard(printer_id)
  1699. printer_info = printer_manager.get_printer(printer_id)
  1700. if printer_info:
  1701. try:
  1702. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1703. except Exception as e:
  1704. logging.getLogger(__name__).warning(
  1705. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1706. )
  1707. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1708. if pending is not None and not pending.done():
  1709. logging.getLogger(__name__).info(
  1710. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1711. printer_id,
  1712. )
  1713. pending.cancel()
  1714. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1715. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1716. temps = state.temperatures or {}
  1717. nozzle_temp = round(temps.get("nozzle", 0))
  1718. bed_temp = round(temps.get("bed", 0))
  1719. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1720. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1721. # Auto-detect dual-nozzle printers from MQTT temperature data
  1722. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1723. _nozzle_count_updated.add(printer_id)
  1724. # Update nozzle_count in database
  1725. async with async_session() as db:
  1726. from backend.app.models.printer import Printer
  1727. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1728. printer = result.scalar_one_or_none()
  1729. if printer and printer.nozzle_count != 2:
  1730. printer.nozzle_count = 2
  1731. await db.commit()
  1732. logging.getLogger(__name__).info(
  1733. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1734. )
  1735. # Include target temps for heating phase detection
  1736. bed_target = round(temps.get("bed_target", 0))
  1737. nozzle_target = round(temps.get("nozzle_target", 0))
  1738. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1739. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1740. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1741. #
  1742. # dry_countdown_stalled rides along because it is the one drying signal the
  1743. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1744. # dry_time stopped moving, so on the frame that flips it every other member
  1745. # of this key is identical and the push would be deduplicated away. Mid-print
  1746. # a temperature would eventually break the tie, but a parked command on an
  1747. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1748. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1749. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1750. ams_dry_key = (
  1751. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1752. if state.raw_data
  1753. else ()
  1754. )
  1755. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1756. #
  1757. # The filament identity fields are here because Configure Slot writes
  1758. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1759. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1760. # matched, this function returned before broadcasting, and the card kept
  1761. # showing the old filament until the 30s fallback poll or a page reload —
  1762. # even though the configure route asks the printer for a fresh pushall and
  1763. # that push does carry the new values. Reset always worked, because it
  1764. # clears tray_type.
  1765. #
  1766. # These fields only change when someone configures a slot or swaps a spool,
  1767. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1768. ams_tray_key = (
  1769. tuple(
  1770. (
  1771. t.get("id"),
  1772. t.get("tray_type", ""),
  1773. t.get("state"),
  1774. t.get("tray_color", ""),
  1775. t.get("tray_info_idx", ""),
  1776. t.get("tray_sub_brands", ""),
  1777. t.get("cali_idx"),
  1778. )
  1779. for a in (state.raw_data.get("ams") or [])
  1780. for t in a.get("tray", [])
  1781. )
  1782. if state.raw_data
  1783. else ()
  1784. )
  1785. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1786. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1787. # in the AMS change-hash (tray fields only, and widening that would fire
  1788. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1789. # screen changed no key at all and the card's inlet badges sat stale until a
  1790. # reload. Like the filament-backup flag, these only move when someone
  1791. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1792. fts_key = (
  1793. state.fila_switch.installed if state.fila_switch else False,
  1794. tuple(sorted(state.ams_switch_inlet.items())),
  1795. # Which hotend holds which slot. Unlike the two above this does move
  1796. # mid-print, on every filament change — but only between discrete slots,
  1797. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1798. # it live: it decides which hotend the Load dialog may offer and whether
  1799. # Unload has anything to act on.
  1800. tuple(
  1801. sorted(
  1802. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1803. # Sort on the extruder id alone: the other members are nullable
  1804. # and comparing None with an int raises.
  1805. key=lambda entry: entry[0],
  1806. )
  1807. ),
  1808. )
  1809. status_key = (
  1810. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1811. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1812. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1813. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1814. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1815. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1816. )
  1817. # Fields that change only when the machine does (a nozzle swap, a firmware
  1818. # update, developer mode) or once per print (its AMS mapping): no traffic,
  1819. # but on an idle printer nothing else moves the key when they change.
  1820. machine_key = (
  1821. tuple((n.nozzle_type, n.nozzle_diameter) for n in (state.nozzles or [])),
  1822. state.firmware_version,
  1823. state.developer_mode,
  1824. tuple(state.print_ams_mapping) if isinstance(state.print_ams_mapping, list) else None,
  1825. # Cooling/heating, switched on the printer's screen too: on an idle
  1826. # printer nothing else moves the key (PSF-4).
  1827. state.airduct_mode,
  1828. )
  1829. status_key = f"{status_key}:{machine_key}"
  1830. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1831. if not is_active_print:
  1832. _unauthorized_print_kill_sent.discard(printer_id)
  1833. elif printer_id in _unauthorized_print_kill_sent:
  1834. # stop_print() was already sent for this print; avoid all further
  1835. # ownership and settings work until the printer leaves an active state.
  1836. pass
  1837. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1838. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1839. _unauthorized_print_kill_sent.discard(printer_id)
  1840. else:
  1841. kill_switch_enabled = False
  1842. authorization: bool | None = None
  1843. status_logger = logging.getLogger(__name__)
  1844. try:
  1845. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1846. if kill_switch_enabled:
  1847. async with async_session() as db:
  1848. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1849. except Exception as e:
  1850. # Fail safe: a database/reconciliation error must never turn into an
  1851. # irreversible stop of a print whose ownership is still unknown.
  1852. authorization = None
  1853. status_logger.warning(
  1854. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1855. )
  1856. if not kill_switch_enabled or authorization is True:
  1857. _unauthorized_print_kill_sent.discard(printer_id)
  1858. elif authorization is None:
  1859. _unauthorized_print_kill_sent.discard(printer_id)
  1860. status_logger.debug(
  1861. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1862. printer_id,
  1863. )
  1864. else:
  1865. try:
  1866. stopped = printer_manager.stop_print(printer_id)
  1867. if stopped:
  1868. _unauthorized_print_kill_sent.add(printer_id)
  1869. _kill_switch_stopped.add(printer_id)
  1870. printer_info = printer_manager.get_printer(printer_id)
  1871. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1872. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1873. notification_data = {
  1874. "status": "stopped",
  1875. "filename": state.gcode_file or state.current_print or "",
  1876. "subtask_name": state.subtask_name or "",
  1877. "progress": state.progress,
  1878. "reason": "unauthorized_print",
  1879. }
  1880. status_logger.warning(
  1881. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1882. printer_id,
  1883. state.state,
  1884. )
  1885. try:
  1886. await ws_manager.broadcast(
  1887. {
  1888. "type": "kill_switch_triggered",
  1889. "printer_id": printer_id,
  1890. "printer_name": printer_name,
  1891. "filename": filename,
  1892. "reason": "unauthorized_print",
  1893. }
  1894. )
  1895. except Exception as e:
  1896. status_logger.warning(
  1897. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1898. )
  1899. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1900. if previous_task is not None and not previous_task.done():
  1901. previous_task.cancel()
  1902. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1903. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1904. name=f"kill-switch-notification-{printer_id}",
  1905. )
  1906. else:
  1907. status_logger.warning(
  1908. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1909. printer_id,
  1910. state.state,
  1911. )
  1912. except Exception as e:
  1913. status_logger.warning(
  1914. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1915. )
  1916. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1917. try:
  1918. printer_info = printer_manager.get_printer(printer_id)
  1919. if printer_info:
  1920. await mqtt_relay.on_printer_status(
  1921. printer_id,
  1922. state,
  1923. printer_info.name,
  1924. printer_info.serial_number,
  1925. printer_manager.is_awaiting_plate_clear(printer_id),
  1926. )
  1927. except Exception:
  1928. pass # Don't fail status callback if MQTT fails
  1929. if _last_status_broadcast.get(printer_id) == status_key:
  1930. return # No change, skip WebSocket broadcast
  1931. _last_status_broadcast[printer_id] = status_key
  1932. # Check for progress milestone notifications (25%, 50%, 75%)
  1933. progress = state.progress or 0
  1934. is_printing = state.state in ("RUNNING", "PRINTING")
  1935. if is_printing and progress > 0:
  1936. current_milestone = _progress_milestone_to_notify(printer_id, state)
  1937. if current_milestone is not None:
  1938. try:
  1939. from backend.app.models.printer import Printer
  1940. # Read the printer in a short session and release the connection
  1941. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1942. # pinned a pooled connection per milestone, per printer (issue #2572).
  1943. async with async_session() as db:
  1944. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1945. printer = result.scalar_one_or_none()
  1946. printer_name = printer.name if printer else f"Printer {printer_id}"
  1947. filename = state.subtask_name or state.gcode_file or "Unknown"
  1948. # remaining_time is in minutes, convert to seconds for notification
  1949. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1950. # Capture camera snapshot for notification image attachment (no DB held).
  1951. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1952. # Notification send needs a session (provider/template lookups).
  1953. async with async_session() as db:
  1954. await notification_service.on_print_progress(
  1955. printer_id,
  1956. printer_name,
  1957. filename,
  1958. current_milestone,
  1959. db,
  1960. remaining_time_seconds,
  1961. image_data=image_data,
  1962. )
  1963. except Exception as e:
  1964. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1965. elif progress < 5:
  1966. # Reset milestone tracking when print restarts or new print begins
  1967. _last_progress_milestone[printer_id] = 0
  1968. _first_layer_notified[printer_id] = False
  1969. # HMS error codes that should not trigger notifications even though they
  1970. # have known descriptions (e.g. user-initiated actions, not real errors).
  1971. _HMS_NOTIFICATION_SUPPRESS = {
  1972. "0500_400E", # Printing was cancelled (user action, not an error)
  1973. }
  1974. # Check for new HMS errors and send notifications
  1975. current_hms_errors = getattr(state, "hms_errors", []) or []
  1976. if current_hms_errors:
  1977. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  1978. if new_errors:
  1979. try:
  1980. from backend.app.models.printer import Printer
  1981. # Read the printer in a short session and release the connection
  1982. # BEFORE the ~15s camera snapshot below (issue #2572).
  1983. async with async_session() as db:
  1984. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1985. printer = result.scalar_one_or_none()
  1986. printer_name = printer.name if printer else f"Printer {printer_id}"
  1987. # Format error details for notification
  1988. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1989. module_names = {
  1990. 0x03: "Print/Task",
  1991. 0x05: "Nozzle/Extruder",
  1992. 0x07: "AMS/Filament",
  1993. 0x0C: "Motion Controller",
  1994. 0x12: "Chamber",
  1995. }
  1996. # Capture camera snapshot once for all error notifications (no DB held).
  1997. error_image_data = await _capture_snapshot_for_notification(
  1998. printer_id, printer, logging.getLogger(__name__)
  1999. )
  2000. # Notification sends need a session (provider/template lookups).
  2001. async with async_session() as db:
  2002. sent_count = 0
  2003. for error in new_errors:
  2004. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  2005. # Build short code like "0700_8010"
  2006. # Mask to 16 bits to handle printers that send larger values
  2007. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  2008. error_code_masked = error_code_int & 0xFFFF
  2009. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  2010. # Only notify for errors Bambu publishes text for — printers
  2011. # send undocumented codes that aren't real errors, and Bambu
  2012. # lists some with empty text. Resolved at parse time (#2926);
  2013. # short_code is still needed for the suppression set below.
  2014. description = error.description
  2015. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  2016. continue
  2017. error_type = f"{module_name} Error"
  2018. error_detail = description
  2019. await notification_service.on_printer_error(
  2020. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  2021. )
  2022. sent_count += 1
  2023. if sent_count:
  2024. logging.getLogger(__name__).info(
  2025. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  2026. )
  2027. # Also publish to MQTT relay (no DB): every new fault that
  2028. # counts, with or without text, the same set the UI counts.
  2029. printer_info = printer_manager.get_printer(printer_id)
  2030. if printer_info:
  2031. errors_data = [
  2032. {
  2033. "code": e.code,
  2034. "attr": e.attr,
  2035. "module": e.module,
  2036. "severity": e.severity,
  2037. }
  2038. for e in new_errors
  2039. ]
  2040. await mqtt_relay.on_printer_error(
  2041. printer_id, printer_info.name, printer_info.serial_number, errors_data
  2042. )
  2043. except Exception as e:
  2044. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  2045. else:
  2046. # No HMS errors: nothing to send, but faults gone long enough (or gone
  2047. # across a print state change) are forgotten. Some codes, e.g. chamber
  2048. # temperature regulation during PETG prints, toggle every few seconds.
  2049. _take_new_hms_faults(printer_id, [], state.state)
  2050. await ws_manager.send_printer_status(
  2051. printer_id,
  2052. printer_state_to_dict(
  2053. state,
  2054. printer_id,
  2055. printer_manager.get_model(printer_id),
  2056. printer_manager.get_drying_targets(printer_id),
  2057. ),
  2058. )
  2059. def _is_bambu_uuid(tray_uuid: str) -> bool:
  2060. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  2061. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  2062. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  2063. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  2064. K-profiles are per-nozzle and the printer's calibration table is numbered
  2065. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  2066. switch's other inlet therefore silently invalidates every configured slot in
  2067. it: the index stays put and now resolves against the other nozzle's table.
  2068. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  2069. and 0.020 on the right kept the left profile after the move, and a manual
  2070. RFID re-read only re-asserted the same wrong one.
  2071. Configuring a slot is a deliberate preparation step, so this re-selects
  2072. rather than re-configures: only the calibration binding moves, and only for
  2073. slots whose spool already has a stored profile for the new nozzle. A slot
  2074. Bambuddy knows nothing about is left exactly as the operator left it.
  2075. """
  2076. logger = logging.getLogger(__name__)
  2077. target_extruder = extruder_for_inlet(inlet)
  2078. if target_extruder is None:
  2079. return
  2080. client = printer_manager.get_client(printer_id)
  2081. state = printer_manager.get_status(printer_id)
  2082. if not client or not state or not state.raw_data:
  2083. return
  2084. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  2085. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  2086. # the nozzle width, which changes both the K profile to select and the
  2087. # preset the slot should carry.
  2088. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  2089. ams_raw = state.raw_data.get("ams")
  2090. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2091. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  2092. if not unit:
  2093. return
  2094. try:
  2095. async with async_session() as db:
  2096. for tray in unit.get("tray", []):
  2097. tray_id = int(tray.get("id", -1))
  2098. if tray_id < 0 or not tray.get("tray_type"):
  2099. continue
  2100. current_idx = tray.get("cali_idx")
  2101. profile = await find_slot_kprofile_for_extruder(
  2102. db,
  2103. printer_id,
  2104. ams_id,
  2105. tray_id,
  2106. target_extruder,
  2107. nozzle_diameter,
  2108. printer_manager.get_model(printer_id),
  2109. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2110. )
  2111. if profile is None or profile.cali_idx is None:
  2112. continue
  2113. if current_idx == profile.cali_idx:
  2114. continue # Already on the right one.
  2115. logger.info(
  2116. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2117. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2118. printer_id,
  2119. ams_id,
  2120. tray_id,
  2121. inlet,
  2122. target_extruder,
  2123. profile.name,
  2124. current_idx,
  2125. profile.cali_idx,
  2126. profile.k_value,
  2127. )
  2128. client.extrusion_cali_sel(
  2129. ams_id=ams_id,
  2130. tray_id=tray_id,
  2131. cali_idx=profile.cali_idx,
  2132. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2133. nozzle_diameter=nozzle_diameter,
  2134. )
  2135. except Exception as e:
  2136. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2137. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2138. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2139. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2140. from the delayed re-check -- which is why it takes the AMS data and print
  2141. state as arguments instead of reading them from the push (#3186).
  2142. """
  2143. logger = logging.getLogger(__name__)
  2144. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2145. # Auto-unlink spool assignments with stale fingerprints. Under the
  2146. # per-printer assignment lock since #3186: the held-removal re-check runs
  2147. # this outside any MQTT push, so it can now overlap one.
  2148. try:
  2149. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2150. from sqlalchemy.orm import selectinload
  2151. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2152. from backend.app.models.spool import Spool as _Spool
  2153. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2154. from backend.app.services.ams_slot_presence import spool_present
  2155. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2156. # Built-in assignments only. Since #2812 they survive a switch to
  2157. # Spoolman mode rather than being deleted by it, and this pass ends
  2158. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2159. # time as the AMS contents changed under the other mode, undoing the
  2160. # preservation more slowly but just as completely.
  2161. assignments = []
  2162. if not await spoolman_owns_assignments(db):
  2163. result = await db.execute(
  2164. select(SA)
  2165. .where(SA.printer_id == printer_id)
  2166. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2167. )
  2168. assignments = result.scalars().all()
  2169. # ``printing_now`` (top of this function) keeps a runout from
  2170. # unlinking the spool that fed the print — the next idle-time pass
  2171. # unlinks it if the user really did take it out.
  2172. stale = []
  2173. # Removals this pass is holding rather than unlinking (#3186).
  2174. held: set[tuple] = set()
  2175. for assignment in assignments:
  2176. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2177. if assignment.ams_id == 255:
  2178. ps = printer_manager.get_status(printer_id)
  2179. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2180. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2181. current_tray = None
  2182. for vt in vt_tray_raw:
  2183. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2184. current_tray = vt
  2185. break
  2186. if not current_tray:
  2187. # vt_tray data may not have arrived yet — keep assignment
  2188. continue
  2189. else:
  2190. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2191. if not current_tray:
  2192. if printing_now:
  2193. logger.info(
  2194. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2195. assignment.spool_id,
  2196. assignment.ams_id,
  2197. assignment.tray_id,
  2198. )
  2199. continue
  2200. # A whole AMS unit can drop out of one push and come back in
  2201. # the next; only a slot that stays gone is a removal (#3186).
  2202. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2203. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2204. held.add(hold_key)
  2205. logger.info(
  2206. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2207. "unlinking if it is still gone in %ds",
  2208. assignment.spool_id,
  2209. assignment.ams_id,
  2210. assignment.tray_id,
  2211. int(slot_unlink_grace.GRACE_SECONDS),
  2212. )
  2213. continue
  2214. logger.info(
  2215. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2216. assignment.spool_id,
  2217. assignment.ams_id,
  2218. assignment.tray_id,
  2219. )
  2220. stale.append(assignment) # Slot empty
  2221. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2222. # A Bambu Lab spool is in this slot — check if it's the same spool
  2223. # that's currently assigned. If yes, keep the assignment (avoids
  2224. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2225. # the printer's filament preset on every startup).
  2226. tray_uuid = current_tray.get("tray_uuid", "")
  2227. tag_uid = current_tray.get("tag_uid", "")
  2228. spool = assignment.spool
  2229. spool_matches = False
  2230. if spool:
  2231. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2232. spool.tag_uid
  2233. and tag_uid
  2234. and tag_uid != "0000000000000000"
  2235. and spool.tag_uid.upper() == tag_uid.upper()
  2236. ):
  2237. spool_matches = True
  2238. if spool_matches:
  2239. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2240. cur_color = current_tray.get("tray_color", "")
  2241. cur_type = current_tray.get("tray_type", "")
  2242. fp_color = assignment.fingerprint_color or ""
  2243. fp_type = assignment.fingerprint_type or ""
  2244. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2245. assignment.fingerprint_color = cur_color
  2246. assignment.fingerprint_type = cur_type
  2247. logger.debug(
  2248. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2249. assignment.spool_id,
  2250. assignment.ams_id,
  2251. assignment.tray_id,
  2252. )
  2253. continue
  2254. # Different BL spool or unrecognized — unlink so auto-assign can match
  2255. logger.info(
  2256. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2257. assignment.spool_id,
  2258. assignment.ams_id,
  2259. assignment.tray_id,
  2260. tray_uuid,
  2261. )
  2262. stale.append(assignment)
  2263. else:
  2264. cur_color = current_tray.get("tray_color", "")
  2265. cur_type = current_tray.get("tray_type", "")
  2266. cur_state = current_tray.get("state")
  2267. fp_color = assignment.fingerprint_color or ""
  2268. fp_type = assignment.fingerprint_type or ""
  2269. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2270. # the slot was empty when the user pre-assigned via SpoolBuddy
  2271. # (the firmware drops ams_filament_setting on empty slots, so
  2272. # MQTT was deferred). The moment any filament gets inserted
  2273. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2274. # reconfigured spool — fire the deferred configuration.
  2275. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2276. # extruder" code) OR, on firmwares that don't use the state
  2277. # enum meaningfully, a non-empty tray_type when state is
  2278. # NOT one of the firmware's explicit empty signals (9, 10).
  2279. # state-only was wrong for firmwares that never set 11 — A1
  2280. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2281. # always report state=3 — so the replay never fired for them
  2282. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2283. # explicit "empty" signals authoritative over any stale
  2284. # tray_type that might survive the relay's auto-clearing.
  2285. #
  2286. # tray_exist_bits comes first because that guard cannot tell
  2287. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2288. # writes state=9 when the bit is 0 and leaves it there when the
  2289. # bit returns. A non-RFID spool inserted into a pre-assigned
  2290. # slot brings no tray_type with it, so the stale 9 made this
  2291. # expression false forever and the deferred config never fired
  2292. # — the deadlock #1322 removed from the assign path, still in
  2293. # place here (#3084, #3100).
  2294. loaded = spool_present(current_tray) is True or (
  2295. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2296. )
  2297. if not fp_type.strip() and loaded and assignment.spool:
  2298. # The fingerprint ends this replay. Not recorded when nothing
  2299. # could be sent (no MQTT client while the printer reconnects),
  2300. # so the next AMS change tries again. An attempt that raised is
  2301. # recorded as before: it may have sent part of the commands and
  2302. # would raise again on every change, remain% steps included.
  2303. configured: bool | None = False
  2304. try:
  2305. from backend.app.api.routes.inventory import (
  2306. apply_spool_to_slot_via_mqtt,
  2307. )
  2308. configured = await apply_spool_to_slot_via_mqtt(
  2309. db=db,
  2310. current_user=None,
  2311. spool=assignment.spool,
  2312. printer_id=printer_id,
  2313. ams_id=assignment.ams_id,
  2314. tray_id=assignment.tray_id,
  2315. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2316. current_tray_type=cur_type,
  2317. current_tray_sub_brands=current_tray.get("tray_sub_brands", ""),
  2318. )
  2319. except Exception:
  2320. logger.exception(
  2321. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2322. assignment.spool_id,
  2323. printer_id,
  2324. assignment.ams_id,
  2325. assignment.tray_id,
  2326. )
  2327. configured = None
  2328. if configured is False:
  2329. logger.warning(
  2330. "Pre-config not sent for spool %d on printer %d AMS%d-T%d (no MQTT client); "
  2331. "retrying on the next AMS change",
  2332. assignment.spool_id,
  2333. printer_id,
  2334. assignment.ams_id,
  2335. assignment.tray_id,
  2336. )
  2337. else:
  2338. if configured:
  2339. logger.info(
  2340. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2341. assignment.spool_id,
  2342. printer_id,
  2343. assignment.ams_id,
  2344. assignment.tray_id,
  2345. )
  2346. assignment.fingerprint_color = cur_color
  2347. assignment.fingerprint_type = cur_type
  2348. continue
  2349. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2350. # Blank tray data mid-print is a runout, not a swap: the
  2351. # firmware clears colour and type when it unloads a spool
  2352. # it just emptied. Unlinking here would erase the record
  2353. # of which spool fed the print so far.
  2354. if printing_now and not cur_color.strip() and not cur_type.strip():
  2355. logger.info(
  2356. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2357. "(runout?)",
  2358. assignment.spool_id,
  2359. assignment.ams_id,
  2360. assignment.tray_id,
  2361. )
  2362. continue
  2363. # Same reasoning off the print, on firmware's own say-so:
  2364. # a blank tray report from a slot whose tray_exist_bits
  2365. # bit is set describes a spool the AMS cannot identify —
  2366. # a non-RFID one, or one whose slot was reset — not a
  2367. # spool that was taken out. Deleting the assignment there
  2368. # threw away the identity the user had supplied, which is
  2369. # the only place it existed (#3100). A slot the bit calls
  2370. # empty, or one that carries no bit at all, still unlinks.
  2371. #
  2372. # Unless the slot was reported empty first: a removal
  2373. # already held means a spool came out and another went
  2374. # in, so the blank report keeps the hold running below
  2375. # rather than cancelling it (#3186).
  2376. if (
  2377. spool_present(current_tray) is True
  2378. and not cur_color.strip()
  2379. and not cur_type.strip()
  2380. and not slot_unlink_grace.is_held(
  2381. printer_id,
  2382. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2383. )
  2384. ):
  2385. logger.info(
  2386. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2387. "tray reports no filament data yet",
  2388. assignment.spool_id,
  2389. assignment.ams_id,
  2390. assignment.tray_id,
  2391. )
  2392. continue
  2393. # A blank report the presence bit does not vouch for is
  2394. # still only one push. An idle X1C cleared a whole AMS
  2395. # unit's bits, colour and type for a moment and lost
  2396. # four saved assignments that way (#3186); unlink only
  2397. # if the slot is still blank after the grace period.
  2398. if not cur_color.strip() and not cur_type.strip():
  2399. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2400. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2401. held.add(hold_key)
  2402. logger.info(
  2403. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2404. "unlinking if it is still blank in %ds",
  2405. assignment.spool_id,
  2406. assignment.ams_id,
  2407. assignment.tray_id,
  2408. int(slot_unlink_grace.GRACE_SECONDS),
  2409. )
  2410. continue
  2411. # Fingerprint mismatch — but check if tray now matches the
  2412. # assigned spool (e.g. auto-configure changed the tray).
  2413. # Both sides are reduced to the type the slot can carry
  2414. # before comparing: the assign path writes that rather
  2415. # than the spool's raw material (#2902), so a spool whose
  2416. # material is a product line — "PLA+", "HTPLA" — reports
  2417. # back as "PLA" and would otherwise fail this check and
  2418. # be auto-unlinked from the slot it was just assigned to.
  2419. # Reducing the printer's side too keeps slots configured
  2420. # by an older Bambuddy, still reporting "PLA+", matching.
  2421. spool = assignment.spool
  2422. if spool:
  2423. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2424. # Two ways the assign path can have arrived at the
  2425. # slot's type, so both count as "we wrote this".
  2426. # The material column is one; the spool's preset is
  2427. # the other, and it outranks the material when the
  2428. # spool has one -- a spool whose material says PLA
  2429. # and whose preset is "Bambu PLA Aero" puts
  2430. # PLA-AERO in the slot (#2902). Read from the stored
  2431. # preset name rather than resolving the preset,
  2432. # because this runs on every AMS push and a cloud
  2433. # lookup here would be both slow and unavailable on
  2434. # the unauthenticated replay path.
  2435. spool_types = {printer_filament_type(spool.material).upper()}
  2436. if spool.slicer_filament_name:
  2437. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2438. # An imported local preset stores its type outright,
  2439. # which is what the assign path used -- and the name
  2440. # above may be unset. One keyed read, and only on a
  2441. # mismatch, which is rare.
  2442. #
  2443. # slicer_filament is free text up to fifty characters,
  2444. # so the digits have to be checked against the range
  2445. # of the integer primary key they are about to be
  2446. # compared with. Postgres raises on an out-of-range
  2447. # integer rather than simply not matching, and that
  2448. # would poison this session and abandon the rest of
  2449. # the cleanup pass.
  2450. lp_ref = (spool.slicer_filament or "").strip()
  2451. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2452. from backend.app.models.local_preset import LocalPreset as _LP
  2453. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2454. if lp_type:
  2455. spool_types.add(printer_filament_type(lp_type).upper())
  2456. if (
  2457. _colors_similar(cur_color, spool_color)
  2458. and printer_filament_type(cur_type).upper() in spool_types
  2459. ):
  2460. logger.info(
  2461. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2462. assignment.spool_id,
  2463. assignment.ams_id,
  2464. assignment.tray_id,
  2465. )
  2466. assignment.fingerprint_color = cur_color
  2467. assignment.fingerprint_type = cur_type
  2468. continue
  2469. logger.info(
  2470. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2471. assignment.spool_id,
  2472. assignment.ams_id,
  2473. assignment.tray_id,
  2474. cur_color,
  2475. cur_type,
  2476. fp_color,
  2477. fp_type,
  2478. spool.rgba if spool else "?",
  2479. spool.material if spool else "?",
  2480. )
  2481. stale.append(assignment) # Spool changed
  2482. slot_unlink_grace.settle(printer_id, "inventory", held)
  2483. # Snapshot slots before delete — ORM attribute access after the
  2484. # commit would refresh against a deleted row.
  2485. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2486. for a in stale:
  2487. await db.delete(a)
  2488. if stale:
  2489. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2490. # Commit any changes (stale deletions and/or fingerprint updates)
  2491. await db.commit()
  2492. # Tell open browsers the assignment is gone (#2575). Only the manual
  2493. # REST assign/unassign endpoints broadcast this event; without it the
  2494. # frontend's spool-assignments cache keeps rendering the unlinked
  2495. # spool on the slot until an unrelated refetch — which reads exactly
  2496. # like "the fix didn't work" (reporter verified: a browser refresh
  2497. # after the swap showed the correct state all along).
  2498. for ams_id, tray_id in unlinked_slots:
  2499. await ws_manager.broadcast(
  2500. {
  2501. "type": "spool_assignment_changed",
  2502. "printer_id": printer_id,
  2503. "ams_id": ams_id,
  2504. "tray_id": tray_id,
  2505. }
  2506. )
  2507. except Exception as e:
  2508. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2509. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2510. """Delete Spoolman slot rows whose held removal has run its grace period.
  2511. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2512. talks to Spoolman for every tray; this only needs the local rows, so it
  2513. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2514. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2515. not in a slot the presence bit calls occupied -- and nothing else.
  2516. """
  2517. logger = logging.getLogger(__name__)
  2518. try:
  2519. async with async_session() as db:
  2520. from backend.app.api.routes.settings import get_setting
  2521. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2522. from backend.app.services.ams_slot_presence import spool_present
  2523. enabled = await get_setting(db, "spoolman_enabled")
  2524. if not enabled or enabled.lower() != "true":
  2525. return
  2526. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2527. if sync_mode and sync_mode != "auto":
  2528. return
  2529. trays: dict[tuple[int, int], dict] = {}
  2530. for ams_unit in ams_data or []:
  2531. if not isinstance(ams_unit, dict):
  2532. continue
  2533. for tray in ams_unit.get("tray", []):
  2534. if isinstance(tray, dict):
  2535. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2536. rows = (
  2537. (
  2538. await db.execute(
  2539. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2540. )
  2541. )
  2542. .scalars()
  2543. .all()
  2544. )
  2545. held: set[tuple] = set()
  2546. expired: list[tuple[int, int]] = []
  2547. for row in rows:
  2548. tray = trays.get((row.ams_id, row.tray_id))
  2549. if tray is None or printing_now:
  2550. continue
  2551. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2552. continue
  2553. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2554. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2555. continue
  2556. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2557. expired.append((row.ams_id, row.tray_id))
  2558. else:
  2559. held.add(hold_key)
  2560. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2561. if not expired:
  2562. return
  2563. # A statement rather than ORM deletes, like the sync pass: the two
  2564. # can overlap, and a row the other already removed must not fail
  2565. # this commit.
  2566. for ams_id, tray_id in expired:
  2567. await db.execute(
  2568. delete(SpoolmanSlotAssignment).where(
  2569. SpoolmanSlotAssignment.printer_id == printer_id,
  2570. SpoolmanSlotAssignment.ams_id == ams_id,
  2571. SpoolmanSlotAssignment.tray_id == tray_id,
  2572. )
  2573. )
  2574. await db.commit()
  2575. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2576. for ams_id, tray_id in expired:
  2577. await ws_manager.broadcast(
  2578. {
  2579. "type": "spool_assignment_changed",
  2580. "printer_id": printer_id,
  2581. "ams_id": ams_id,
  2582. "tray_id": tray_id,
  2583. }
  2584. )
  2585. except Exception as e:
  2586. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2587. async def _recheck_held_unlinks(printer_id: int) -> None:
  2588. """Re-run just the slot cleanup against the printer's current AMS state.
  2589. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2590. passes otherwise run only when the AMS hash changes, and a slot that went
  2591. empty and stayed empty may never change it again.
  2592. """
  2593. status = printer_manager.get_status(printer_id)
  2594. # A disconnected printer's state is its last report, not a new one: acting
  2595. # on it would "confirm" a removal nobody has seen for the whole grace
  2596. # period. Leave the holds; the first push after reconnecting decides.
  2597. if status is None or not status.connected:
  2598. return
  2599. ams_raw = status.raw_data.get("ams")
  2600. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2601. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2602. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2603. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2604. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2605. async def on_ams_change(printer_id: int, ams_data: list):
  2606. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2607. logger = logging.getLogger(__name__)
  2608. # Snapshot BEFORE any await: if a print is active, or a finished one is
  2609. # still being charged, skip weight sync later. on_print_complete may pop
  2610. # _active_sessions during our awaits (#880).
  2611. from backend.app.services.usage_tracker import printer_is_charging
  2612. _print_active = printer_is_charging(printer_id)
  2613. # A slot that reports empty while a print is running is a filament runout,
  2614. # not a spool swap: the spool is still physically in the AMS, just
  2615. # consumed. Dropping either inventory backend's slot link there loses the
  2616. # only record of which spool fed the print, so the completion path can't
  2617. # charge the runout segment to anything. Both cleanup passes below consult
  2618. # this; computed once, up front, so neither depends on the other having run.
  2619. _unlink_state = printer_manager.get_status(printer_id)
  2620. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2621. # The session alone is not enough: a restart that finds a stale persisted
  2622. # session registers none for the print that is running.
  2623. _print_active = _print_active or printing_now
  2624. # MQTT relay - publish AMS change
  2625. try:
  2626. printer_info = printer_manager.get_printer(printer_id)
  2627. if printer_info:
  2628. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2629. except Exception:
  2630. pass # Don't fail AMS callback if MQTT fails
  2631. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2632. # This ensures frontend gets immediate updates when AMS slots are configured
  2633. try:
  2634. state = printer_manager.get_status(printer_id)
  2635. if state:
  2636. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2637. await ws_manager.send_printer_status(
  2638. printer_id,
  2639. printer_state_to_dict(
  2640. state,
  2641. printer_id,
  2642. printer_manager.get_model(printer_id),
  2643. printer_manager.get_drying_targets(printer_id),
  2644. ),
  2645. )
  2646. except Exception as e:
  2647. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2648. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2649. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2650. # Serialised per-printer via services/ams_assignment_lock: MQTT bursts can deliver
  2651. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2652. # "no existing assignment" for the same (printer, ams, tray) and race to
  2653. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2654. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2655. # bug stayed latent there. See services/ams_assignment_lock for details.
  2656. try:
  2657. async with get_ams_assignment_lock(printer_id), async_session() as db:
  2658. from sqlalchemy.orm import selectinload
  2659. from backend.app.api.routes.settings import get_setting
  2660. from backend.app.models.spool import Spool
  2661. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2662. from backend.app.services.spool_tag_matcher import (
  2663. auto_assign_spool,
  2664. create_spool_from_tray,
  2665. find_matching_untagged_spool,
  2666. get_spool_by_tag,
  2667. is_bambu_tag,
  2668. is_valid_tag,
  2669. link_tag_to_inventory_spool,
  2670. tag_belongs_to_archived_spool,
  2671. )
  2672. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2673. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2674. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2675. if not _spoolman_on or _spoolman_on.lower() != "true":
  2676. for ams_unit in ams_data:
  2677. if not isinstance(ams_unit, dict):
  2678. continue
  2679. ams_id = int(ams_unit.get("id", 0))
  2680. for tray in ams_unit.get("tray", []):
  2681. if not isinstance(tray, dict):
  2682. continue
  2683. tray_id = int(tray.get("id", 0))
  2684. tag_uid = tray.get("tag_uid", "")
  2685. tray_uuid = tray.get("tray_uuid", "")
  2686. tray_info_idx = tray.get("tray_info_idx", "")
  2687. if not tray.get("tray_type"):
  2688. # Slot reported empty — drop any cached unknown-tag
  2689. # broadcast so reinserting the same spool re-prompts.
  2690. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2691. continue # Empty slot
  2692. # Check if assignment already exists for this slot
  2693. existing = await db.execute(
  2694. select(SA)
  2695. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2696. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2697. )
  2698. existing_assignment = existing.scalar_one_or_none()
  2699. if existing_assignment:
  2700. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2701. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2702. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2703. # Skip during active prints: the usage tracker handles deduction
  2704. # precisely via 3MF data on print completion. Without this guard the
  2705. # AMS remain% SET and the usage tracker ADD both fire from the same
  2706. # MQTT message, doubling the deduction (#880).
  2707. if _print_active:
  2708. continue
  2709. remain_raw = tray.get("remain")
  2710. if (
  2711. remain_raw is not None
  2712. and existing_assignment.spool
  2713. and not existing_assignment.spool.weight_locked
  2714. ):
  2715. try:
  2716. remain_val = int(remain_raw)
  2717. except (TypeError, ValueError):
  2718. remain_val = -1
  2719. if 1 <= remain_val <= 100:
  2720. lw = existing_assignment.spool.label_weight or 1000
  2721. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2722. current_used = existing_assignment.spool.weight_used or 0
  2723. if new_used > current_used + 1:
  2724. # Rechecked in the statement: the spool was loaded
  2725. # before this, and a weight set by hand (or weighed)
  2726. # and locked since then must stay (WL-6).
  2727. result = cast(
  2728. CursorResult,
  2729. await db.execute(
  2730. update(Spool)
  2731. .where(
  2732. Spool.id == existing_assignment.spool_id,
  2733. Spool.weight_locked.is_not(True),
  2734. func.coalesce(Spool.weight_used, 0) < new_used - 1,
  2735. )
  2736. .values(weight_used=new_used)
  2737. ),
  2738. )
  2739. await db.commit()
  2740. if result.rowcount:
  2741. logger.info(
  2742. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2743. existing_assignment.spool_id,
  2744. current_used,
  2745. new_used,
  2746. remain_val,
  2747. )
  2748. await ws_manager.broadcast({"type": "inventory_changed"})
  2749. # A K-profile the slot lost (the default K after a reset or
  2750. # power cycle) is put back by kprofile_drift on the next idle
  2751. # push; a different real profile was picked on purpose and
  2752. # stays (#3219, item 44).
  2753. continue
  2754. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2755. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2756. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2757. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  2758. # An archived spool still in the AMS: the slot
  2759. # stays free rather than adopting its tag.
  2760. continue
  2761. if not spool:
  2762. # Try matching an untagged inventory spool (same material/color)
  2763. spool = await find_matching_untagged_spool(db, tray)
  2764. if spool:
  2765. await link_tag_to_inventory_spool(db, spool, tray)
  2766. elif _auto_add_unknown:
  2767. spool = await create_spool_from_tray(db, tray)
  2768. else:
  2769. # Auto-add disabled: surface the slot so the
  2770. # user can add it manually via the UI.
  2771. await _broadcast_unknown_tag(
  2772. printer_id=printer_id,
  2773. ams_id=ams_id,
  2774. tray_id=tray_id,
  2775. tag_uid=tag_uid,
  2776. tray_uuid=tray_uuid,
  2777. tray_type=tray.get("tray_type"),
  2778. tray_color=tray.get("tray_color"),
  2779. tray_sub_brands=tray.get("tray_sub_brands"),
  2780. tray_count=len(ams_unit.get("tray", [])),
  2781. )
  2782. continue
  2783. # Slot matched (existing tag, untagged inventory
  2784. # match, or freshly auto-created spool) — drop any
  2785. # stale dedup so a future tag swap re-prompts.
  2786. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2787. await auto_assign_spool(
  2788. printer_id,
  2789. ams_id,
  2790. tray_id,
  2791. spool,
  2792. printer_manager,
  2793. db,
  2794. tray_info_idx=tray_info_idx,
  2795. )
  2796. await db.commit()
  2797. await ws_manager.broadcast(
  2798. {
  2799. "type": "spool_auto_assigned",
  2800. "printer_id": printer_id,
  2801. "ams_id": ams_id,
  2802. "tray_id": tray_id,
  2803. "spool_id": spool.id,
  2804. }
  2805. )
  2806. logger.info(
  2807. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2808. spool.id,
  2809. printer_id,
  2810. ams_id,
  2811. tray_id,
  2812. )
  2813. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  2814. db, tag_uid, tray_uuid
  2815. ):
  2816. # Non-BL spool with some tag — let user choose (not
  2817. # an archived one's, whose slot stays free)
  2818. await _broadcast_unknown_tag(
  2819. printer_id=printer_id,
  2820. ams_id=ams_id,
  2821. tray_id=tray_id,
  2822. tag_uid=tag_uid,
  2823. tray_uuid=tray_uuid,
  2824. tray_type=tray.get("tray_type"),
  2825. tray_color=tray.get("tray_color"),
  2826. tray_sub_brands=tray.get("tray_sub_brands"),
  2827. tray_count=len(ams_unit.get("tray", [])),
  2828. )
  2829. # No-tag slots (generic non-RFID filament) are left alone:
  2830. # nothing to identify, prompting "+ Add" would just create
  2831. # ghost spools with empty tags on every confirm.
  2832. except Exception as e:
  2833. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2834. try:
  2835. async with async_session() as db:
  2836. from backend.app.api.routes.settings import get_setting
  2837. from backend.app.models.printer import Printer
  2838. # Check if Spoolman is enabled
  2839. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2840. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2841. return
  2842. # Check sync mode
  2843. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2844. if sync_mode and sync_mode != "auto":
  2845. return # Only sync on auto mode
  2846. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2847. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2848. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2849. # always owned by per-print tracking, never by AMS auto-sync. The
  2850. # setting is still read by the settings UI for backwards compat but
  2851. # has no effect on the sync path here.
  2852. # Get Spoolman URL
  2853. spoolman_url = await get_setting(db, "spoolman_url")
  2854. if not spoolman_url:
  2855. return
  2856. # Get or create Spoolman client
  2857. client = await get_spoolman_client()
  2858. if not client:
  2859. try:
  2860. client = await init_spoolman_client(spoolman_url)
  2861. except ValueError as exc:
  2862. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2863. return
  2864. # Check if Spoolman is reachable
  2865. if not await client.health_check():
  2866. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2867. return
  2868. # Get printer name for location
  2869. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2870. printer = result.scalar_one_or_none()
  2871. printer_name = printer.name if printer else f"Printer {printer_id}"
  2872. # OPTIMIZATION: Fetch all spools once before processing trays
  2873. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2874. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2875. try:
  2876. cached_spools = await client.get_spools()
  2877. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2878. except Exception as e:
  2879. logger.error(
  2880. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2881. printer_id,
  2882. e,
  2883. )
  2884. return
  2885. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2886. from sqlalchemy.orm import selectinload
  2887. from backend.app.models.spool_assignment import SpoolAssignment
  2888. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2889. from backend.app.services.ams_slot_presence import spool_present
  2890. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2891. # Built-in remaining weight, used by sync_ams_tray only when the
  2892. # firmware reports an unusable remain%/tray_weight for a slot.
  2893. #
  2894. # Left empty since #2812. This block runs in Spoolman mode only,
  2895. # and until then the built-in table was emptied on the switch, so
  2896. # there was never anything here to read and the fallback was inert.
  2897. # Preserving those rows makes it live again, and it is keyed by slot
  2898. # rather than by spool: after a mode switch the tray may well hold
  2899. # different filament, and ``create_spool`` writes ``remaining_weight``
  2900. # unconditionally, so a stale figure would be seeded into a brand new
  2901. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2902. # intent survives for whoever revisits the cross-mode fallback.
  2903. inventory_weights: dict[tuple[int, int], float] = {}
  2904. if not await spoolman_owns_assignments(db):
  2905. try:
  2906. assign_result = await db.execute(
  2907. select(SpoolAssignment)
  2908. .options(selectinload(SpoolAssignment.spool))
  2909. .where(SpoolAssignment.printer_id == printer_id)
  2910. )
  2911. for assignment in assign_result.scalars().all():
  2912. spool = assignment.spool
  2913. if spool and spool.label_weight > 0:
  2914. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2915. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2916. except Exception as e:
  2917. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2918. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2919. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2920. slot_map_read = False
  2921. try:
  2922. slot_result = await db.execute(
  2923. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2924. )
  2925. for slot in slot_result.scalars().all():
  2926. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2927. slot_map_read = True
  2928. except Exception as e:
  2929. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2930. # Sync each AMS tray and collect slot changes for DB persistence
  2931. synced = 0
  2932. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2933. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2934. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  2935. for ams_unit in ams_data:
  2936. if not isinstance(ams_unit, dict):
  2937. continue
  2938. ams_id = int(ams_unit.get("id", 0))
  2939. trays = ams_unit.get("tray", [])
  2940. for tray_data in trays:
  2941. if not isinstance(tray_data, dict):
  2942. continue
  2943. tray_id_raw = int(tray_data.get("id", 0))
  2944. tray = client.parse_ams_tray(ams_id, tray_data)
  2945. if not tray:
  2946. # Empty tray slot — record for local assignment cleanup
  2947. # and drop any cached unknown-tag broadcast so a
  2948. # reinserted spool re-prompts.
  2949. #
  2950. # Not during a running print: a slot that empties there
  2951. # is a filament runout, and the spool is still in the
  2952. # AMS. `spoolman_slot_assignments` is how a tag-less
  2953. # spool assigned through the Bambuddy UI is resolved at
  2954. # completion (#1459), so deleting the row mid-print
  2955. # loses the runout segment's usage — the same failure
  2956. # the internal inventory's auto-unlink had.
  2957. #
  2958. # Nor when firmware's presence bit says the slot is
  2959. # occupied. parse_ams_tray calls a tray with no type or
  2960. # no colour empty, and a spool the AMS cannot read has
  2961. # neither until something configures it — so a tag-less
  2962. # spool assigned through the UI had its row deleted by
  2963. # the first idle push after it was inserted. Same
  2964. # deletion as the internal inventory's in #3100, same
  2965. # answer, so the two modes stay in step.
  2966. #
  2967. # And only once the slot has stayed empty for the grace
  2968. # period -- the internal inventory's #3186 answer, for
  2969. # the same one-push blank.
  2970. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  2971. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  2972. if not printing_now and (
  2973. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  2974. ):
  2975. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2976. empty_slots.append((ams_id, tray_id_raw))
  2977. else:
  2978. spoolman_held.add(hold_key)
  2979. logger.info(
  2980. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  2981. "unlinking if it is still empty in %ds",
  2982. ams_id,
  2983. tray_id_raw,
  2984. linked_spool,
  2985. int(slot_unlink_grace.GRACE_SECONDS),
  2986. )
  2987. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2988. continue
  2989. spool_tag = (
  2990. tray.tray_uuid
  2991. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2992. else tray.tag_uid
  2993. )
  2994. # Provide the hint only when no RFID is available
  2995. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2996. try:
  2997. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2998. result = await client.sync_ams_tray(
  2999. tray,
  3000. printer_name,
  3001. db,
  3002. # Per-print tracking is the only weight writer (#1119).
  3003. # AMS auto-sync still maintains spool metadata / slot
  3004. # assignments but no longer touches remaining_weight.
  3005. disable_weight_sync=True,
  3006. cached_spools=cached_spools,
  3007. inventory_remaining=inv_remaining,
  3008. spoolman_spool_id_hint=hint,
  3009. auto_add_unknown_rfid=auto_add_unknown_rfid,
  3010. )
  3011. if result is None and spool_tag and not auto_add_unknown_rfid:
  3012. # Spoolman skipped auto-create per user setting — surface
  3013. # the slot so the UI can offer "+ Add to inventory".
  3014. await _broadcast_unknown_tag(
  3015. printer_id=printer_id,
  3016. ams_id=ams_id,
  3017. tray_id=tray.tray_id,
  3018. tag_uid=tray.tag_uid or "",
  3019. tray_uuid=tray.tray_uuid or "",
  3020. tray_type=tray.tray_type,
  3021. tray_color=tray.tray_color,
  3022. tray_sub_brands=tray.tray_sub_brands,
  3023. tray_count=len(trays),
  3024. )
  3025. elif result:
  3026. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  3027. if result:
  3028. synced += 1
  3029. if result.get("id"):
  3030. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  3031. # If a new spool was created, add it to the cache
  3032. # so subsequent trays can find it if they reference the same tag
  3033. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  3034. if not spool_exists:
  3035. cached_spools.append(result)
  3036. logger.debug(
  3037. "[Printer %s] Added newly created spool %s to cache",
  3038. printer_id,
  3039. result["id"],
  3040. )
  3041. # Reconcile slot_preset_mappings (the same row internal
  3042. # mode keeps in sync via inventory + spool_tag_matcher).
  3043. # Without this the slot card surfaces the previous spool's
  3044. # preset name — same bug shape, different inventory mode.
  3045. from backend.app.services.slot_preset_writer import (
  3046. upsert_slot_preset_for_spoolman_spool,
  3047. )
  3048. await upsert_slot_preset_for_spoolman_spool(
  3049. db=db,
  3050. spoolman_spool=result,
  3051. tray_info_idx=tray.tray_info_idx or "",
  3052. tray_sub_brands=tray.tray_sub_brands or "",
  3053. tray_type=tray.tray_type or "",
  3054. printer_id=printer_id,
  3055. ams_id=ams_id,
  3056. tray_id=tray.tray_id,
  3057. )
  3058. except Exception as e:
  3059. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3060. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3061. if synced > 0:
  3062. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3063. # Persist slot assignment changes to the local table: only slots
  3064. # whose spool this pass changed, and only while they still hold what
  3065. # it read before awaiting Spoolman, so a spool assigned by hand in
  3066. # between stays (SSA-3). The changed slots are announced: the slot
  3067. # card reads slot_preset_mappings (rewritten above) ahead of the live
  3068. # tray, so with no event it kept the previous spool's preset name.
  3069. if slot_changes or empty_slots:
  3070. from backend.app.services.spoolman_slot_sync import write_slot_results
  3071. try:
  3072. await write_slot_results(
  3073. db,
  3074. {(printer_id, a_id, t_id): spool_id for (a_id, t_id), spool_id in spoolman_slot_map.items()}
  3075. if slot_map_read
  3076. else None,
  3077. [(printer_id, a_id, t_id, spool_id) for a_id, t_id, spool_id in slot_changes],
  3078. [(printer_id, a_id, t_id) for a_id, t_id in empty_slots],
  3079. )
  3080. except Exception as e:
  3081. await db.rollback()
  3082. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3083. except Exception as e:
  3084. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3085. # Largest finish photo attached to a notification; a bigger one is still linked.
  3086. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3087. async def _finish_photo_for_notification(
  3088. db, archive, archive_id: int, filename: str
  3089. ) -> tuple[str | None, bytes | None]:
  3090. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3091. With authentication off the link is the archive's own photo route, as it
  3092. always was: it opens without a login and doesn't expire. With
  3093. authentication on that route needs a media token, which nothing tapping a
  3094. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3095. link only ever answered 401. The photo is then saved as a notification
  3096. photo as well (utils/notification_photos.py) and the link points there: an
  3097. unguessable name that opens this one photo and nothing else, for 3 days.
  3098. The link is relative when no External URL is set. Bytes over
  3099. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3100. ``(None, None)`` when the photo can't be found.
  3101. """
  3102. from backend.app.api.routes.settings import get_setting
  3103. from backend.app.core.auth import is_auth_enabled
  3104. from backend.app.utils.archive_paths import find_archive_photo
  3105. from backend.app.utils.notification_photos import save_notification_photo
  3106. log = logging.getLogger(__name__)
  3107. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3108. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3109. photo_bytes: bytes | None = None
  3110. try:
  3111. photo_path = find_archive_photo(archive, filename)
  3112. if photo_path is not None:
  3113. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3114. except Exception as e:
  3115. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3116. try:
  3117. auth_on = await is_auth_enabled(db)
  3118. except Exception:
  3119. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3120. if auth_on:
  3121. url = None
  3122. if photo_bytes:
  3123. try:
  3124. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3125. url = f"{base}/api/v1/notifications/photos/{name}"
  3126. except Exception as e:
  3127. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3128. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3129. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3130. return url, None
  3131. if photo_bytes:
  3132. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3133. return url, photo_bytes
  3134. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3135. """Capture a camera snapshot for notification image attachment.
  3136. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3137. Uses: external camera > buffered frame > fresh capture.
  3138. Turns the chamber light on for the picture when the printer asks for it
  3139. (#1655). ``light=False`` is for callers that capture all through a print,
  3140. where the light would flash with every frame.
  3141. """
  3142. if not printer:
  3143. return None
  3144. async with camera_light(printer if light else None):
  3145. return await _capture_snapshot_frame(printer_id, printer, logger)
  3146. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3147. """The capture behind ``_capture_snapshot_for_notification``."""
  3148. try:
  3149. from backend.app.api.routes.settings import get_setting
  3150. async with async_session() as db:
  3151. capture_enabled = await get_setting(db, "capture_finish_photo")
  3152. if capture_enabled is not None and capture_enabled.lower() != "true":
  3153. return None
  3154. # Try external camera first
  3155. if printer.external_camera_enabled and printer.external_camera_url:
  3156. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3157. from backend.app.api.routes.camera import live_frame_for_capture
  3158. from backend.app.services.external_camera import capture_frame
  3159. # An external camera allows one reader, so capturing while a viewer
  3160. # is attached fails (#2707). A None here falls through to the paths
  3161. # below exactly as a failed capture did.
  3162. defer, buffered = live_frame_for_capture(printer_id)
  3163. if defer:
  3164. frame_data = buffered
  3165. else:
  3166. frame_data = await capture_frame(
  3167. printer.external_camera_url,
  3168. printer.external_camera_type or "mjpeg",
  3169. snapshot_url=printer.external_camera_snapshot_url,
  3170. )
  3171. if frame_data and len(frame_data) <= 2_500_000:
  3172. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3173. return _apply_camera_rotation(frame_data, printer, logger)
  3174. # Try buffered frame from active stream
  3175. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3176. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3177. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3178. buffered_frame = get_buffered_frame(printer_id)
  3179. if (active_for_printer or active_chamber) and buffered_frame:
  3180. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3181. if len(buffered_frame) <= 2_500_000:
  3182. return _apply_camera_rotation(buffered_frame, printer, logger)
  3183. # Fresh capture from printer camera
  3184. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3185. from backend.app.services.camera import capture_camera_frame_bytes
  3186. frame_data = await capture_camera_frame_bytes(
  3187. printer.ip_address, printer.access_code, printer.model, timeout=15
  3188. )
  3189. if frame_data and len(frame_data) <= 2_500_000:
  3190. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3191. return _apply_camera_rotation(frame_data, printer, logger)
  3192. except Exception as e:
  3193. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3194. return None
  3195. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3196. """#1867: bank a recent in-print camera frame for the finish photo.
  3197. Called on every layer change and (#2547) on every print-progress advance.
  3198. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3199. path has a pre-End-G-code image for prints that end with a plate swap.
  3200. Both drivers are print telemetry that stops the instant printing ends: no
  3201. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3202. plate swap) executes. So the last banked frame is always the finished print,
  3203. never the swapped plate — that property is what the #1867 path relies on and
  3204. it must survive any change to the throttle below.
  3205. Layer changes alone were not enough: they stop when the *final* layer
  3206. begins, which on a three-minute last layer left the bank stale by the whole
  3207. length of that layer (#2547). Progress keeps ticking through it.
  3208. Best-effort: any failure just leaves the previous banked frame.
  3209. """
  3210. logger = logging.getLogger(__name__)
  3211. client = printer_manager.get_client(printer_id)
  3212. state = client.state if client else None
  3213. if not state or state.state != "RUNNING":
  3214. return
  3215. # Only during actual extrusion — firmware ticks layer_num during the
  3216. # pre-print calibration sequence, whose sub-stages are non-zero.
  3217. if state.mc_print_sub_stage not in (None, 0):
  3218. return
  3219. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3220. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3221. # now that progress advances also drive banking, that exemption would fire a
  3222. # camera grab on every percent tick of the last layer. Bambu printers accept
  3223. # one RTSP client at a time, so each grab contends with the live view.
  3224. now = time.monotonic()
  3225. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3226. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3227. return
  3228. total = state.total_layers or 0
  3229. try:
  3230. async with async_session() as db:
  3231. from backend.app.models.printer import Printer
  3232. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3233. printer = result.scalar_one_or_none()
  3234. if not printer:
  3235. return
  3236. # Reuses the notification snapshot path, which honours the
  3237. # `capture_finish_photo` setting (returns None when disabled) so we
  3238. # don't bank frames the user never asked for. Without the chamber light
  3239. # (#1655): this runs every 25 seconds for the whole print.
  3240. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3241. if frame:
  3242. _inprint_frame_bank[printer_id] = frame
  3243. _inprint_frame_bank_ts[printer_id] = now
  3244. logger.debug(
  3245. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3246. printer_id,
  3247. layer_num,
  3248. total,
  3249. len(frame),
  3250. )
  3251. except Exception as e:
  3252. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3253. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3254. """Apply camera rotation to snapshot image if configured."""
  3255. from backend.app.services.camera import apply_camera_rotation
  3256. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3257. async def _send_print_start_notification(
  3258. printer_id: int,
  3259. data: dict,
  3260. archive_data: dict | None = None,
  3261. logger=None,
  3262. ):
  3263. """Helper to send print start notification with optional archive data."""
  3264. if logger is None:
  3265. logger = logging.getLogger(__name__)
  3266. try:
  3267. async with async_session() as db:
  3268. from backend.app.models.printer import Printer
  3269. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3270. printer = result.scalar_one_or_none()
  3271. printer_name = printer.name if printer else f"Printer {printer_id}"
  3272. # Capture camera snapshot for notification image attachment
  3273. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3274. if image_data:
  3275. if archive_data is None:
  3276. archive_data = {}
  3277. archive_data["image_data"] = image_data
  3278. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3279. # Send user-specific email notification for print start
  3280. if archive_data and archive_data.get("created_by_id"):
  3281. await notification_service.send_user_print_email(
  3282. event_type="user_print_start",
  3283. created_by_id=archive_data["created_by_id"],
  3284. printer_name=printer_name,
  3285. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3286. db=db,
  3287. )
  3288. except Exception as e:
  3289. logger.warning("Notification on_print_start failed: %s", e)
  3290. async def _dispatch_user_print_email(
  3291. status: str,
  3292. created_by_id: int | None,
  3293. printer_name: str,
  3294. filename: str,
  3295. db,
  3296. image_data: bytes | None = None,
  3297. finish_photo_url: str | None = None,
  3298. ) -> None:
  3299. """Send a user-specific print-completion email based on print status.
  3300. Maps the normalised print status to the correct event type and delegates
  3301. to :meth:`NotificationService.send_user_print_email`. A single helper
  3302. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3303. "stopped"`` dispatch block at every call site.
  3304. Does nothing if *created_by_id* is ``None``.
  3305. """
  3306. if created_by_id is None:
  3307. return
  3308. if status == "completed":
  3309. event_type = "user_print_complete"
  3310. elif status == "failed":
  3311. event_type = "user_print_failed"
  3312. elif status in ("stopped", "aborted", "cancelled"):
  3313. event_type = "user_print_stopped"
  3314. else:
  3315. return
  3316. await notification_service.send_user_print_email(
  3317. event_type=event_type,
  3318. created_by_id=created_by_id,
  3319. printer_name=printer_name,
  3320. filename=filename,
  3321. db=db,
  3322. image_data=image_data,
  3323. finish_photo_url=finish_photo_url,
  3324. )
  3325. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3326. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3327. try:
  3328. from backend.app.services.archive import extract_printable_objects_from_archive
  3329. client = printer_manager.get_client(printer_id)
  3330. if not client:
  3331. return
  3332. # Extract with positions for UI overlay, scoped to the plate that
  3333. # is printing — resolve_plate_id is the same resolver /cover uses,
  3334. # so the object list can't disagree with the thumbnail it is drawn
  3335. # over (#2522).
  3336. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3337. app_settings.base_dir / archive.file_path,
  3338. plate_number=resolve_plate_id(client.state),
  3339. )
  3340. if printable_objects:
  3341. client.state.printable_objects = printable_objects
  3342. client.state.printable_objects_bbox_all = bbox_all
  3343. client.state.skipped_objects = []
  3344. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3345. except Exception as e:
  3346. logger.debug("Failed to extract printable objects from archive: %s", e)
  3347. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3348. """Put the skip-objects list back after a restart mid-print.
  3349. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3350. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3351. which the #1304 guard suppresses on the first RUNNING push after startup.
  3352. Everything else this hook restores (the archive, the usage-tracking session,
  3353. the timelapse baseline) was already handled; the object list was not, so a
  3354. restart mid-print took skip-objects away for the rest of that print.
  3355. Nothing recovered it either: the printer card gates its Skip button on the
  3356. object count, and the one endpoint that can rebuild the list is reachable
  3357. only from the modal that button opens.
  3358. Anchored on ``subtask_id``, which the firmware mints per print, so a
  3359. leftover ``status="printing"`` row from a completion we never saw cannot
  3360. hand this print someone else's objects. Without one, nothing is loaded
  3361. rather than guessed — the reload path on ``GET /print/objects`` covers that
  3362. case on demand.
  3363. """
  3364. client = printer_manager.get_client(printer_id)
  3365. if client is None or client.state.printable_objects:
  3366. return
  3367. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  3368. if subtask_id in ("", "0"):
  3369. return
  3370. from backend.app.models.archive import PrintArchive
  3371. archive = await db.scalar(
  3372. select(PrintArchive)
  3373. .where(
  3374. PrintArchive.printer_id == printer_id,
  3375. PrintArchive.status == "printing",
  3376. PrintArchive.subtask_id == subtask_id,
  3377. )
  3378. .order_by(PrintArchive.created_at.desc())
  3379. .limit(1)
  3380. )
  3381. if archive is not None:
  3382. _load_objects_from_archive(archive, printer_id, logger)
  3383. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3384. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3385. # past it; the second covers a handshake that failed again on the way back and
  3386. # armed a fresh one. Module-level so tests can shrink them.
  3387. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3388. # Retry ladder for the other temporary give-up: the file service answered and
  3389. # the transfer still did not finish, which at print start is usually the printer
  3390. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3391. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3392. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3393. # two cover a printer that stays busy well into the print.
  3394. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3395. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3396. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3397. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3398. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3399. # by view, so two views race), the cool-off retry task, and print completion.
  3400. # Without this they each read file_path == "" and each run a full copy, so the row
  3401. # ends up pointing at one timestamped directory while the others sit orphaned.
  3402. #
  3403. # Keyed by printer rather than archive because a printer runs one print at a time,
  3404. # which makes the two equally strong here — and it bounds the dict by printer
  3405. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3406. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3407. # resuming, so "no waiters" is not a question this API can answer.
  3408. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3409. # How many of a printer's newest archives a touchscreen reprint is compared
  3410. # against (#3307). A repeat is usually of a recent job; the bound keeps a
  3411. # print start from reading a long history's extra_data.
  3412. _REPEAT_LOOKBACK = 200
  3413. async def _archived_3mf_for_repeat(
  3414. db, printer_id: int, subtask_name: str | None, gcode_file: str | None, total_layers: int | None
  3415. ):
  3416. """The newest archive of the job this printer is running again, with its 3MF.
  3417. A "Print again" on the printer's screen never names the file on the card:
  3418. it reports its own history copy under a generic name
  3419. (``file:///userdata/project_file.gcode.3mf``), the 3MF's internal title as
  3420. ``subtask_name`` and the plate as ``gcode_file`` -- and the title is often
  3421. not the card file's name, so every lookup built from it misses (#3307).
  3422. An earlier run that was archived recorded that same title and plate in its
  3423. ``_print_data``, and holds the 3MF.
  3424. Same printer, same title, same plate, a 3MF still on disk. A layer count
  3425. known on both sides must agree: the same title and plate re-sliced is
  3426. another job. None when nothing matches.
  3427. """
  3428. from backend.app.models.archive import PrintArchive
  3429. if not subtask_name or not gcode_file:
  3430. return None
  3431. rows = (
  3432. (
  3433. await db.execute(
  3434. select(PrintArchive)
  3435. .where(
  3436. PrintArchive.printer_id == printer_id,
  3437. PrintArchive.deleted_at.is_(None),
  3438. PrintArchive.file_path.isnot(None),
  3439. PrintArchive.file_path != "",
  3440. )
  3441. .order_by(PrintArchive.created_at.desc(), PrintArchive.id.desc())
  3442. .limit(_REPEAT_LOOKBACK)
  3443. )
  3444. )
  3445. .scalars()
  3446. .all()
  3447. )
  3448. for archive in rows:
  3449. extra = archive.extra_data if isinstance(archive.extra_data, dict) else {}
  3450. run = extra.get("_print_data")
  3451. if not isinstance(run, dict):
  3452. continue
  3453. if run.get("subtask_name") != subtask_name or run.get("filename") != gcode_file:
  3454. continue
  3455. if total_layers and archive.total_layers and archive.total_layers != total_layers:
  3456. continue
  3457. if not (app_settings.base_dir / archive.file_path).is_file():
  3458. continue
  3459. return archive
  3460. return None
  3461. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True) -> bool:
  3462. """Fill in a no-3MF archive from a 3MF that turned up later.
  3463. Returns True when the row was upgraded. Safe to call speculatively: it
  3464. verifies the archive still exists, is still a fallback, and that the file
  3465. is a readable 3MF before touching anything.
  3466. Serialised per printer — see ``_fallback_recovery_locks``.
  3467. """
  3468. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3469. async with lock:
  3470. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id, price=price)
  3471. async def _recover_fallback_archive_locked(
  3472. archive_id: int, source_3mf: Path, printer_id: int, *, price: bool = True
  3473. ) -> bool:
  3474. """The body of :func:`_recover_fallback_archive`, under its per-printer lock.
  3475. ``price`` is False when the print's end is being handled: the archive
  3476. still reads "printing" then, and its end prices it.
  3477. """
  3478. import zipfile
  3479. from backend.app.models.archive import PrintArchive
  3480. from backend.app.services.archive import ArchiveService
  3481. logger = logging.getLogger(__name__)
  3482. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3483. return False
  3484. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3485. # A truncated or half-written download is worse than no download: it
  3486. # would replace an honest empty archive with wrong metadata.
  3487. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3488. return False
  3489. async with async_session() as db:
  3490. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3491. if archive is None or archive.deleted_at is not None:
  3492. return False
  3493. if archive.file_path:
  3494. # Already recovered, or never was a fallback. Either way there is a
  3495. # real 3MF attached and overwriting it is not this function's job.
  3496. return False
  3497. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3498. service = ArchiveService(db)
  3499. recovered = await service.archive_print(
  3500. printer_id=printer_id,
  3501. source_file=source_3mf,
  3502. print_data={**print_data, "status": archive.status or "printing"},
  3503. subtask_id=archive.subtask_id,
  3504. update_archive_id=archive.id,
  3505. )
  3506. if recovered is None:
  3507. return False
  3508. logger.info(
  3509. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3510. archive_id,
  3511. source_3mf,
  3512. recovered.file_size,
  3513. )
  3514. # Spoolman's tracking stored no 3MF usage at print start and would
  3515. # charge the AMS remain% change; the built-in tracker reads the archive
  3516. # at completion and needs nothing. Also at the print's end (``price``
  3517. # False): that recovery runs inside the close-out, before the charge.
  3518. try:
  3519. from backend.app.services.spoolman_tracking import attach_recovered_3mf
  3520. from backend.app.services.usage_tracker import is_completing
  3521. await attach_recovered_3mf(
  3522. printer_id,
  3523. recovered.id,
  3524. recovered.file_path,
  3525. db,
  3526. printer_manager,
  3527. plate_id=_get_start_plate_id(recovered.id) or recovered.plate_id,
  3528. may_start=not price or (recovered.status == "printing" and not is_completing(printer_id)),
  3529. )
  3530. except Exception:
  3531. logger.warning(
  3532. "[RECOVER] Archive %s: could not add the 3MF to Spoolman's usage tracking", archive_id, exc_info=True
  3533. )
  3534. if price and recovered.status == "printing":
  3535. # Print start priced it from the default rate, having no 3MF to
  3536. # estimate from; now it has one. An ended print is left alone: its
  3537. # end prices it. A print Bambuddy didn't dispatch has no start
  3538. # plate; the one the archive just read from the 3MF stands in.
  3539. _schedule_archive_cost_estimate(
  3540. printer_id,
  3541. recovered.id,
  3542. printer_manager,
  3543. ams_mapping=_get_start_ams_mapping(print_data, recovered.id),
  3544. plate_id=_get_start_plate_id(recovered.id) or recovered.plate_id,
  3545. session_factory=async_session,
  3546. )
  3547. # `archive_updated`, not `archive_created` — the row was already on the
  3548. # Archives page as an empty card and is now filled in, not new.
  3549. await ws_manager.send_archive_updated(
  3550. {
  3551. "id": recovered.id,
  3552. "printer_id": recovered.printer_id,
  3553. "filename": recovered.filename,
  3554. "print_name": recovered.print_name,
  3555. "status": recovered.status,
  3556. }
  3557. )
  3558. return True
  3559. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path, *, price: bool = True) -> bool:
  3560. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3561. Called from the paths that pull a 3MF for a print that is already under way
  3562. — chiefly the cover endpoint, which downloads the very file the archive flow
  3563. could not get and, before #2957, used it for a thumbnail and nothing else.
  3564. The bytes are already local, so this costs a parse and a row update.
  3565. No-op when the running print has a real archive, which is the common case.
  3566. """
  3567. from backend.app.models.archive import PrintArchive
  3568. logger = logging.getLogger(__name__)
  3569. # `_active_prints` is keyed on the raw names seen at print start — the
  3570. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3571. # Callers here arrive with whichever variant their own path produced, so
  3572. # match on the same normalization the download cache uses rather than on an
  3573. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3574. # endpoint find an archive registered under "Desktop_Goose".
  3575. wanted = normalize_3mf_name(name)
  3576. archive_id = None
  3577. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3578. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3579. archive_id = value
  3580. break
  3581. if archive_id is None:
  3582. return False
  3583. async with async_session() as db:
  3584. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3585. # Cheap pre-check so the common case (a normal archive) does no work.
  3586. if archive is None or archive.file_path or archive.deleted_at is not None:
  3587. return False
  3588. try:
  3589. return await _recover_fallback_archive(archive_id, path, printer_id, price=price)
  3590. except Exception as e:
  3591. # Recovery is opportunistic. A failure here must never take down the
  3592. # caller, which is usually just trying to render a thumbnail.
  3593. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3594. return False
  3595. def _schedule_fallback_3mf_retry(
  3596. printer_id: int,
  3597. archive_id: int,
  3598. filenames: list[str],
  3599. delays: tuple[float, ...] | None = None,
  3600. reason: str = REASON_FTPS_COOLOFF,
  3601. ) -> None:
  3602. """Re-attempt the 3MF download after a temporary give-up.
  3603. ``reason`` says which give-up this is, and picks the default ladder: an
  3604. FTPS cool-off has to be waited out, while a transfer that timed out under
  3605. contention is worth asking about again straight away (#3063). It is only
  3606. read for the ladder and the log line -- the retry itself is identical, since
  3607. in both cases the file is on the printer and the last attempt at it failed
  3608. for a reason that does not last.
  3609. """
  3610. logger = logging.getLogger(__name__)
  3611. if delays is None:
  3612. delays = (
  3613. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3614. if reason == REASON_FTP_TRANSFER_FAILED
  3615. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3616. )
  3617. async def _retry() -> None:
  3618. from backend.app.models.archive import PrintArchive
  3619. from backend.app.models.printer import Printer
  3620. for delay in delays:
  3621. await asyncio.sleep(delay)
  3622. async with async_session() as db:
  3623. archive = (
  3624. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3625. ).scalar_one_or_none()
  3626. if archive is None or archive.deleted_at is not None or archive.file_path:
  3627. return
  3628. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3629. if printer is None:
  3630. return
  3631. # Read the fields while the session is open rather than touching
  3632. # a detached instance minutes later, mid-download.
  3633. printer_ip = printer.ip_address
  3634. printer_code = printer.access_code
  3635. printer_model = printer.model
  3636. # Someone else may have fetched it in the meantime — the cover
  3637. # endpoint routinely does, and its copy is the same bytes.
  3638. for name in filenames:
  3639. cached = get_cached_3mf(printer_id, name)
  3640. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3641. return
  3642. if ftps_handshake_blocked(printer_ip):
  3643. logger.info(
  3644. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3645. printer_id,
  3646. archive_id,
  3647. )
  3648. continue
  3649. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3650. for candidate in filenames:
  3651. # Bare name only. These come from the print-start flow, which
  3652. # already strips the path, but the local temp write must not
  3653. # depend on that holding for every future caller — a name that
  3654. # is absolute or contains ".." would otherwise escape the data
  3655. # volume via the `/` operator.
  3656. name = Path(candidate).name
  3657. if not name or name in (".", ".."):
  3658. continue
  3659. if not name.endswith(".3mf"):
  3660. name = f"{name}.3mf"
  3661. temp_path = app_settings.archive_dir / "temp" / name
  3662. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3663. try:
  3664. hit = await download_file_try_paths_async(
  3665. printer_ip,
  3666. printer_code,
  3667. ftp_probe_paths(name),
  3668. temp_path,
  3669. socket_timeout=ftp_timeout,
  3670. printer_model=printer_model,
  3671. max_total_timeout=RECOVERY_DOWNLOAD_MAX_TIMEOUT,
  3672. )
  3673. except Exception as e:
  3674. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3675. continue
  3676. if not hit:
  3677. continue
  3678. cache_3mf_download(printer_id, name, temp_path)
  3679. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3680. return
  3681. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3682. async def _guarded() -> None:
  3683. try:
  3684. await _retry()
  3685. except asyncio.CancelledError:
  3686. raise
  3687. except Exception as e:
  3688. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3689. finally:
  3690. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3691. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3692. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3693. if existing and not existing.done():
  3694. existing.cancel()
  3695. task = asyncio.create_task(_guarded())
  3696. _fallback_3mf_retry_tasks[printer_id] = task
  3697. logger.info(
  3698. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3699. archive_id,
  3700. reason,
  3701. printer_id,
  3702. ", ".join(f"{d:g}s" for d in delays),
  3703. )
  3704. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3705. """Whether an archive created here should ask for the print's outcome (#1898).
  3706. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3707. branches below: a queued job already has its archive and takes the
  3708. expected-print branch, where the queue item's own ``confirm_outcome``
  3709. decides. The queue is still consulted, because a restart mid-print empties
  3710. ``_expected_prints`` — without the check the setting could override a queue
  3711. item that deliberately has the flag off. Any failure answers "don't ask":
  3712. an unwanted prompt is worse than a missing one, and this must never be the
  3713. reason a print goes unarchived.
  3714. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3715. leaves one behind when a completion cannot be matched to it
  3716. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3717. only takes it back once the printer has sat connected and terminal for
  3718. minutes. Until then every screen-started print on that printer would
  3719. silently lose its prompt, so the row is held against ``observed_name`` by
  3720. the same comparison a completion uses: a positive disagreement means the row
  3721. is about some other run and this print is external after all.
  3722. """
  3723. logger = logging.getLogger(__name__)
  3724. try:
  3725. # A savepoint rather than a rollback of the caller's transaction on
  3726. # failure: a failed statement leaves the transaction unusable, but a
  3727. # full rollback also expires every object the caller has loaded (the
  3728. # printer, the archive it just created), and on an async session the
  3729. # next attribute read then raises instead of reloading. Everything here
  3730. # is a read, so undoing the savepoint loses nothing.
  3731. async with db.begin_nested():
  3732. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3733. except Exception as e:
  3734. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3735. return False
  3736. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3737. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3738. from backend.app.api.routes.settings import get_setting, setting_is_true
  3739. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3740. return False
  3741. from backend.app.models.print_queue import PrintQueueItem
  3742. dispatched_here = await db.scalar(
  3743. select(PrintQueueItem)
  3744. .where(
  3745. PrintQueueItem.printer_id == printer_id,
  3746. PrintQueueItem.status == "printing",
  3747. )
  3748. .limit(1)
  3749. )
  3750. if dispatched_here is None:
  3751. return True
  3752. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3753. observed = (observed_name or "").strip()
  3754. if not expected or not observed or _subtask_names_match(expected, observed):
  3755. logger.info(
  3756. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3757. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3758. printer_id,
  3759. dispatched_here.id,
  3760. )
  3761. return False
  3762. logger.info(
  3763. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3764. "%r; treating this as an externally started print.",
  3765. dispatched_here.id,
  3766. printer_id,
  3767. expected,
  3768. observed,
  3769. )
  3770. return True
  3771. async def _dispatch_outcome_confirmation_safely(
  3772. db,
  3773. printer_id: int,
  3774. printer_name: str,
  3775. data: dict,
  3776. archive_id: int,
  3777. archive_data: dict | None = None,
  3778. ) -> None:
  3779. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3780. The completion task sends the per-user print email on the same session
  3781. right after the prompt. A failed statement in the prompt leaves that
  3782. session needing a rollback, and without one the email step fails with
  3783. PendingRollbackError; the prompt is the optional part, so it must not be
  3784. the reason the email never goes out.
  3785. """
  3786. try:
  3787. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3788. except Exception as e:
  3789. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  3790. try:
  3791. await db.rollback()
  3792. except Exception:
  3793. pass
  3794. async def dispatch_outcome_confirmation(
  3795. db,
  3796. printer_id: int,
  3797. printer_name: str,
  3798. data: dict,
  3799. archive_id: int,
  3800. archive_data: dict | None = None,
  3801. ) -> bool:
  3802. """Emit the post-print outcome prompt for a completed archive (#1898).
  3803. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3804. queue item, or from ``confirm_outcome_external_prints`` for a print
  3805. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3806. question still open. Mints the per-archive capability token the one-tap
  3807. verdict links carry.
  3808. Lives here rather than inline in ``on_print_complete``'s notification task
  3809. because that task swallows every exception: extracted, the gate and the two
  3810. emissions can be driven by a test, which is the only thing standing between
  3811. a regression here and a farm that quietly stops asking.
  3812. Returns whether a prompt was sent.
  3813. """
  3814. logger = logging.getLogger(__name__)
  3815. from backend.app.models.archive import PrintArchive
  3816. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3817. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3818. return False
  3819. import secrets as _secrets
  3820. # A spent token stays on the row so the one-tap route can recognise it, so
  3821. # "has a token" no longer means "answerable". A prompt going out now needs a
  3822. # live one: mint a new token whenever the stored one is already spent, or
  3823. # every button in the new message would land on the already-answered page.
  3824. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  3825. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  3826. confirm_archive.confirm_token_used_at = None
  3827. await db.commit()
  3828. from backend.app.api.routes.settings import get_external_base_url, get_setting
  3829. base = await get_external_base_url(db)
  3830. if not await get_setting(db, "external_url"):
  3831. # Both the Telegram inline keyboard and the ntfy action buttons need an
  3832. # absolute URL, so an unconfigured install used to get a message body
  3833. # with two unusable relative paths and no buttons at all. The shared
  3834. # fallback at least produces tappable links; say which setting makes
  3835. # them resolve from a phone.
  3836. logger.warning(
  3837. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  3838. "Set Settings → External URL so they resolve away from this host.",
  3839. base,
  3840. )
  3841. token = confirm_archive.confirm_token
  3842. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  3843. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  3844. confirm_url = f"{base}/archives?confirm={archive_id}"
  3845. await ws_manager.send_print_confirm_request(
  3846. printer_id,
  3847. {
  3848. "archive_id": archive_id,
  3849. "print_name": confirm_archive.print_name or confirm_archive.filename,
  3850. },
  3851. )
  3852. await notification_service.on_print_confirm_request(
  3853. printer_id,
  3854. printer_name,
  3855. data,
  3856. db,
  3857. archive_data=archive_data,
  3858. good_url=good_url,
  3859. reject_url=reject_url,
  3860. confirm_url=confirm_url,
  3861. archive_id=archive_id,
  3862. )
  3863. return True
  3864. async def _printer_gone(db, printer_id: int) -> bool:
  3865. """Whether the printer was deleted. A column read: the session's loaded
  3866. Printer would otherwise answer for the database."""
  3867. from backend.app.models.printer import Printer
  3868. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  3869. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  3870. """Remove the archive just written if its printer was deleted meanwhile.
  3871. The delete route sweeps the printer's archives before it commits, so a row
  3872. committed after that sweep (the check before writing passed while the
  3873. delete was still uncommitted) is left for a printer that will never report
  3874. the print's end. A row the sweep reached is the route's: deleted with the
  3875. printer's archives, or detached (printer_id NULL) when the user kept them,
  3876. and then left as it is. Either way nothing is registered for it. Run after
  3877. the archive's commit, before anything is registered for it.
  3878. """
  3879. from backend.app.models.archive import PrintArchive
  3880. if not await _printer_gone(db, printer_id):
  3881. return False
  3882. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  3883. if owner == printer_id:
  3884. logging.getLogger(__name__).info(
  3885. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  3886. )
  3887. await ArchiveService(db).delete_archive(archive_id)
  3888. await forget_printer(printer_id)
  3889. return True
  3890. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  3891. """After an IntegrityError on a print start's archive write: whether it was
  3892. the printer being deleted, forgotten then (the caller returns).
  3893. PostgreSQL: the delete route locks the printer from its archive sweep to its
  3894. commit, so an archive written or adopted for it meanwhile (one that sets
  3895. printer_id) waits and the printer's foreign key then refuses it. That is
  3896. the printer being deleted, not an error; anything else is re-raised by the
  3897. caller.
  3898. """
  3899. await db.rollback()
  3900. if not await _printer_gone(db, printer_id):
  3901. return False
  3902. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  3903. await forget_printer(printer_id)
  3904. return True
  3905. async def _forget_if_printer_gone(printer_id: int) -> None:
  3906. """At the end of a print start: the slow steps after the last check (smart
  3907. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  3908. printer's delete and its forget_printer, and then wrote state back.
  3909. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  3910. SQLite; PostgreSQL refuses it.)
  3911. Its own session: those steps can leave the handler's needing a rollback (a
  3912. write to the archive the delete removed). Never raises: it runs inside the
  3913. fallback branch's try, whose except reports the archive as failed.
  3914. """
  3915. try:
  3916. async with async_session() as db:
  3917. gone = await _printer_gone(db, printer_id)
  3918. if gone:
  3919. await forget_printer(printer_id)
  3920. except Exception:
  3921. logging.getLogger(__name__).warning(
  3922. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  3923. )
  3924. async def _announce_plate_check_failed(printer_id: int, printer_name: str, reason: str) -> None:
  3925. """Tell the UI a plate check could not run. It does not block the print,
  3926. but an unchecked plate is not an empty one."""
  3927. try:
  3928. await ws_manager.broadcast(
  3929. {"type": "plate_check_failed", "printer_id": printer_id, "printer_name": printer_name, "reason": reason}
  3930. )
  3931. except Exception as e:
  3932. logging.getLogger(__name__).warning("[PLATE CHECK] Could not announce the failed check: %s", e)
  3933. def _expected_print_keys(printer_id: int, filename: str | None, subtask_name: str | None) -> list[tuple[int, str]]:
  3934. """The ``_expected_prints`` keys a print start may be registered under."""
  3935. keys: list[tuple[int, str]] = []
  3936. if subtask_name:
  3937. keys.append((printer_id, subtask_name))
  3938. keys.append((printer_id, f"{subtask_name}.3mf"))
  3939. keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  3940. if filename:
  3941. fname = filename.split("/")[-1] if "/" in filename else filename
  3942. keys.append((printer_id, fname))
  3943. # Strip extensions to match
  3944. base = fname.replace(".gcode", "").replace(".3mf", "")
  3945. keys.append((printer_id, base))
  3946. keys.append((printer_id, f"{base}.3mf"))
  3947. return keys
  3948. async def _dispatched_by_bambuddy(db, printer_id: int, filename: str | None, subtask_name: str | None) -> bool:
  3949. """Whether this print start is one Bambuddy sent to the printer."""
  3950. if any(key in _expected_prints for key in _expected_print_keys(printer_id, filename, subtask_name)):
  3951. return True
  3952. from backend.app.models.archive import PrintArchive
  3953. from backend.app.models.print_queue import PrintQueueItem
  3954. # The queue row the scheduler sets to printing before it sends -- but only
  3955. # when it was sent as this print: a row left printing by a run whose end
  3956. # was missed names another file.
  3957. dispatched_names = (
  3958. await db.execute(
  3959. select(PrintArchive.filename)
  3960. .join(PrintQueueItem, PrintQueueItem.archive_id == PrintArchive.id)
  3961. .where(PrintQueueItem.printer_id == printer_id, PrintQueueItem.status == "printing")
  3962. )
  3963. ).scalars()
  3964. observed = [name for name in (subtask_name, (filename or "").rsplit("/", 1)[-1]) if name]
  3965. return any(
  3966. _subtask_names_match(_subtask_name_from_filename(dispatched), _subtask_name_from_filename(seen))
  3967. for dispatched in dispatched_names
  3968. if dispatched
  3969. for seen in observed
  3970. )
  3971. async def on_print_start(printer_id: int, data: dict):
  3972. """Handle print start - archive the 3MF file immediately."""
  3973. logger = logging.getLogger(__name__)
  3974. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3975. try:
  3976. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  3977. except Exception:
  3978. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  3979. # Clear any stale user-stopped flag from previous print cycles
  3980. _user_stopped_printers.discard(printer_id)
  3981. _kill_switch_stopped.discard(printer_id)
  3982. # A new print starts its milestones from zero (#3211). The status path only
  3983. # resets on progress below 5 while not printing, which a printer that goes
  3984. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  3985. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  3986. # or on resume from pause, so it cannot repeat a milestone mid-print.
  3987. _last_progress_milestone[printer_id] = 0
  3988. _kill_switch_notification_tasks.pop(printer_id, None)
  3989. # #1721: drop any leftover pre-captured finish frame from a prior print
  3990. # so a never-consumed cache entry can't bleed into the new print's photo.
  3991. _stage22_finish_frames.pop(printer_id, None)
  3992. # #1867: same for the in-print frame bank — a queued print must not reuse
  3993. # the previous job's banked frame.
  3994. _inprint_frame_bank.pop(printer_id, None)
  3995. _inprint_frame_bank_ts.pop(printer_id, None)
  3996. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3997. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3998. # print's flag instead of inheriting it.
  3999. print_dispatch_context.adopt(printer_id)
  4000. # Cancel any active bed cooldown waiter for this printer
  4001. if _bed_cool_waiters.pop(printer_id, None):
  4002. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  4003. # Clear cached cover images so the new print's thumbnail is fetched fresh
  4004. from backend.app.api.routes.printers import clear_cover_cache
  4005. clear_cover_cache(printer_id)
  4006. await ws_manager.send_print_start(printer_id, data)
  4007. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  4008. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  4009. # MQTT relay - publish print start
  4010. try:
  4011. printer_info = printer_manager.get_printer(printer_id)
  4012. if printer_info:
  4013. await mqtt_relay.on_print_start(
  4014. printer_id,
  4015. printer_info.name,
  4016. printer_info.serial_number,
  4017. data.get("filename", ""),
  4018. data.get("subtask_name", ""),
  4019. )
  4020. except Exception:
  4021. pass # Don't fail print start callback if MQTT fails
  4022. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  4023. # and mapping, and the seeded tray-change log.
  4024. #
  4025. # Unconditional, for both inventory backends. This only *captures* — the
  4026. # writing is still split, with the internal tracker skipped at completion
  4027. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  4028. # carries its plate-scoped 3MF figures and stored mapping, but not the
  4029. # tray-change log, and that log is the only record of which spool fed
  4030. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  4031. # it on one side only would leave Spoolman users with the mid-print
  4032. # restart bug this fixes for everyone else.
  4033. try:
  4034. async with async_session() as db:
  4035. from backend.app.api.routes.settings import get_setting
  4036. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  4037. _spoolman_on = await get_setting(db, "spoolman_enabled")
  4038. await usage_on_print_start(
  4039. printer_id,
  4040. data,
  4041. printer_manager,
  4042. db=db,
  4043. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  4044. )
  4045. except Exception as e:
  4046. logger.warning("Usage tracker on_print_start failed: %s", e)
  4047. # Track if notification was sent (to avoid sending twice)
  4048. notification_sent = False
  4049. # Smart plug automation: turn on plug when print starts
  4050. try:
  4051. async with async_session() as db:
  4052. await smart_plug_manager.on_print_start(printer_id, db)
  4053. except Exception as e:
  4054. logger.warning("Smart plug on_print_start failed: %s", e)
  4055. async with async_session() as db:
  4056. from backend.app.models.printer import Printer
  4057. from backend.app.services.bambu_ftp import list_files_async
  4058. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4059. printer = result.scalar_one_or_none()
  4060. # Plate detection check - pause if objects detected on build plate
  4061. logger.info(
  4062. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  4063. )
  4064. if printer and printer.plate_detection_enabled:
  4065. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  4066. # Release the pooled DB connection before the plate-detection camera
  4067. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  4068. # printer SELECT has run so far — nothing to persist — so this commit
  4069. # is a data-noop that ends the read transaction and returns the
  4070. # connection to the pool during the I/O (issue #2572). expire_on_commit
  4071. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  4072. # archive lookups below re-acquire a fresh connection on next execute.
  4073. await db.commit()
  4074. try:
  4075. from backend.app.services.plate_detection import check_plate_empty
  4076. # Build ROI tuple from printer settings if available
  4077. roi = None
  4078. if all(
  4079. [
  4080. printer.plate_detection_roi_x is not None,
  4081. printer.plate_detection_roi_y is not None,
  4082. printer.plate_detection_roi_w is not None,
  4083. printer.plate_detection_roi_h is not None,
  4084. ]
  4085. ):
  4086. roi = (
  4087. printer.plate_detection_roi_x,
  4088. printer.plate_detection_roi_y,
  4089. printer.plate_detection_roi_w,
  4090. printer.plate_detection_roi_h,
  4091. )
  4092. # The light is held, not switched, so a live view opened
  4093. # meanwhile keeps it when the check lets go (SP-C11). Every
  4094. # printer, whatever the camera light mode: detection needs it.
  4095. plate_photo_data = None
  4096. objects_detected = False
  4097. check_failure: str | None = None
  4098. async with camera_light(printer, any_mode=True, settle=2.5):
  4099. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  4100. plate_result = await check_plate_empty(
  4101. printer_id=printer_id,
  4102. ip_address=printer.ip_address,
  4103. access_code=printer.access_code,
  4104. model=printer.model,
  4105. include_debug_image=False,
  4106. external_camera_url=printer.external_camera_url,
  4107. external_camera_type=printer.external_camera_type,
  4108. use_external=printer.external_camera_enabled,
  4109. roi=roi,
  4110. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  4111. )
  4112. # No reference to compare against is a check that did not
  4113. # run either: say so rather than call the plate empty.
  4114. check_failure = getattr(plate_result, "failure_reason", None) or (
  4115. "not_calibrated" if plate_result.needs_calibration else None
  4116. )
  4117. objects_detected = not check_failure and not plate_result.is_empty
  4118. if objects_detected:
  4119. # Objects detected - pause the print!
  4120. logger.warning(
  4121. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  4122. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  4123. )
  4124. pause_client = printer_manager.get_client(printer_id)
  4125. if pause_client:
  4126. pause_client.pause_print()
  4127. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  4128. # Snapshot while the light's still on — restoring it first
  4129. # would leave the notification with a dark photo.
  4130. try:
  4131. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  4132. except Exception as snap_err:
  4133. logger.warning(
  4134. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  4135. )
  4136. if objects_detected:
  4137. # Send notification about plate not empty
  4138. await ws_manager.broadcast(
  4139. {
  4140. "type": "plate_not_empty",
  4141. "printer_id": printer_id,
  4142. "printer_name": printer.name,
  4143. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  4144. }
  4145. )
  4146. # Also send push notification
  4147. try:
  4148. await notification_service.on_plate_not_empty(
  4149. printer_id=printer_id,
  4150. printer_name=printer.name,
  4151. db=db,
  4152. difference_percent=plate_result.difference_percent,
  4153. image_data=plate_photo_data,
  4154. )
  4155. except Exception as notif_err:
  4156. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4157. elif check_failure:
  4158. logger.warning(
  4159. "[PLATE CHECK] Plate check could not run for printer %s (%s): %s; proceeding with print",
  4160. printer_id,
  4161. check_failure,
  4162. plate_result.message,
  4163. )
  4164. await _announce_plate_check_failed(printer_id, printer.name, check_failure)
  4165. else:
  4166. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4167. except Exception as plate_err:
  4168. # Don't block print on plate detection errors
  4169. logger.warning(
  4170. "[PLATE CHECK] Plate check could not run for printer %s: %s; proceeding with print",
  4171. printer_id,
  4172. plate_err,
  4173. )
  4174. await _announce_plate_check_failed(printer_id, printer.name, "error")
  4175. if not printer:
  4176. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4177. if not notification_sent:
  4178. await _send_print_start_notification(printer_id, data, logger=logger)
  4179. return
  4180. # Skip the printer's own jobs — a calibration run is not a user's print.
  4181. # See is_internal_printer_job for what counts and why both fields are
  4182. # tested; the pressure-advance line reports as a subtask name with no
  4183. # /usr/ path, which the old prefix-only test here missed entirely.
  4184. #
  4185. # No notification either. The event describes the printer calibrating
  4186. # itself, so "Print started" is as wrong as the archive was, and the
  4187. # matching completion is suppressed in on_print_complete for the same
  4188. # reason. Checked before the auto-archive switches, whose "off" path
  4189. # still notifies.
  4190. # A /usr/ path is the printer's own file. A name alone is not proof: a
  4191. # print Bambuddy dispatched is never one, whatever it is called.
  4192. # Dispatched = an expected print, or, after a restart that lost those,
  4193. # a queue job printing on the printer.
  4194. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")) and (
  4195. (data.get("filename") or "").startswith("/usr/")
  4196. or not await _dispatched_by_bambuddy(db, printer_id, data.get("filename", ""), data.get("subtask_name", ""))
  4197. ):
  4198. logger.info(
  4199. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4200. data.get("filename", ""),
  4201. data.get("subtask_name", ""),
  4202. )
  4203. return
  4204. # The global switch is the master: off, no printer archives prints
  4205. # started outside Bambuddy; on, each printer's own switch decides.
  4206. from backend.app.api.routes.settings import get_setting
  4207. _global_auto_archive = await get_setting(db, "auto_archive")
  4208. archives_prints = printer.auto_archive and (
  4209. _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4210. )
  4211. if not archives_prints:
  4212. # auto-archive disabled — check if there's an expected print (dispatched
  4213. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4214. # If so, fall through to the expected-print handling below so the archive
  4215. # is tracked in _active_prints and usage tracking works at completion.
  4216. _fn = data.get("filename", "")
  4217. _sn = data.get("subtask_name", "")
  4218. _check_keys: list[tuple[int, str]] = []
  4219. if _sn:
  4220. _check_keys += [
  4221. (printer_id, _sn),
  4222. (printer_id, f"{_sn}.3mf"),
  4223. (printer_id, f"{_sn}.gcode.3mf"),
  4224. ]
  4225. if _fn:
  4226. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4227. _check_keys.append((printer_id, _base_fn))
  4228. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4229. _check_keys += [
  4230. (printer_id, _no_archive_base),
  4231. (printer_id, f"{_no_archive_base}.3mf"),
  4232. ]
  4233. _has_expected = any(k in _expected_prints for k in _check_keys)
  4234. if not _has_expected:
  4235. # No expected print — truly external print (started from slicer/touchscreen)
  4236. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4237. if not notification_sent:
  4238. _no_archive_creator: int | None = None
  4239. for _key in _check_keys:
  4240. _expected_prints.pop(_key, None)
  4241. _expected_print_registered_at.pop(_key, None)
  4242. popped_creator = _expected_print_creators.pop(_key, None)
  4243. if _no_archive_creator is None:
  4244. _no_archive_creator = popped_creator
  4245. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4246. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4247. return
  4248. else:
  4249. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4250. # Get the filename and subtask_name
  4251. filename = data.get("filename", "")
  4252. subtask_name = data.get("subtask_name", "")
  4253. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4254. # present, it lets us match an archive across a backend restart (#972):
  4255. # same id → same print → resume the existing row instead of cancelling
  4256. # it and recreating from scratch (which loses started_at). Treat "0"
  4257. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4258. raw_mqtt = data.get("raw_data") or {}
  4259. subtask_id = raw_mqtt.get("subtask_id")
  4260. if subtask_id is not None:
  4261. subtask_id = str(subtask_id).strip()
  4262. if subtask_id in ("", "0"):
  4263. subtask_id = None
  4264. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4265. if not filename and not subtask_name:
  4266. # Send notification without archive data (no filename)
  4267. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4268. if not notification_sent:
  4269. await _send_print_start_notification(printer_id, data, logger=logger)
  4270. return
  4271. # Check if this is an expected print from reprint/scheduled
  4272. expected_keys = _expected_print_keys(printer_id, filename, subtask_name)
  4273. expected_archive_id = None
  4274. # Who queued it, taken with the entries it was registered beside: left
  4275. # behind once those are gone (the archive deleted mid-dispatch, or the
  4276. # start notification already sent), the expiry never saw it, and an
  4277. # unrelated later print of that name was attributed to that user (EP-2).
  4278. fallback_creator = None
  4279. for key in expected_keys:
  4280. expected_archive_id = _expected_prints.pop(key, None)
  4281. _expected_print_registered_at.pop(key, None)
  4282. if expected_archive_id:
  4283. # Clean up other possible keys for this print
  4284. for other_key in expected_keys:
  4285. _expected_prints.pop(other_key, None)
  4286. _expected_print_registered_at.pop(other_key, None)
  4287. creator = _expected_print_creators.pop(other_key, None)
  4288. if fallback_creator is None:
  4289. fallback_creator = creator
  4290. break
  4291. if expected_archive_id:
  4292. # This is a reprint/scheduled print - use existing archive, don't create new one
  4293. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4294. # Bambuddy dispatched it: the kill switch's fast path keeps it as
  4295. # Bambuddy's once the expected entry is consumed here.
  4296. _owned_print_archive_ids.add(expected_archive_id)
  4297. from backend.app.models.archive import PrintArchive
  4298. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4299. archive = result.scalar_one_or_none()
  4300. # Deleted after this handler loaded it (the plate check waits
  4301. # seconds) but before the route forgot the expected print: the
  4302. # archive the route kept or deleted is left as the route left it.
  4303. if archive and await _printer_gone(db, printer_id):
  4304. logger.info(
  4305. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4306. )
  4307. await forget_printer(printer_id)
  4308. return
  4309. if archive:
  4310. # As it was before this adoption: put back if the printer turns
  4311. # out to have been deleted while it was adopted (below).
  4312. before_adoption = {
  4313. attr.columns[0].name: getattr(archive, attr.key)
  4314. for attr in sa_inspect(PrintArchive).column_attrs
  4315. if attr.key != "id"
  4316. }
  4317. # Update archive status to printing
  4318. archive.status = "printing"
  4319. archive.started_at = datetime.now(timezone.utc)
  4320. # The previous run's outcome is not this one's: a reprint that
  4321. # completes must not keep showing why the last one failed.
  4322. archive.failure_reason = None
  4323. archive.completed_at = None
  4324. # The previous run's answer is still on this row and the
  4325. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4326. # so without a reset the second run inherits the first run's
  4327. # verdict: no prompt at all, and a green "good" badge on a run
  4328. # nobody ever judged.
  4329. if archive.confirm_requested:
  4330. archive.user_verdict = None
  4331. archive.user_verdict_source = None
  4332. archive.user_verdict_at = None
  4333. archive.confirm_token = None
  4334. archive.confirm_token_used_at = None
  4335. # Reprint of an archive reuses the source row. Without resetting
  4336. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4337. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4338. # extracts the *original* print's last frame, which then ships in
  4339. # the completion notification (#1707). Clear the path so the
  4340. # scanner runs fresh; also unlink the old video file so reprints
  4341. # don't accumulate orphans in the archive directory. Photos list
  4342. # is left alone — accumulating one finish photo per run is fine.
  4343. # The print-start baseline (#2704) is stale for the same reason:
  4344. # it describes the printer before the previous run. The capture
  4345. # below overwrites it, but clear it here too so an early failure
  4346. # can't leave the scan diffing against the wrong snapshot.
  4347. #
  4348. # Unlinked only when it is the same plate printing again. Every
  4349. # plate of a Send All shares this archive, and the video on it
  4350. # can be the only copy of another plate's run -- the printer's
  4351. # was deleted once it attached (#3275). That one is left in the
  4352. # archive directory, which goes with the archive. A video whose
  4353. # plate is not on record (attached by hand, or before the
  4354. # column existed) is kept too where the 3MF has other plates,
  4355. # or cannot be read: nothing tells it apart from another plate's,
  4356. # and keeping costs one file where deleting can cost the only
  4357. # copy. On an archive with exactly one plate it is that plate's.
  4358. archive.timelapse_baseline = None
  4359. stale_timelapse_relpath = archive.timelapse_path
  4360. stale_timelapse_plate_id = archive.timelapse_plate_id
  4361. starting_plate_id = _print_plate_ids.get(expected_archive_id)
  4362. if stale_timelapse_relpath:
  4363. archive.timelapse_path = None
  4364. archive.timelapse_plate_id = None
  4365. stale_is_this_plates = stale_timelapse_plate_id == starting_plate_id
  4366. if stale_timelapse_relpath and stale_timelapse_plate_id is None and archive.file_path:
  4367. from backend.app.services.archive import plate_indexes_in_3mf
  4368. plates = await asyncio.to_thread(
  4369. plate_indexes_in_3mf,
  4370. app_settings.base_dir / archive.file_path, # SEC-PATH-OK: stored relative archive path
  4371. )
  4372. stale_is_this_plates = len(plates) == 1
  4373. if stale_timelapse_relpath and not stale_is_this_plates:
  4374. logger.info(
  4375. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4376. stale_timelapse_relpath,
  4377. stale_timelapse_plate_id,
  4378. expected_archive_id,
  4379. starting_plate_id,
  4380. )
  4381. # The video is deleted once the adoption stands (below).
  4382. delete_stale_video = bool(stale_timelapse_relpath) and stale_is_this_plates
  4383. # Persist a restart-stable id so a later restart resumes this
  4384. # archive by subtask_id instead of name-matching + duplicating
  4385. # it (#1485). The printer often hasn't echoed subtask_id back
  4386. # this soon after dispatch, so fall back to the id Bambuddy
  4387. # minted when it sent the print command. Scoped to this
  4388. # expected-print branch on purpose: an expected match means
  4389. # Bambuddy dispatched this exact print in this process, so the
  4390. # client's last-dispatch id genuinely belongs to it — using it
  4391. # for an externally-started print could mis-tag the archive.
  4392. effective_subtask_id = subtask_id
  4393. if not effective_subtask_id:
  4394. _client = printer_manager.get_client(printer_id)
  4395. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4396. if _dispatched:
  4397. effective_subtask_id = str(_dispatched).strip() or None
  4398. # Update on first-set OR on reprint (the queue dispatcher mints
  4399. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4400. # the rewrite for reprints leaves the archive holding the FIRST
  4401. # run's id; if MQTT then reconnects mid-print, the reconciler
  4402. # (#1542) compares the stale stored id against the printer's
  4403. # live id, sees a mismatch, and synthesises a bogus PRINT
  4404. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4405. # in #1807. Inequality check preserves the noop-on-stable-push
  4406. # behaviour the earlier `not archive.subtask_id` guard provided.
  4407. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4408. archive.subtask_id = effective_subtask_id
  4409. # #1403 follow-up: VP-queue archives are created with
  4410. # printer_id=None at queue-add time (we don't know which
  4411. # printer will run the job yet). When the print actually
  4412. # starts on a specific printer the expected-archive lookup
  4413. # used to skip this assignment, leaving printer_id=None
  4414. # forever — which then disables the "Scan for timelapse"
  4415. # button in ArchivesPage (gated on !archive.printer_id).
  4416. if archive.printer_id != printer_id:
  4417. archive.printer_id = printer_id
  4418. adopting_id = archive.id # a rollback expires the object
  4419. try:
  4420. await db.commit()
  4421. except (IntegrityError, StaleDataError):
  4422. # The archive stays unchanged, or is gone: "delete archives"
  4423. # removed the row under the adoption, which then matched no
  4424. # row (StaleDataError) rather than being refused.
  4425. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4426. return
  4427. raise
  4428. # The printer can be deleted between the check above and this
  4429. # commit (the route's transaction lasts seconds), and the commit
  4430. # then adopted the archive anyway: status, verdict and timelapse
  4431. # changed, and the deleted printer's id written on a row the
  4432. # route had detached or never touched. Undo the adoption.
  4433. if await _printer_gone(db, printer_id):
  4434. logger.info(
  4435. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4436. printer_id,
  4437. archive.id,
  4438. )
  4439. # Everything as before this adoption. The printer it had
  4440. # then stays, unless it was the deleted one: the route
  4441. # detached that row (kept) or deleted it (no row matches).
  4442. previous_printer = before_adoption["printer_id"]
  4443. await db.execute(
  4444. update(PrintArchive)
  4445. .where(PrintArchive.id == archive.id)
  4446. .values(
  4447. {
  4448. **before_adoption,
  4449. "printer_id": None if previous_printer == printer_id else previous_printer,
  4450. }
  4451. )
  4452. )
  4453. await db.commit()
  4454. await forget_printer(printer_id)
  4455. return
  4456. if delete_stale_video and stale_timelapse_relpath:
  4457. try:
  4458. stale_path = app_settings.base_dir / stale_timelapse_relpath
  4459. if stale_path.is_file():
  4460. stale_path.unlink()
  4461. logger.info(
  4462. "Deleted stale timelapse %s on reprint of archive %s",
  4463. stale_timelapse_relpath,
  4464. expected_archive_id,
  4465. )
  4466. except OSError as e:
  4467. logger.warning(
  4468. "Failed to delete stale timelapse %s on reprint: %s",
  4469. stale_timelapse_relpath,
  4470. e,
  4471. )
  4472. # Track as active print
  4473. _bind_active_print(printer_id, archive.id, archive.filename, filename, subtask_name)
  4474. # Start timelapse session if external camera is enabled (#1353).
  4475. # Queue / VP-dispatched prints land here in the expected-archive
  4476. # branch and used to skip start_session entirely — frames were
  4477. # never captured and the post-print stitch silently returned None.
  4478. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4479. # Inject ams_mapping into usage tracker session — the session was created
  4480. # before expected-print promotion, so it may have ams_mapping=None when
  4481. # the MQTT request topic subscription failed (common on P1S/A1).
  4482. _stored_map = _print_ams_mappings.get(expected_archive_id)
  4483. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  4484. if _stored_map or _stored_plate_id is not None:
  4485. try:
  4486. from backend.app.services.usage_tracker import _active_sessions
  4487. _ut_session = _active_sessions.get(printer_id)
  4488. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4489. _ut_session.ams_mapping = _stored_map
  4490. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4491. # plate_id injection covers direct-Print of plate N of a multi-plate
  4492. # 3MF — queue prints already capture it via the on_print_start queue
  4493. # lookup, but direct-Print never goes through the queue (#1697).
  4494. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4495. _ut_session.plate_id = _stored_plate_id
  4496. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4497. except Exception:
  4498. pass
  4499. # Set up energy tracking (#941: persist start on archive row)
  4500. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4501. await ws_manager.send_archive_updated(
  4502. {
  4503. "id": archive.id,
  4504. "status": "printing",
  4505. }
  4506. )
  4507. # Send notification with archive data (reprint/scheduled)
  4508. if not notification_sent:
  4509. # Use archive's created_by_id; fall back to the creator registered via
  4510. # register_expected_print (handles library-file-based queue items where
  4511. # the freshly-created archive has no created_by_id yet), taken above.
  4512. archive_data = {
  4513. "print_time_seconds": archive.print_time_seconds,
  4514. "created_by_id": archive.created_by_id or fallback_creator,
  4515. }
  4516. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4517. # Extract printable objects from the archived 3MF file
  4518. _load_objects_from_archive(archive, printer_id, logger)
  4519. # Store Spoolman tracking data for per-filament usage reporting
  4520. try:
  4521. await _store_spoolman_print_data(
  4522. printer_id,
  4523. archive.id,
  4524. archive.file_path,
  4525. db,
  4526. printer_manager,
  4527. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4528. plate_id=_get_start_plate_id(archive.id),
  4529. )
  4530. except Exception as e:
  4531. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4532. # Price the print from its spools now rather than only at completion (#3261)
  4533. _schedule_archive_cost_estimate(
  4534. printer_id,
  4535. archive.id,
  4536. printer_manager,
  4537. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4538. plate_id=_get_start_plate_id(archive.id),
  4539. session_factory=async_session,
  4540. )
  4541. # Capture timelapse file baseline for snapshot-diff on completion
  4542. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4543. # hit this branch — without the baseline the completion-time scan
  4544. # falls into its "take baseline now" fallback, which snapshots
  4545. # AFTER the new MP4 already exists and never matches a diff
  4546. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4547. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4548. await _forget_if_printer_gone(printer_id)
  4549. return # Skip creating a new archive
  4550. # The archive was deleted after the job was queued.
  4551. if not archives_prints:
  4552. # Only the expected print brought a printer that does not
  4553. # archive this far; with it gone, nothing is archived.
  4554. return
  4555. # Otherwise archive the print anew rather than drop it, so it still
  4556. # gets its notification, usage tracking and history.
  4557. logger.warning(
  4558. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4559. expected_archive_id,
  4560. printer_id,
  4561. )
  4562. # Check if there's already a "printing" archive for this printer/file
  4563. # This prevents duplicates when backend restarts during an active print
  4564. from backend.app.models.archive import PrintArchive
  4565. existing_archive: PrintArchive | None = None
  4566. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4567. # across a backend restart for the same print, so this is the most
  4568. # reliable way to reattach. Only a row still printing: a cancelled one
  4569. # has been through completion (usage, history, notifications) already,
  4570. # and reopening it would count the print twice.
  4571. if subtask_id:
  4572. by_id = await db.execute(
  4573. select(PrintArchive)
  4574. .where(PrintArchive.printer_id == printer_id)
  4575. .where(PrintArchive.subtask_id == subtask_id)
  4576. .where(PrintArchive.status == "printing")
  4577. .order_by(PrintArchive.created_at.desc())
  4578. .limit(1)
  4579. )
  4580. existing_archive = by_id.scalar_one_or_none()
  4581. # Fallback match: name-based lookup. Kept as-is for prints whose
  4582. # subtask_id is missing ("0" / local / non-cloud prints).
  4583. if existing_archive is None:
  4584. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4585. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4586. # A print started from the printer's screen names its file in full,
  4587. # so the forms above double its extension. The file itself is the
  4588. # one exact match, and nothing looser is added (#3009).
  4589. if _subtask_is_the_file(subtask_name, filename):
  4590. archive_filenames.append(subtask_name)
  4591. existing = await db.execute(
  4592. select(PrintArchive)
  4593. .where(PrintArchive.printer_id == printer_id)
  4594. .where(PrintArchive.status == "printing")
  4595. .where(
  4596. or_(
  4597. PrintArchive.print_name == check_name,
  4598. PrintArchive.filename.in_(archive_filenames),
  4599. )
  4600. )
  4601. .order_by(PrintArchive.created_at.desc())
  4602. .limit(1)
  4603. )
  4604. existing_archive = existing.scalar_one_or_none()
  4605. if existing_archive:
  4606. # subtask_id match → always resume, regardless of age. Same print,
  4607. # just a backend restart.
  4608. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4609. if subtask_match:
  4610. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4611. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4612. _mark_owned_if_dispatched(existing_archive)
  4613. if existing_archive.energy_start_kwh is None:
  4614. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4615. if not notification_sent:
  4616. archive_data = {
  4617. "print_time_seconds": existing_archive.print_time_seconds,
  4618. "created_by_id": existing_archive.created_by_id,
  4619. }
  4620. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4621. _load_objects_from_archive(existing_archive, printer_id, logger)
  4622. return
  4623. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4624. # stale from the printer's *current* progress, not wall-clock age.
  4625. # A genuinely long print used to trip a blind 4h cutoff and have its
  4626. # live archive cancelled + duplicated on every backend restart
  4627. # (#1485). If the printer reports real progress, this name-matched
  4628. # 'printing' archive IS that ongoing print — resume it whatever its
  4629. # age. Only treat it as a stale leftover when the printer clearly
  4630. # shows a different, freshly-started print: near-0% progress on an
  4631. # archive far too old to still be at 0%. Unknown progress (printer
  4632. # not connected) never cancels — resuming is the safe default.
  4633. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4634. live_status = printer_manager.get_status(printer_id)
  4635. live_progress = getattr(live_status, "progress", None) if live_status else None
  4636. looks_stale = (
  4637. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4638. )
  4639. # Two subtask ids are two prints, however young the archive: one
  4640. # whose completion was missed must not swallow the next print of
  4641. # the same file. Except Bambuddy's own reprint, which reuses the
  4642. # row and mints a fresh id (#1807): the id it last sent says so,
  4643. # and after a restart, which forgets it, this printer's queue job
  4644. # running the archive.
  4645. if (
  4646. not looks_stale
  4647. and subtask_id
  4648. and existing_archive.subtask_id
  4649. and existing_archive.subtask_id != subtask_id
  4650. ):
  4651. _client = printer_manager.get_client(printer_id)
  4652. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  4653. if _dispatched:
  4654. looks_stale = _dispatched != subtask_id
  4655. else:
  4656. from backend.app.models.print_queue import PrintQueueItem as _PQI
  4657. queue_run = await db.scalar(
  4658. select(_PQI.id)
  4659. .where(_PQI.archive_id == existing_archive.id)
  4660. .where(_PQI.printer_id == printer_id)
  4661. .where(_PQI.status == "printing")
  4662. .limit(1)
  4663. )
  4664. looks_stale = queue_run is None
  4665. if looks_stale:
  4666. logger.warning(
  4667. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  4668. " — marking cancelled and creating new archive",
  4669. existing_archive.id,
  4670. archive_age,
  4671. live_progress,
  4672. existing_archive.subtask_id,
  4673. subtask_id,
  4674. )
  4675. existing_archive.status = "cancelled"
  4676. # Canonical key, not a sentence (issue #2974). "No status update
  4677. # received" is what both stale paths actually observed; which of
  4678. # the two it was is already carried by ``status`` -- cancelled
  4679. # here, the reconciled outcome at the reconnect site -- so one
  4680. # key loses no information and gives the Statistics breakdown a
  4681. # single bucket instead of two untranslatable prose strings.
  4682. existing_archive.failure_reason = "noStatusUpdate"
  4683. await db.commit()
  4684. # Its print keys go with it; the new archive registers its own.
  4685. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id]:
  4686. del _active_prints[_key]
  4687. # Fall through to create new archive (don't return)
  4688. else:
  4689. logger.info(
  4690. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4691. )
  4692. # Track this as the active print
  4693. _bind_active_print(printer_id, existing_archive.id, existing_archive.filename, filename, subtask_name)
  4694. _mark_owned_if_dispatched(existing_archive)
  4695. # Attach subtask_id retroactively so future restarts can resume.
  4696. # Compare for inequality (not "is empty") to also pick up reprint
  4697. # dispatches that mint a fresh id — see #1807 for the bogus
  4698. # "Print Stopped" the strict-empty guard caused on reconnect.
  4699. if subtask_id and existing_archive.subtask_id != subtask_id:
  4700. existing_archive.subtask_id = subtask_id
  4701. await db.commit()
  4702. # Also set up energy tracking if not already tracked (#941: persisted column)
  4703. if existing_archive.energy_start_kwh is None:
  4704. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4705. # Send notification with archive data (existing archive)
  4706. if not notification_sent:
  4707. archive_data = {
  4708. "print_time_seconds": existing_archive.print_time_seconds,
  4709. "created_by_id": existing_archive.created_by_id,
  4710. }
  4711. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4712. # Extract printable objects from the archived 3MF file
  4713. _load_objects_from_archive(existing_archive, printer_id, logger)
  4714. return
  4715. # Build list of possible 3MF filenames to try
  4716. possible_names = []
  4717. # Bambu printers typically store files as "Name.gcode.3mf"
  4718. # The subtask_name is usually the best source for the filename
  4719. if subtask_name:
  4720. if _subtask_is_the_file(subtask_name, filename):
  4721. # A print started from the printer's own screen reports the
  4722. # file's full name, extension included. That is the file, so
  4723. # no extension is appended to it (#3009).
  4724. possible_names.append(subtask_name)
  4725. else:
  4726. # Try common Bambu naming patterns
  4727. possible_names.append(f"{subtask_name}.gcode.3mf")
  4728. possible_names.append(f"{subtask_name}.3mf")
  4729. # Try original filename with .3mf extension
  4730. if filename:
  4731. # Extract just the filename part, not the full path
  4732. fname = filename.split("/")[-1] if "/" in filename else filename
  4733. if fname.endswith(".3mf"):
  4734. possible_names.append(fname)
  4735. elif fname.endswith(".gcode"):
  4736. base = fname.rsplit(".", 1)[0]
  4737. possible_names.append(f"{base}.gcode.3mf")
  4738. possible_names.append(f"{base}.3mf")
  4739. else:
  4740. possible_names.append(f"{fname}.gcode.3mf")
  4741. possible_names.append(f"{fname}.3mf")
  4742. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4743. space_variants = []
  4744. for name in possible_names:
  4745. if " " in name:
  4746. space_variants.append(name.replace(" ", "_"))
  4747. possible_names.extend(space_variants)
  4748. # Remove duplicates while preserving order
  4749. seen = set()
  4750. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4751. logger.info("Trying filenames: %s", possible_names)
  4752. # Release the pooled DB connection before the 3MF FTP download. Reaching
  4753. # here means none of the expected-/existing-archive write branches ran
  4754. # (they all return earlier) — only SELECTs have executed on this path, so
  4755. # this commit persists nothing; it ends the read transaction so the
  4756. # connection returns to the pool during the download. That download tries
  4757. # up to five remote paths per candidate filename with retry/backoff and
  4758. # can run for minutes under FTP contention; holding the session across it
  4759. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  4760. # work runs during the download — the new-archive writes below re-acquire
  4761. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  4762. await db.commit()
  4763. # Try to find and download the 3MF file
  4764. temp_path = None
  4765. downloaded_filename = None
  4766. # Cache check: cover endpoint may have already pulled this 3MF during
  4767. # the print (frontend opens the card and shows the thumbnail) — reuse
  4768. # that file instead of re-downloading 36MB over the same FTP link that
  4769. # just served it (#972). The cache keys on a normalized filename so
  4770. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  4771. for try_filename in possible_names:
  4772. if not try_filename.endswith(".3mf"):
  4773. continue
  4774. cached = get_cached_3mf(printer_id, try_filename)
  4775. if cached:
  4776. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  4777. temp_path = cached
  4778. downloaded_filename = try_filename
  4779. break
  4780. # Does this printer keep the sliced file somewhere FTPS can reach? On
  4781. # H2-series and P2S the answer is routinely no — the file stays on
  4782. # internal eMMC and port 990 only ever serves external storage — and
  4783. # then the whole sweep below (six filenames x five directories x four
  4784. # retries, then the directory walk) is ~110 connections that cannot
  4785. # succeed. Skip it and say why (#2780).
  4786. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  4787. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  4788. # running rather than because the file is somewhere unreachable. The
  4789. # distinction is the whole of #2957: one is permanent, the other clears
  4790. # in minutes with the file still sitting on the printer.
  4791. blocked_by_ftps_cooloff = False
  4792. # Set when a probe reached the printer and still came back without the
  4793. # file -- a timeout mid-transfer, a refused connection, anything that is
  4794. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  4795. # caught by name below, so a file that genuinely is not on the card
  4796. # leaves this False and schedules nothing. Anything else means the
  4797. # transfer, not the file, is what failed, and that does not last (#3063).
  4798. ftp_transfer_failed = False
  4799. # The narrower case of the above: the directory walk *listed* a file
  4800. # for this print and could not fetch it, so the file is on the card
  4801. # under a name that matches. The only failure that rules out an
  4802. # earlier run's 3MF standing in for it (#3307).
  4803. walk_transfer_failed = False
  4804. # Paths the sweep reached and could not transfer -- a timeout, not a
  4805. # 550. The directory walk lists the same folders and would download
  4806. # the same file again: on a slow A1 that was a second 300 s on the
  4807. # printer's one FTPS slot, at print start, for a file the recovery
  4808. # retry fetches with a deadline twice as long (#3308).
  4809. sweep_failed_paths: set[str] = set()
  4810. # The print's name, for a fallback archive whose `subtask_name` the
  4811. # plate guard below had to disown. Display only, and deliberately kept
  4812. # apart from `subtask_name`: that variable is what every file lookup
  4813. # here is built from, and once a name has been shown to fetch another
  4814. # plate's 3MF it must not key `_active_prints` either, or the cover
  4815. # endpoint hands the same contradicted file to
  4816. # `_recover_fallback_archive` and fills the row in with it (#3126).
  4817. display_name_after_plate_reject: str | None = None
  4818. # Get FTP retry settings
  4819. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  4820. # ...but "the printer put it on eMMC" is where it went, not whether we
  4821. # can read it. An H2D with a card in mirrors the job to /cache and
  4822. # serves it happily, and skipping on the URL alone cost that reporter
  4823. # every archive for two days (#2856). So ask the printer instead of
  4824. # guessing: the dispatch named the exact file, which is one connection
  4825. # walking five paths rather than the sweep's ~110. Only when the probe
  4826. # comes back empty does the verdict's reason stand.
  4827. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  4828. if ftps_handshake_blocked(printer.ip_address):
  4829. # Deliberately NOT recorded as a cool-off give-up. This branch
  4830. # only runs on an unreachable verdict, and that verdict is the
  4831. # honest, permanent reason the archive is empty — the probe was
  4832. # a long shot on top of it. Blaming the cool-off here would
  4833. # schedule a retry for a file sitting on internal eMMC, which is
  4834. # the sweep #2780 removed (#2957).
  4835. logger.debug(
  4836. "Not probing for %s on printer %s: its file service is not answering over TLS",
  4837. storage.probe_filename,
  4838. printer_id,
  4839. )
  4840. else:
  4841. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  4842. probe_path.parent.mkdir(parents=True, exist_ok=True)
  4843. try:
  4844. probe_hit = await download_file_try_paths_async(
  4845. printer.ip_address,
  4846. printer.access_code,
  4847. ftp_probe_paths(storage.probe_filename),
  4848. probe_path,
  4849. socket_timeout=ftp_timeout,
  4850. printer_model=printer.model,
  4851. )
  4852. except Exception as e:
  4853. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  4854. probe_hit = False
  4855. if probe_hit:
  4856. downloaded_filename = storage.probe_filename
  4857. temp_path = probe_path
  4858. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  4859. # Naming the path, not just the file: a printer that keeps
  4860. # uploads around for weeks can serve a same-named copy of an
  4861. # earlier slice, and without the directory in the log that
  4862. # mismatch is invisible rather than merely rare (#1820).
  4863. logger.info(
  4864. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  4865. downloaded_filename,
  4866. probe_hit,
  4867. printer_id,
  4868. storage.reason,
  4869. )
  4870. if not storage.reachable and not downloaded_filename:
  4871. # Same opening words whether or not a probe ran, because that is
  4872. # the phrase support asks people to grep for — only the tail says
  4873. # which of the two happened.
  4874. logger.info(
  4875. "Skipping the 3MF lookup for printer %s: %s — %s",
  4876. printer_id,
  4877. storage.reason,
  4878. "no copy of it on external storage either"
  4879. if storage.probe_filename
  4880. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  4881. )
  4882. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  4883. if not try_filename.endswith(".3mf"):
  4884. continue
  4885. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  4886. # printers, so try it first — deferring it to last cost #972's reporter
  4887. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  4888. # landing on the path that actually had the file.
  4889. remote_paths = [
  4890. f"/{try_filename}",
  4891. f"/cache/{try_filename}",
  4892. f"/model/{try_filename}",
  4893. f"/data/{try_filename}",
  4894. f"/data/Metadata/{try_filename}",
  4895. ]
  4896. temp_path = app_settings.archive_dir / "temp" / try_filename
  4897. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4898. for remote_path in remote_paths:
  4899. if ftps_handshake_blocked(printer.ip_address):
  4900. # The printer's FTPS service is not completing a TLS
  4901. # handshake, so it has no path we could reach — walking the
  4902. # remaining candidates only re-runs the same failure
  4903. # (#2780). Fall through to the no-3MF archive now.
  4904. #
  4905. # Remember *why*, though. This is the one give-up that is
  4906. # temporary: the cool-off clears in minutes and the file was
  4907. # on the printer the whole time. The fallback archive is
  4908. # stamped with it so a retry can be scheduled, and so the
  4909. # Archives banner stops blaming storage (#2957).
  4910. blocked_by_ftps_cooloff = True
  4911. logger.warning(
  4912. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  4913. printer_id,
  4914. )
  4915. break
  4916. logger.debug("Trying FTP download: %s", remote_path)
  4917. try:
  4918. if ftp_retry_enabled:
  4919. downloaded = await with_ftp_retry(
  4920. download_file_async,
  4921. printer.ip_address,
  4922. printer.access_code,
  4923. remote_path,
  4924. temp_path,
  4925. timeout=ftp_timeout,
  4926. socket_timeout=ftp_timeout,
  4927. printer_model=printer.model,
  4928. max_retries=ftp_retry_count,
  4929. retry_delay=ftp_retry_delay,
  4930. operation_name=f"Download 3MF from {remote_path}",
  4931. cooloff_ip=printer.ip_address,
  4932. non_retry_exceptions=(FileNotOnPrinterError,),
  4933. )
  4934. else:
  4935. downloaded = await download_file_async(
  4936. printer.ip_address,
  4937. printer.access_code,
  4938. remote_path,
  4939. temp_path,
  4940. timeout=ftp_timeout,
  4941. socket_timeout=ftp_timeout,
  4942. printer_model=printer.model,
  4943. )
  4944. if downloaded:
  4945. downloaded_filename = try_filename
  4946. logger.info("Downloaded: %s", remote_path)
  4947. # Populate shared cache so the cover endpoint (if it
  4948. # runs next) doesn't refetch the same 36MB over FTP.
  4949. cache_3mf_download(printer_id, try_filename, temp_path)
  4950. break
  4951. # with_ftp_retry returns None once it has spent its budget,
  4952. # and download_file_async returns False on a timeout, so an
  4953. # exhausted transfer arrives here rather than as an
  4954. # exception (#3063).
  4955. ftp_transfer_failed = True
  4956. sweep_failed_paths.add(remote_path)
  4957. except FileNotOnPrinterError:
  4958. # 550 — file isn't at this path. Advance to next candidate
  4959. # without burning the retry budget.
  4960. logger.debug("3MF not at %s (550), trying next path", remote_path)
  4961. except Exception as e:
  4962. ftp_transfer_failed = True
  4963. sweep_failed_paths.add(remote_path)
  4964. logger.debug("FTP download failed for %s: %s", remote_path, e)
  4965. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  4966. break
  4967. # If still not found, try listing directories to find matching file
  4968. # Different printer models use different directory structures. Skipped
  4969. # when the printer's FTPS handshake is failing — the directory walk is
  4970. # five more connections that cannot get further than the download did.
  4971. if (
  4972. not downloaded_filename
  4973. and storage.reachable
  4974. and (filename or subtask_name)
  4975. and not ftps_handshake_blocked(printer.ip_address)
  4976. ):
  4977. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  4978. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  4979. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  4980. # Every folder is listed before one file is picked, so a file named
  4981. # for the print in a later folder wins over one that merely
  4982. # contains the name in an earlier folder.
  4983. listed_paths: list[str] = []
  4984. for search_dir in search_dirs:
  4985. try:
  4986. dir_files = await list_files_async(
  4987. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  4988. )
  4989. except Exception as e:
  4990. logger.debug("Failed to list %s: %s", search_dir, e)
  4991. continue
  4992. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  4993. if threemf_files:
  4994. logger.info(
  4995. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  4996. )
  4997. listed_paths += [
  4998. posixpath.join(search_dir, f.get("name", "")) for f in dir_files if not f.get("is_directory")
  4999. ]
  5000. for remote_full_path in _3mf_files_for_print(listed_paths, search_term):
  5001. if remote_full_path in sweep_failed_paths:
  5002. # Listed for this print, and its transfer already failed:
  5003. # the same as a failed walk download, without spending a
  5004. # second deadline on it. Skipping it cannot hand the walk a
  5005. # look-alike: while a file of the print's own name is
  5006. # listed, files that merely contain the name are not.
  5007. logger.info(
  5008. "Not downloading %s again: its transfer already failed; the recovery retry will fetch it",
  5009. remote_full_path,
  5010. )
  5011. walk_transfer_failed = True
  5012. continue
  5013. fname = posixpath.basename(remote_full_path)
  5014. logger.info("Found matching file: %s", remote_full_path)
  5015. temp_path = app_settings.archive_dir / "temp" / fname
  5016. temp_path.parent.mkdir(parents=True, exist_ok=True)
  5017. try:
  5018. if ftp_retry_enabled:
  5019. downloaded = await with_ftp_retry(
  5020. download_file_async,
  5021. printer.ip_address,
  5022. printer.access_code,
  5023. remote_full_path,
  5024. temp_path,
  5025. timeout=ftp_timeout,
  5026. socket_timeout=ftp_timeout,
  5027. printer_model=printer.model,
  5028. max_retries=ftp_retry_count,
  5029. retry_delay=ftp_retry_delay,
  5030. operation_name=f"Download 3MF from {remote_full_path}",
  5031. cooloff_ip=printer.ip_address,
  5032. )
  5033. else:
  5034. downloaded = await download_file_async(
  5035. printer.ip_address,
  5036. printer.access_code,
  5037. remote_full_path,
  5038. temp_path,
  5039. timeout=ftp_timeout,
  5040. socket_timeout=ftp_timeout,
  5041. printer_model=printer.model,
  5042. )
  5043. except Exception as e:
  5044. logger.debug("Failed to download %s: %s", remote_full_path, e)
  5045. continue
  5046. if downloaded:
  5047. downloaded_filename = fname
  5048. logger.info("Found and downloaded: %s", remote_full_path)
  5049. cache_3mf_download(printer_id, fname, temp_path)
  5050. break
  5051. # The listing named the file, so it is on the card;
  5052. # only the transfer failed (#3063).
  5053. ftp_transfer_failed = True
  5054. walk_transfer_failed = True
  5055. # A "Print again" on the printer's screen names no file Bambuddy can
  5056. # find: only its history copy under a generic name, and the 3MF's
  5057. # internal title (#3307). When an earlier run of the same job was
  5058. # archived, its 3MF is the one being printed again. Not when the
  5059. # directory walk listed a file for this print and only its transfer
  5060. # failed: that file is on the card, and the retry fetches it. A
  5061. # cool-off or a failed sweep path is no such evidence -- the retry
  5062. # tries the same names, which this print's file never had.
  5063. reused_3mf_from: int | None = None
  5064. if not downloaded_filename and not walk_transfer_failed:
  5065. reported_layers = raw_mqtt.get("total_layer_num")
  5066. earlier = await _archived_3mf_for_repeat(
  5067. db,
  5068. printer_id,
  5069. subtask_name,
  5070. filename,
  5071. reported_layers if isinstance(reported_layers, int) and reported_layers > 0 else None,
  5072. )
  5073. if earlier is not None:
  5074. reuse_name = Path(earlier.filename or "").name or f"archive_{earlier.id}.3mf"
  5075. # Per printer: two printers reprinting the same job at once
  5076. # must not write one temp file (archive_print names the
  5077. # archive after original_filename, not this path).
  5078. reuse_path = app_settings.archive_dir / "temp" / f"reprint_{printer_id}_{reuse_name}"
  5079. try:
  5080. reuse_path.parent.mkdir(parents=True, exist_ok=True)
  5081. await asyncio.to_thread(shutil.copyfile, app_settings.base_dir / earlier.file_path, reuse_path)
  5082. except OSError as e:
  5083. # A copy that fails leaves the print the fallback archive
  5084. # it would have had, not no archive at all.
  5085. logger.warning("Could not copy the 3MF of archive %s for printer %s: %s", earlier.id, printer_id, e)
  5086. else:
  5087. temp_path = reuse_path
  5088. downloaded_filename = reuse_name
  5089. reused_3mf_from = earlier.id
  5090. cache_3mf_download(printer_id, reuse_name, temp_path)
  5091. logger.info(
  5092. "No 3MF on printer %s for %s (%s); using the 3MF of archive %s, an earlier run of the same job",
  5093. printer_id,
  5094. subtask_name,
  5095. filename,
  5096. earlier.id,
  5097. )
  5098. # Validate the downloaded 3MF actually matches the plate that's running
  5099. # (#1204): subtask_name lags across consecutive plates of the same model,
  5100. # so the first FTP candidate (built from subtask_name) can land on the
  5101. # previous plate's still-resident upload. Cross-check the slice_info
  5102. # plate index against the plate parsed from gcode_file (always fresh —
  5103. # it's the field whose change triggered this callback).
  5104. if downloaded_filename and temp_path:
  5105. expected_plate = parse_plate_id(filename)
  5106. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  5107. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  5108. logger.warning(
  5109. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  5110. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  5111. downloaded_filename,
  5112. actual_plate,
  5113. expected_plate,
  5114. subtask_name,
  5115. )
  5116. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  5117. retry_succeeded = False
  5118. if corrected_subtask and corrected_subtask != subtask_name:
  5119. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  5120. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  5121. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  5122. for remote_path in (
  5123. f"/{try_filename}",
  5124. f"/cache/{try_filename}",
  5125. f"/model/{try_filename}",
  5126. f"/data/{try_filename}",
  5127. f"/data/Metadata/{try_filename}",
  5128. ):
  5129. try:
  5130. if ftp_retry_enabled:
  5131. downloaded = await with_ftp_retry(
  5132. download_file_async,
  5133. printer.ip_address,
  5134. printer.access_code,
  5135. remote_path,
  5136. retry_temp_path,
  5137. timeout=ftp_timeout,
  5138. socket_timeout=ftp_timeout,
  5139. printer_model=printer.model,
  5140. max_retries=ftp_retry_count,
  5141. retry_delay=ftp_retry_delay,
  5142. operation_name=f"Re-download 3MF from {remote_path}",
  5143. cooloff_ip=printer.ip_address,
  5144. non_retry_exceptions=(FileNotOnPrinterError,),
  5145. )
  5146. else:
  5147. downloaded = await download_file_async(
  5148. printer.ip_address,
  5149. printer.access_code,
  5150. remote_path,
  5151. retry_temp_path,
  5152. timeout=ftp_timeout,
  5153. socket_timeout=ftp_timeout,
  5154. printer_model=printer.model,
  5155. )
  5156. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  5157. logger.info(
  5158. "[CALLBACK] Re-download succeeded with corrected name %s "
  5159. "(plate %s) — replacing wrong file",
  5160. try_filename,
  5161. expected_plate,
  5162. )
  5163. try:
  5164. temp_path.unlink(missing_ok=True)
  5165. except OSError:
  5166. pass
  5167. temp_path = retry_temp_path
  5168. downloaded_filename = try_filename
  5169. subtask_name = corrected_subtask
  5170. cache_3mf_download(printer_id, try_filename, temp_path)
  5171. retry_succeeded = True
  5172. break
  5173. elif downloaded:
  5174. # Wrong plate again — discard and keep trying
  5175. try:
  5176. retry_temp_path.unlink(missing_ok=True)
  5177. except OSError:
  5178. pass
  5179. except FileNotOnPrinterError:
  5180. continue
  5181. except Exception as e:
  5182. logger.debug("Re-download failed for %s: %s", remote_path, e)
  5183. if retry_succeeded:
  5184. break
  5185. # If the retry didn't find a matching file, drop the wrong 3MF
  5186. # so the no-3MF fallback below creates an archive whose name
  5187. # at least reflects the right plate.
  5188. if not retry_succeeded:
  5189. logger.warning(
  5190. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  5191. expected_plate,
  5192. )
  5193. try:
  5194. temp_path.unlink(missing_ok=True)
  5195. except OSError:
  5196. pass
  5197. temp_path = None
  5198. downloaded_filename = None
  5199. # Whatever the sweep's transport did earlier, it is not why
  5200. # this archive ends up empty: a 3MF downloaded fine, it was
  5201. # just the wrong plate. Retrying would re-fetch that same
  5202. # contradicted file under the same stale names and hand it
  5203. # to _recover_fallback_archive, which checks that a
  5204. # candidate is a readable 3MF but not which plate it is --
  5205. # so the row would be filled in with another plate's
  5206. # filament and cost, the exact swap #2957 removed (#3063).
  5207. ftp_transfer_failed = False
  5208. # Disown the name for *lookups*: it has just been shown to
  5209. # fetch another plate's 3MF, and it keys `_active_prints`
  5210. # below, where the cover endpoint's own download of that
  5211. # same name would find this archive and fill it in with the
  5212. # file we are discarding here.
  5213. #
  5214. # Keep it for the *title*, which is a separate question.
  5215. # ``swap_plate_suffix`` returns None both for a name that
  5216. # carries no "- Plate N" / "_plate_N" suffix and for no
  5217. # name at all, and those are not the same situation: a name
  5218. # without a suffix holds no stale plate number to be wrong
  5219. # about. Blanking both uses at once dropped the project
  5220. # name too, and the row fell through to the gcode_file path
  5221. # titled "plate_1" though the real name was in hand.
  5222. # #1204's own premise is consecutive plates *of the same
  5223. # model*, so the project part is right either way (#3126).
  5224. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  5225. subtask_name = corrected_subtask or ""
  5226. # Deleted while the 3MF was being fetched (that can take minutes): no
  5227. # archive, timelapse or tracking for a printer that will never report
  5228. # the print's end. forget_printer again: the download registered its
  5229. # 3MF cache entry after the delete cleared the id. (A delete committing
  5230. # while the archive is written is caught after its commit.)
  5231. if await _printer_gone(db, printer_id):
  5232. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  5233. await forget_printer(printer_id)
  5234. return
  5235. if not downloaded_filename or not temp_path:
  5236. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  5237. # Create a fallback archive without 3MF data so the print is still tracked
  5238. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  5239. try:
  5240. from backend.app.models.archive import PrintArchive
  5241. # Why the card is empty. The two temporary causes outrank the
  5242. # storage verdict because they say the sweep never got a fair
  5243. # answer: a cool-off skipped it at the transport, and a failed
  5244. # transfer reached the printer but never finished. Either way
  5245. # the file is still on the card, so reporting where the printer
  5246. # files its jobs would describe a setting that is not the
  5247. # problem (#2957, #3063).
  5248. if blocked_by_ftps_cooloff:
  5249. no_3mf_reason = REASON_FTPS_COOLOFF
  5250. elif storage.reachable and ftp_transfer_failed:
  5251. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5252. else:
  5253. no_3mf_reason = storage.reason
  5254. # Derive print name from subtask_name or filename. The
  5255. # plate guard's disowned name comes second: it is a real name
  5256. # for a real print, and only the gcode_file path is left
  5257. # otherwise -- which titles the row "plate_1" (#3126).
  5258. print_name = subtask_name or display_name_after_plate_reject or filename
  5259. if print_name:
  5260. # Clean up the name (remove extensions, path parts)
  5261. print_name = print_name.split("/")[-1]
  5262. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5263. else:
  5264. print_name = "Unknown Print"
  5265. # Recover estimated print time from MQTT (best-effort for notifications)
  5266. fallback_print_time = None
  5267. mqtt_remaining = data.get("remaining_time")
  5268. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5269. fallback_print_time = int(mqtt_remaining)
  5270. if fallback_print_time is None:
  5271. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5272. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5273. fallback_print_time = int(mc_remaining * 60)
  5274. # Best-effort filament metadata from MQTT — see
  5275. # _extract_filament_data_from_mqtt. Without this the fallback
  5276. # archive's filament fields stayed NULL even though the AMS
  5277. # state at print start was sitting right there in `data`.
  5278. # The slicer's ams_mapping (when present) narrows the result
  5279. # to slots actually used by the print (#1533).
  5280. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  5281. # Create minimal archive entry
  5282. fallback_archive = PrintArchive(
  5283. printer_id=printer_id,
  5284. filename=filename or f"{print_name}.3mf",
  5285. file_path="", # Empty - no 3MF file available
  5286. file_size=0,
  5287. print_name=print_name,
  5288. print_time_seconds=fallback_print_time,
  5289. status="printing",
  5290. started_at=datetime.now(timezone.utc),
  5291. subtask_id=subtask_id,
  5292. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5293. filament_type=mqtt_filament_meta.get("filament_type"),
  5294. filament_color=mqtt_filament_meta.get("filament_color"),
  5295. extra_data={
  5296. "no_3mf_available": True,
  5297. # Why the card is empty, when we know -- see above. The
  5298. # banner reads this to stop telling H2/P2 owners to
  5299. # switch on a setting that is already on and would not
  5300. # have helped (#2780).
  5301. "no_3mf_reason": no_3mf_reason,
  5302. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5303. "_print_data": data,
  5304. },
  5305. )
  5306. db.add(fallback_archive)
  5307. try:
  5308. await db.commit()
  5309. except IntegrityError:
  5310. # Not "Failed to create fallback archive" below, and no
  5311. # start notification for a printer that is gone.
  5312. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5313. return
  5314. raise
  5315. await db.refresh(fallback_archive)
  5316. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5317. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5318. return
  5319. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5320. # Track as active print
  5321. _bind_active_print(printer_id, fallback_archive.id, fallback_archive.filename, filename, subtask_name)
  5322. # Record starting energy if smart plug available (#941: persisted column)
  5323. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5324. # Send WebSocket notification
  5325. await ws_manager.send_archive_created(
  5326. {
  5327. "id": fallback_archive.id,
  5328. "printer_id": fallback_archive.printer_id,
  5329. "filename": fallback_archive.filename,
  5330. "print_name": fallback_archive.print_name,
  5331. "status": fallback_archive.status,
  5332. }
  5333. )
  5334. # MQTT relay - publish archive created
  5335. try:
  5336. await mqtt_relay.on_archive_created(
  5337. archive_id=fallback_archive.id,
  5338. print_name=fallback_archive.print_name,
  5339. printer_name=printer.name,
  5340. status=fallback_archive.status,
  5341. )
  5342. except Exception:
  5343. pass # Don't fail if MQTT fails
  5344. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5345. try:
  5346. await _store_spoolman_print_data(
  5347. printer_id,
  5348. fallback_archive.id,
  5349. fallback_archive.file_path,
  5350. db,
  5351. printer_manager,
  5352. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  5353. plate_id=_get_start_plate_id(fallback_archive.id),
  5354. )
  5355. except Exception as e:
  5356. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5357. # Both temporary give-ups are worth coming back for, and for
  5358. # the same reason: the file is on the printer and the last look
  5359. # failed at the transport rather than finding nothing. One waits
  5360. # out the handshake block (#2957), the other waits for the
  5361. # printer to stop being busy (#3063). Deliberately not scheduled
  5362. # for a storage verdict: a file on internal eMMC will not appear
  5363. # at any FTPS path however long we wait, and retrying it is
  5364. # exactly the sweep #2780 removed.
  5365. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5366. # `possible_names`, not the raw MQTT strings: it is the exact
  5367. # list this flow just tried, already stripped of any path
  5368. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5369. # some firmware) and deduped.
  5370. _schedule_fallback_3mf_retry(
  5371. printer_id=printer_id,
  5372. archive_id=fallback_archive.id,
  5373. filenames=list(possible_names),
  5374. reason=no_3mf_reason,
  5375. )
  5376. # Send notification without archive data (file not found)
  5377. if not notification_sent:
  5378. await _send_print_start_notification(printer_id, data, logger=logger)
  5379. # The same baseline the other two on_print_start branches take
  5380. # (#2704), and last for the same reason they are: it lists the
  5381. # printer's timelapse directory, so a slow card must not delay
  5382. # the _active_prints registration, the energy reading, the
  5383. # archive-created event or the start notification above it.
  5384. #
  5385. # This branch never took one, so every no-3MF archive reached
  5386. # completion with no baseline in memory and none on the row, and
  5387. # the completion scan fell into its "snapshot now" fallback --
  5388. # which runs after the printer has written the video, so the new
  5389. # file landed inside the baseline and no diff ever matched
  5390. # (#2957 follow-up).
  5391. #
  5392. # Skipped when the FTPS cool-off is what produced this fallback:
  5393. # the listing needs the same connection that just failed, so it
  5394. # could only record that the card was unreadable. The scan
  5395. # handles that case by refusing to choose between candidates.
  5396. if not blocked_by_ftps_cooloff:
  5397. await _capture_timelapse_baseline_at_start(
  5398. printer, printer_id, logger, archive_id=fallback_archive.id
  5399. )
  5400. await _forget_if_printer_gone(printer_id)
  5401. return
  5402. except Exception as e:
  5403. logger.error("Failed to create fallback archive: %s", e)
  5404. # Send notification without archive data (file not found)
  5405. if not notification_sent:
  5406. await _send_print_start_notification(printer_id, data, logger=logger)
  5407. return
  5408. try:
  5409. # Archive the file with status "printing"
  5410. service = ArchiveService(db)
  5411. try:
  5412. archive = await service.archive_print(
  5413. printer_id=printer_id,
  5414. source_file=temp_path,
  5415. print_data={
  5416. **data,
  5417. "status": "printing",
  5418. # Where the 3MF came from when the printer had none to
  5419. # give (#3307), for whoever reads this archive later.
  5420. **({"_3mf_from_archive": reused_3mf_from} if reused_3mf_from is not None else {}),
  5421. },
  5422. subtask_id=subtask_id,
  5423. # The reused copy's temp name carries the printer id; a
  5424. # download's is the file's own name, as before.
  5425. original_filename=downloaded_filename if reused_3mf_from is not None else None,
  5426. )
  5427. except IntegrityError:
  5428. # archive_print removed the folder it had copied the 3MF into.
  5429. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5430. return
  5431. raise
  5432. if archive:
  5433. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5434. # Set on the row rather than passed to archive_print, which also
  5435. # serves the queue dispatcher — there the queue item decides.
  5436. # Guarded because this branch has no ``except``: an unhandled
  5437. # write error would take the _active_prints registration, the
  5438. # start notification, the energy reading and the timelapse
  5439. # baseline below it with it, and a missing prompt is by far the
  5440. # cheaper failure.
  5441. archive_id = archive.id
  5442. try:
  5443. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5444. archive.confirm_requested = True
  5445. await db.commit()
  5446. except Exception as e:
  5447. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5448. # The rollback expires every loaded object, and on an async
  5449. # session reading one afterwards raises instead of
  5450. # reloading, so the two this branch goes on to use are
  5451. # fetched again. The archive itself was committed by
  5452. # archive_print; only the flag is lost.
  5453. try:
  5454. await db.rollback()
  5455. archive = await db.get(PrintArchive, archive_id)
  5456. printer = await db.get(Printer, printer_id)
  5457. except Exception as reload_error:
  5458. logger.warning(
  5459. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5460. )
  5461. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5462. return
  5463. # Track this active print (use both original filename and downloaded filename)
  5464. _bind_active_print(printer_id, archive_id, downloaded_filename, filename, subtask_name)
  5465. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5466. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5467. # Record starting energy from smart plug if available (#941: persisted column)
  5468. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5469. await ws_manager.send_archive_created(
  5470. {
  5471. "id": archive.id,
  5472. "printer_id": archive.printer_id,
  5473. "filename": archive.filename,
  5474. "print_name": archive.print_name,
  5475. "status": archive.status,
  5476. }
  5477. )
  5478. # MQTT relay - publish archive created
  5479. try:
  5480. await mqtt_relay.on_archive_created(
  5481. archive_id=archive.id,
  5482. print_name=archive.print_name,
  5483. printer_name=printer.name,
  5484. status=archive.status,
  5485. )
  5486. except Exception:
  5487. pass # Don't fail if MQTT fails
  5488. # Send notification with archive data (new archive created)
  5489. if not notification_sent:
  5490. archive_data = {
  5491. "print_time_seconds": archive.print_time_seconds,
  5492. "created_by_id": archive.created_by_id,
  5493. }
  5494. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5495. # Extract printable objects for skip object functionality
  5496. try:
  5497. from backend.app.services.archive import extract_printable_objects_from_3mf
  5498. client = printer_manager.get_client(printer_id)
  5499. if client:
  5500. with open(temp_path, "rb") as f:
  5501. threemf_data = f.read()
  5502. # Extract with positions for UI overlay, scoped to the
  5503. # plate that is printing — an all-plates 3MF carries
  5504. # every plate's objects (#2522).
  5505. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5506. threemf_data,
  5507. plate_number=resolve_plate_id(client.state),
  5508. include_positions=True,
  5509. )
  5510. if printable_objects:
  5511. # Store objects in printer state
  5512. client.state.printable_objects = printable_objects
  5513. client.state.printable_objects_bbox_all = bbox_all
  5514. client.state.skipped_objects = [] # Reset skipped objects for new print
  5515. logger.info(
  5516. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5517. )
  5518. except Exception as e:
  5519. logger.debug("Failed to extract printable objects: %s", e)
  5520. # Store Spoolman tracking data for per-filament usage reporting
  5521. try:
  5522. await _store_spoolman_print_data(
  5523. printer_id,
  5524. archive.id,
  5525. archive.file_path,
  5526. db,
  5527. printer_manager,
  5528. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5529. plate_id=_get_start_plate_id(archive.id),
  5530. )
  5531. except Exception as e:
  5532. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5533. # Price the print from its spools now rather than only at completion (#3261)
  5534. _schedule_archive_cost_estimate(
  5535. printer_id,
  5536. archive.id,
  5537. printer_manager,
  5538. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5539. plate_id=_get_start_plate_id(archive.id),
  5540. session_factory=async_session,
  5541. )
  5542. # Capture timelapse file baseline for snapshot-diff on completion
  5543. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5544. await _forget_if_printer_gone(printer_id)
  5545. finally:
  5546. # Keep temp_path around until print completes so the cover endpoint
  5547. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5548. # the file. If the cache entry was evicted early (file vanished),
  5549. # clean up any stragglers here to avoid leaking disk on retries.
  5550. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5551. if temp_path and temp_path.exists() and cached_now != temp_path:
  5552. temp_path.unlink()
  5553. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5554. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5555. # tests can shrink them without waiting out real delays.
  5556. #
  5557. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  5558. # looking. Across 247 support bundles the attempt that found the video was #1
  5559. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  5560. # decaying one, which is the signature of a budget that expires while files are
  5561. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  5562. # prints make big videos and the printer writes them after the print ends, so
  5563. # the poll now runs for minutes and costs one FTP LIST per round.
  5564. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  5565. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  5566. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  5567. def _timelapse_scan_max_attempts() -> int:
  5568. """Round cap for the poll, derived from the wall-clock budget.
  5569. The deadline alone is not a sufficient bound: it assumes each round really
  5570. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5571. and an FTP list that fails immediately would otherwise spin against the
  5572. printer at full speed for the whole window. Whichever bound is reached
  5573. first ends the poll.
  5574. """
  5575. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5576. # A zero interval makes the wall-clock budget meaningless; fall back to
  5577. # the round count the production interval would have given.
  5578. return 32
  5579. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5580. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  5581. """Video filenames already attached to some other archive of this printer.
  5582. Used to disambiguate when more than one file is new since the baseline —
  5583. which happens when a previous print's video landed after this print's
  5584. baseline was taken. Ordering the candidates would be the obvious fix and is
  5585. the wrong one: it can only be done on mtime or on the filename timestamp,
  5586. both of which come from the printer's own clock, and a LAN-only printer
  5587. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  5588. ``attach_timelapse`` saves the video into the archive directory under the
  5589. printer's original filename, and the later MP4 conversion keeps the stem,
  5590. so the stem of ``timelapse_path`` recovers what was claimed.
  5591. """
  5592. from backend.app.models.archive import PrintArchive
  5593. rows = await db.execute(
  5594. select(PrintArchive.timelapse_path).where(
  5595. PrintArchive.printer_id == printer_id,
  5596. PrintArchive.id != exclude_archive_id,
  5597. PrintArchive.timelapse_path.is_not(None),
  5598. )
  5599. )
  5600. return {Path(p).stem for p in rows.scalars().all() if p}
  5601. def _timelapse_listing_is_trustworthy(printer) -> bool:
  5602. """Whether an *empty* timelapse listing for *printer* can be believed.
  5603. ``list_files_async`` answers ``[]`` when its connect fails rather than
  5604. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  5605. from one holding no videos. Everywhere that only wants to know "is there a
  5606. video yet" the difference does not matter — both mean "not yet, retry".
  5607. It matters where an empty listing is recorded as a *baseline*. Recording
  5608. "the card held nothing" for a card that was never read means every video on
  5609. it counts as new once the cool-off expires, and the completion scan then
  5610. attaches a stale video to this print and deletes it from the printer
  5611. (#2957 follow-up). Those two callers ask this first.
  5612. """
  5613. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  5614. ip_address = getattr(printer, "ip_address", None)
  5615. if not ip_address:
  5616. return True
  5617. return not ftps_handshake_blocked(ip_address)
  5618. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5619. """List video files from printer's timelapse directory.
  5620. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5621. Returns (video_files, found_path) where video_files is a list of file dicts
  5622. and found_path is the directory where they were found, or ([], None).
  5623. An empty return does not distinguish "no videos" from "could not read the
  5624. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  5625. baseline callers consult before believing one.
  5626. """
  5627. from backend.app.services.bambu_ftp import list_files_async
  5628. logger = logging.getLogger(__name__)
  5629. # No card in the slot means no /timelapse to walk — four connections that
  5630. # can only fail, on a path whose failures are swallowed and so would go on
  5631. # costing time silently forever (#2780).
  5632. #
  5633. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5634. # inside the loop's own try/except, so a caller that passed something
  5635. # unexpected used to get an empty listing rather than an exception. Keep
  5636. # that, instead of making this gate the first thing that can raise here.
  5637. printer_id = getattr(printer, "id", None)
  5638. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5639. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5640. return [], None
  5641. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  5642. try:
  5643. found_files = await list_files_async(
  5644. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5645. )
  5646. if found_files:
  5647. video_files = [
  5648. f
  5649. for f in found_files
  5650. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5651. ]
  5652. if video_files:
  5653. return video_files, timelapse_path
  5654. except Exception as e:
  5655. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5656. continue
  5657. return [], None
  5658. async def _capture_timelapse_baseline_at_start(
  5659. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5660. ) -> None:
  5661. """Snapshot the printer's timelapse directory at print start so the
  5662. completion-time scan can pick the new file by set-difference.
  5663. Must be called from every on_print_start path that proceeds to a real
  5664. print — both the new-archive branch and the expected-archive branch (which
  5665. queue / VP-dispatched prints take). Without a baseline,
  5666. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5667. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5668. so the new file ends up in the "baseline" set and no diff ever matches.
  5669. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  5670. unreliable — the snapshot-diff approach sidesteps that entirely.
  5671. When ``archive_id`` is known the baseline is also written to the archive
  5672. row, so it survives a restart and the manual "Scan for Timelapse" button
  5673. can run the same diff instead of falling back to clock-based matching
  5674. (#2704). Only baselines taken at print start are persisted — one taken at
  5675. completion already contains the new video and would poison a later scan.
  5676. """
  5677. names: set[str] | None = None
  5678. try:
  5679. if not _timelapse_listing_is_trustworthy(printer):
  5680. # Recorded anyway, deliberately. An empty baseline taken off a card
  5681. # we could not read is not authoritative, but it is still the right
  5682. # *default*: Bambuddy deletes each video from the printer once it is
  5683. # attached, so the usual card holds exactly one video at completion
  5684. # and an empty baseline resolves it correctly. Persisting NULL
  5685. # instead would send completion to take its own snapshot, by which
  5686. # point this print's video is on the card and would be swallowed by
  5687. # it. The ambiguity is handled where it actually bites — see
  5688. # ``require_unambiguous`` in the scan (#2957 follow-up).
  5689. logger.warning(
  5690. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  5691. "handshake cool-off, so the card could not be read — treating it as empty",
  5692. printer_id,
  5693. )
  5694. baseline_files, _ = await _list_timelapse_videos(printer)
  5695. names = {f.get("name", "") for f in baseline_files}
  5696. _timelapse_baselines[printer_id] = names
  5697. logger.info(
  5698. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  5699. len(names),
  5700. printer_id,
  5701. )
  5702. except Exception as e:
  5703. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  5704. if archive_id is None:
  5705. return
  5706. try:
  5707. async with async_session() as db:
  5708. from backend.app.models.archive import PrintArchive
  5709. archive = await db.get(PrintArchive, archive_id)
  5710. if archive is not None:
  5711. # Written even when the listing failed, and then as NULL. A
  5712. # reprint reuses the archive row, so leaving the previous run's
  5713. # baseline in place would have the scan diff this print against
  5714. # the state of the printer before the *last* one — and a stale
  5715. # baseline reads as authoritative, where NULL correctly falls
  5716. # back to a fresh snapshot.
  5717. archive.timelapse_baseline = sorted(names) if names is not None else None
  5718. await db.commit()
  5719. except Exception as e:
  5720. # In-memory baseline still covers the normal completion path.
  5721. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  5722. async def _scan_for_timelapse_with_retries(
  5723. archive_id: int, baseline_names: set[str] | None = None, *, plate_id: int | None = None
  5724. ):
  5725. """Poll the printer for this print's timelapse and attach it.
  5726. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  5727. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  5728. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  5729. (#2704). Comparing the current listing against the set of filenames that
  5730. existed when the print started needs no clock at all, because the printer
  5731. writes the video only once the print has ended.
  5732. Baseline precedence: the caller's in-memory set, then the one persisted on
  5733. the archive at print start, then a snapshot taken now. The last of those is
  5734. a poor substitute — by completion the new video may already be on the card,
  5735. in which case it lands in the "baseline" and no diff can ever match — but it
  5736. is all that is available for a print that began before Bambuddy started.
  5737. On success the video is deleted from the printer, which keeps ``/timelapse``
  5738. down to the unclaimed files and makes the next diff unambiguous.
  5739. """
  5740. logger = logging.getLogger(__name__)
  5741. # Cleared when the baseline had to be taken off a card we could not read, so
  5742. # the attach step refuses to choose between several candidates (#2957).
  5743. baseline_trusted = True
  5744. # --- Phase 1: establish the baseline -------------------------------------
  5745. try:
  5746. async with async_session() as db:
  5747. from backend.app.models.printer import Printer
  5748. service = ArchiveService(db)
  5749. archive = await service.get_archive(archive_id)
  5750. if not archive:
  5751. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  5752. return
  5753. if archive.timelapse_path:
  5754. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  5755. return
  5756. if not archive.printer_id:
  5757. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  5758. return
  5759. # The run this scan is for. The archive row passes to a newer run
  5760. # when it prints again (the next plate, a reprint), and that run's
  5761. # video is its own.
  5762. run_started_at = archive.started_at
  5763. if baseline_names is not None:
  5764. logger.info(
  5765. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  5766. len(baseline_names),
  5767. archive_id,
  5768. )
  5769. elif archive.timelapse_baseline is not None:
  5770. # Persisted at print start — survives a restart mid-print.
  5771. baseline_names = set(archive.timelapse_baseline)
  5772. logger.info(
  5773. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  5774. len(baseline_names),
  5775. archive_id,
  5776. )
  5777. else:
  5778. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5779. printer = result.scalar_one_or_none()
  5780. if not printer:
  5781. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  5782. return
  5783. if not _timelapse_listing_is_trustworthy(printer):
  5784. # The card is unreadable at the one moment a baseline has to
  5785. # be taken, so the empty listing below means "we never
  5786. # looked", not "these are all new". Carry on with it anyway
  5787. # — the usual card holds exactly one video, which resolves
  5788. # correctly — but stop the poll from *choosing* between
  5789. # several, which is how a stale video got attached to this
  5790. # print and then deleted off the printer (#2957 follow-up).
  5791. baseline_trusted = False
  5792. logger.warning(
  5793. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  5794. "handshake cool-off. A single new video still resolves; several will not be "
  5795. "guessed between — use Scan for Timelapse to pick one by hand",
  5796. archive_id,
  5797. archive.printer_id,
  5798. )
  5799. baseline_files, _ = await _list_timelapse_videos(printer)
  5800. baseline_names = {f.get("name", "") for f in baseline_files}
  5801. logger.info(
  5802. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  5803. len(baseline_names),
  5804. archive_id,
  5805. )
  5806. except Exception as e:
  5807. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  5808. return
  5809. # --- Phase 2: poll for a file that was not there when the print began -----
  5810. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  5811. max_attempts = _timelapse_scan_max_attempts()
  5812. seen_names: set[str] = set()
  5813. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  5814. attempt = 0
  5815. while True:
  5816. await asyncio.sleep(delay)
  5817. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  5818. attempt += 1
  5819. try:
  5820. from backend.app.models.printer import Printer
  5821. # Read phase: fetch archive + printer in a short session and release
  5822. # the pooled connection BEFORE the FTP list/download below. Holding it
  5823. # across the FTP round-trips left one connection idle-in-transaction per
  5824. # in-flight scan (issue #2572).
  5825. async with async_session() as db:
  5826. service = ArchiveService(db)
  5827. archive = await service.get_archive(archive_id)
  5828. if not archive:
  5829. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  5830. return
  5831. if archive.timelapse_path:
  5832. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  5833. return
  5834. if archive.started_at != run_started_at:
  5835. logger.info(
  5836. "[TIMELAPSE] Archive %s is printing again, stopping the previous run's poll", archive_id
  5837. )
  5838. return
  5839. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5840. printer = result.scalar_one_or_none()
  5841. if not printer:
  5842. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  5843. return
  5844. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  5845. # I/O phase (no DB connection held): FTP list + download.
  5846. video_files, found_path = await _list_timelapse_videos(printer)
  5847. # The poll can run for dozens of rounds, so only narrate a round
  5848. # that saw something change. Repeating the whole listing every 30 s
  5849. # would bury the one interesting line in the support bundle.
  5850. names_now = {f.get("name", "") for f in video_files}
  5851. changed = attempt == 1 or names_now != seen_names
  5852. seen_names = names_now
  5853. speak = logger.info if changed else logger.debug
  5854. if video_files:
  5855. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  5856. if changed:
  5857. for f in video_files[:5]:
  5858. logger.info("[TIMELAPSE] - %s", f.get("name"))
  5859. attached = await _attach_first_unclaimed_timelapse(
  5860. archive_id,
  5861. printer,
  5862. video_files,
  5863. baseline_names,
  5864. claimed,
  5865. attempt,
  5866. logger,
  5867. quiet=not changed,
  5868. require_unambiguous=not baseline_trusted,
  5869. plate_id=plate_id,
  5870. run_started_at=run_started_at,
  5871. )
  5872. if attached:
  5873. return
  5874. else:
  5875. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  5876. except Exception as e:
  5877. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  5878. if attempt >= max_attempts or time.monotonic() >= deadline:
  5879. break
  5880. # No name-match fallback: it compared the print name against the filename,
  5881. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  5882. # bundles it fired 159 times and matched zero times, so all it added was a
  5883. # misleading log line before giving up.
  5884. logger.warning(
  5885. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  5886. archive_id,
  5887. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  5888. )
  5889. async def _attach_layer_timelapse(
  5890. archive_id: int, timelapse_path: Path, plate_id: int | None, run_started_at: datetime | None
  5891. ) -> None:
  5892. """Attach the external camera's stitched timelapse to the archive.
  5893. The camera's video is the one the user set up in Bambuddy, so it wins
  5894. over the printer's own when both are on: it replaces the printer's video
  5895. (usually there first; stitching takes minutes) and that file is deleted,
  5896. leaving nothing in the archive folder unreferenced. ``run_started_at`` is
  5897. the run the frames were taken for: when the archive is printing again by
  5898. the time the stitch is done, the video is not the new run's and is
  5899. dropped. The stitched file is a temporary either way.
  5900. """
  5901. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  5902. logger = logging.getLogger(__name__)
  5903. try:
  5904. async with async_session() as db:
  5905. service = ArchiveService(db)
  5906. archive = await service.get_archive(archive_id)
  5907. if archive is None:
  5908. return
  5909. if archive.started_at != run_started_at:
  5910. logger.info(
  5911. "[LAYER-TL] Archive %s is printing again; dropping the previous run's layer timelapse", archive_id
  5912. )
  5913. return
  5914. replaced = archive.timelapse_path
  5915. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  5916. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  5917. if not await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=plate_id):
  5918. return
  5919. attached = archive.timelapse_path
  5920. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  5921. if replaced and replaced != attached:
  5922. try:
  5923. old = safe_join_under(app_settings.base_dir, replaced, http=False)
  5924. except PathTraversalError:
  5925. return
  5926. await asyncio.to_thread(old.unlink, missing_ok=True)
  5927. logger.info("[LAYER-TL] Replaced the printer's timelapse %s on archive %s", replaced, archive_id)
  5928. finally:
  5929. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  5930. # ``run_started_at`` not given: attach whichever run the archive is on.
  5931. _ANY_RUN = object()
  5932. async def _attach_first_unclaimed_timelapse(
  5933. archive_id: int,
  5934. printer,
  5935. video_files: list[dict],
  5936. baseline_names: set[str],
  5937. claimed: set[str],
  5938. attempt: int,
  5939. logger: logging.Logger,
  5940. *,
  5941. quiet: bool = False,
  5942. require_unambiguous: bool = False,
  5943. plate_id: int | None = None,
  5944. run_started_at: datetime | None | object = _ANY_RUN,
  5945. ) -> bool:
  5946. """Download and attach the one video that belongs to this print.
  5947. A candidate is any file absent from the print-start baseline. More than one
  5948. can qualify when a previous print's video landed late, after this print's
  5949. baseline was taken — those are filtered out by name, because they are
  5950. already attached to another archive. Sorting the candidates instead would
  5951. mean sorting on mtime or on the filename timestamp, both of which come from
  5952. the printer's unsynced clock.
  5953. Returns True once a video is attached. The printer's copy is deleted only
  5954. after the attach succeeds on bytes whose length matched the listing.
  5955. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  5956. already seen this exact listing — the poll runs for many rounds and only the
  5957. rounds where something changed are worth an INFO line.
  5958. """
  5959. from backend.app.services.bambu_ftp import (
  5960. DownloadDeadlineExceeded,
  5961. delete_archived_timelapse,
  5962. download_file_bytes_async,
  5963. remote_file_settled,
  5964. )
  5965. speak = logger.debug if quiet else logger.info
  5966. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  5967. if not new_files:
  5968. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  5969. return False
  5970. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  5971. if not candidates:
  5972. speak(
  5973. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  5974. attempt,
  5975. len(new_files),
  5976. )
  5977. return False
  5978. if len(candidates) > 1:
  5979. if require_unambiguous:
  5980. # The baseline is not evidence -- it was taken off a card that could
  5981. # not be read -- so "new since the baseline" does not narrow these
  5982. # down at all. Taking the first would attach an arbitrary video to
  5983. # this print and then delete it from the printer.
  5984. logger.warning(
  5985. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  5986. "leaving all of them on the printer for manual selection",
  5987. attempt,
  5988. len(candidates),
  5989. ", ".join(str(f.get("name")) for f in candidates),
  5990. )
  5991. return False
  5992. logger.warning(
  5993. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  5994. "the rest stay on the printer for manual selection",
  5995. attempt,
  5996. len(candidates),
  5997. ", ".join(str(f.get("name")) for f in candidates),
  5998. )
  5999. target = candidates[0]
  6000. file_name = str(target.get("name") or "") # every listed entry has one
  6001. remote_path = target.get("path") or f"/timelapse/{file_name}"
  6002. logger.info(
  6003. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  6004. attempt,
  6005. file_name,
  6006. archive_id,
  6007. )
  6008. # The listing always carries a size (`list_files` skips entries it can't
  6009. # parse), but read it explicitly: the delete below is destructive and must
  6010. # depend on a size we actually had, not on one we hoped was there.
  6011. expected_size = target.get("size")
  6012. try:
  6013. timelapse_data = await download_file_bytes_async(
  6014. printer.ip_address,
  6015. printer.access_code,
  6016. remote_path,
  6017. printer_model=printer.model,
  6018. expected_size=expected_size,
  6019. )
  6020. except DownloadDeadlineExceeded:
  6021. # Too slow for its size this round; the printer keeps its copy.
  6022. timelapse_data = None
  6023. if not timelapse_data:
  6024. # Short or failed transfer. The printer keeps its copy, so the next
  6025. # round can try again — which is exactly why the delete below is
  6026. # gated on a verified download.
  6027. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  6028. return False
  6029. # The length check above proves we got what the listing said, not that the
  6030. # printer had finished writing. A video still being written can be listed
  6031. # short, served short, and pass — so confirm it has stopped growing before
  6032. # committing to it and deleting the original (#2704).
  6033. if not await remote_file_settled(
  6034. printer.ip_address,
  6035. printer.access_code,
  6036. remote_path,
  6037. len(timelapse_data),
  6038. printer_model=printer.model,
  6039. ):
  6040. return False
  6041. # Write phase: attach in a fresh short-lived session. The download took a
  6042. # while: by now the archive may have its video, or be printing again for a
  6043. # newer run, whose video this is not. Then nothing is attached or deleted,
  6044. # and the poll ends (True).
  6045. async with async_session() as db:
  6046. service = ArchiveService(db)
  6047. if run_started_at is not _ANY_RUN:
  6048. current = await service.get_archive(archive_id)
  6049. if current is None or current.timelapse_path or current.started_at != run_started_at:
  6050. logger.info(
  6051. "[TIMELAPSE] Archive %s moved on during the download (video attached or printing again); "
  6052. "%s stays on the printer",
  6053. archive_id,
  6054. file_name,
  6055. )
  6056. return True
  6057. success = await service.attach_timelapse(archive_id, timelapse_data, file_name, plate_id=plate_id)
  6058. if not success:
  6059. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  6060. return False
  6061. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  6062. await delete_archived_timelapse(
  6063. printer.ip_address,
  6064. printer.access_code,
  6065. remote_path,
  6066. verified=expected_size is not None,
  6067. printer_model=printer.model,
  6068. printer_name=printer.name,
  6069. )
  6070. return True
  6071. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  6072. # module-level so tests can monkeypatch them down to ~0 without timing out.
  6073. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  6074. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  6075. # How long the *background* upgrade keeps waiting after the notification has
  6076. # already gone out (#2704 follow-up). The short bound above exists so a slow
  6077. # printer can't hold up the print-complete notification; this one exists so the
  6078. # archive still ends up with the better frame afterwards.
  6079. #
  6080. # Measured across 261 attaches in the support bundles, the video lands a median
  6081. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  6082. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  6083. # was 546s. Every other model was inside 26s. The long budget is therefore
  6084. # almost entirely for P1-series users; on everything else the short wait already
  6085. # wins and this task never runs.
  6086. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  6087. async def _capture_finish_photo_from_timelapse(
  6088. archive_id: int,
  6089. archive_dir: Path,
  6090. timeout: float | None = None,
  6091. rotation: int = 0,
  6092. ) -> tuple[str | None, bool]:
  6093. """Wait for the per-print timelapse to land on the archive and extract its
  6094. last frame as the finish photo (#1397).
  6095. Bambu firmware stops timelapse recording after the toolhead parks but
  6096. before the bed-drop end-gcode runs, so the last frame frames the finished
  6097. print correctly. A live camera grab at gcode_state=FINISH captures the
  6098. bed already lowered.
  6099. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  6100. ``archive.timelapse_path`` when the file lands. This function polls for
  6101. that field.
  6102. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  6103. the wait ran out with no video on the archive yet — i.e. the video may
  6104. still be coming and a later attempt could succeed. It is False when the
  6105. video landed (whether or not extraction worked), because in that case
  6106. waiting longer changes nothing. The caller uses that to decide between
  6107. falling back permanently and scheduling a background upgrade.
  6108. ``rotation`` is the printer's camera_rotation, applied to the extracted
  6109. still (#2708) so this source agrees with every other finish-photo source.
  6110. The archived video itself is the printer's own file and is left alone —
  6111. rotating it would mean re-encoding it.
  6112. """
  6113. import uuid
  6114. from backend.app.models.archive import PrintArchive
  6115. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  6116. logger = logging.getLogger(__name__)
  6117. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  6118. deadline = asyncio.get_event_loop().time() + budget
  6119. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  6120. while True:
  6121. async with async_session() as db:
  6122. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  6123. archive = result.scalar_one_or_none()
  6124. timelapse_relpath = archive.timelapse_path if archive else None
  6125. if timelapse_relpath:
  6126. video_path = app_settings.base_dir / timelapse_relpath
  6127. if video_path.exists() and video_path.stat().st_size > 0:
  6128. photos_dir = archive_dir / "photos"
  6129. photos_dir.mkdir(parents=True, exist_ok=True)
  6130. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  6131. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  6132. output_path = photos_dir / filename
  6133. if await extract_video_last_frame(video_path, output_path):
  6134. await apply_camera_rotation_to_file(output_path, rotation, logger)
  6135. logger.info(
  6136. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  6137. video_path.name,
  6138. archive_id,
  6139. )
  6140. return filename, False
  6141. logger.warning(
  6142. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  6143. video_path.name,
  6144. archive_id,
  6145. )
  6146. return None, False
  6147. if asyncio.get_event_loop().time() >= deadline:
  6148. logger.info(
  6149. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  6150. archive_id,
  6151. budget,
  6152. )
  6153. return None, True
  6154. await asyncio.sleep(poll_interval)
  6155. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  6156. """Add the timelapse's last frame to an archive after the fact (#2704).
  6157. The print-complete notification waits only ~60s for the video, because
  6158. holding a notification for minutes is worse than sending it with a live
  6159. camera grab. On a P1-series printer the video often lands well after that,
  6160. so the archive used to be stuck with the live grab — which is taken at
  6161. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  6162. the worse photo of the two.
  6163. This keeps waiting in the background and, when the video arrives, extracts
  6164. the frame and puts it *first* in the archive's photo list, so opening the
  6165. gallery shows it. The live grab is deliberately kept: the notification that
  6166. already went out links to that exact file, and deleting it would leave a
  6167. broken image in Discord or Telegram.
  6168. """
  6169. logger = logging.getLogger(__name__)
  6170. filename, _ = await _capture_finish_photo_from_timelapse(
  6171. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  6172. )
  6173. if not filename:
  6174. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  6175. return
  6176. try:
  6177. async with async_session() as db:
  6178. from backend.app.models.archive import PrintArchive
  6179. archive = await db.get(PrintArchive, archive_id)
  6180. if archive is None:
  6181. return
  6182. photos = list(archive.photos or [])
  6183. if filename in photos:
  6184. return
  6185. # Front of the list: PhotoGalleryModal opens at index 0.
  6186. archive.photos = [filename, *photos]
  6187. await db.commit()
  6188. except Exception as e:
  6189. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  6190. return
  6191. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  6192. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  6193. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  6194. """Put the filament-attribution context back after a restart mid-print.
  6195. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  6196. both die with the process. The print keeps running, so at completion the
  6197. tracker would fall back to whatever the printer reports *now* — and AMS
  6198. filament backup makes "now" the substitute tray, charging the whole print
  6199. to the spool that only finished it.
  6200. The persisted row is only trusted when its print name still matches what
  6201. the printer says it is running: a row left behind by a completion we never
  6202. saw must not attach itself to the next print.
  6203. """
  6204. try:
  6205. from backend.app.api.routes.settings import get_setting
  6206. from backend.app.services.usage_tracker import (
  6207. clear_persisted_session,
  6208. get_persisted_ams_mapping,
  6209. get_persisted_print_name,
  6210. restore_session,
  6211. )
  6212. persisted_name = await get_persisted_print_name(db, printer_id)
  6213. current_name = (state.subtask_name or "").strip()
  6214. if persisted_name and current_name and persisted_name.strip() != current_name:
  6215. logger.info(
  6216. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  6217. printer_id,
  6218. persisted_name,
  6219. current_name,
  6220. )
  6221. await clear_persisted_session(db, printer_id)
  6222. # Fall through to seeding: the print on the printer is real, it just
  6223. # isn't the one the row described.
  6224. persisted_log = None
  6225. else:
  6226. # Spoolman users get the tray-change log back but no in-memory
  6227. # session — see ``on_print_start`` on why that dict is load-bearing
  6228. # for the remain%-sync guard.
  6229. _spoolman_on = await get_setting(db, "spoolman_enabled")
  6230. persisted_log = await restore_session(
  6231. db,
  6232. printer_id,
  6233. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  6234. )
  6235. # The slot pills (#1762) read the mapping captured from the print
  6236. # command, which dies with the process as well. One this process
  6237. # has captured since is newer.
  6238. if state.print_ams_mapping is None:
  6239. state.print_ams_mapping = await get_persisted_ams_mapping(db, printer_id)
  6240. if persisted_log:
  6241. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  6242. # Anything this process already observed goes after the persisted
  6243. # history — the log is ordered by layer, and a fresh process can
  6244. # only have seen changes from later in the print.
  6245. for entry in state.tray_change_log or []:
  6246. if tuple(entry) not in restored:
  6247. restored.append(tuple(entry))
  6248. state.tray_change_log = restored
  6249. tray_now = state.tray_now
  6250. if 0 <= tray_now <= 254:
  6251. if not state.tray_change_log:
  6252. # No persisted history — a print that started before this build,
  6253. # or before the row existed. Seed with the tray feeding right
  6254. # now so the remainder of the print is at least attributable to
  6255. # the right spool.
  6256. state.tray_change_log = [(tray_now, state.layer_num)]
  6257. logger.info(
  6258. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  6259. printer_id,
  6260. tray_now,
  6261. state.layer_num,
  6262. )
  6263. # The tray handler updates ``last_loaded_tray`` on every push
  6264. # regardless of whether it logged a change, so re-align it to avoid
  6265. # a duplicate entry on the next push. Only ever with a real tray:
  6266. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  6267. # 255" fallback, and writing 255 into it would defeat that.
  6268. state.last_loaded_tray = tray_now
  6269. except Exception:
  6270. # Never let attribution recovery cost the caller its timelapse
  6271. # baseline — that capture has to happen before the printer uploads
  6272. # the in-flight MP4 and there is no second chance at it.
  6273. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  6274. async def on_print_running_observed(printer_id: int, data: dict):
  6275. """Restart-recovery for a print that started before Bambuddy came up.
  6276. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  6277. after Bambuddy startup (#1304 guard, prevents duplicate archive
  6278. creation). This hook restores the persisted archive into ``_active_prints``
  6279. and captures the timelapse baseline that normally hangs off print start.
  6280. Fires once per session, in lieu of on_print_start when restart-recovery
  6281. kicks in. The printer doesn't upload the timelapse until after PRINT
  6282. COMPLETE, so a baseline captured any time during the print is still
  6283. pre-upload.
  6284. """
  6285. logger = logging.getLogger(__name__)
  6286. async with async_session() as db:
  6287. from backend.app.models.printer import Printer
  6288. state = printer_manager.get_status(printer_id)
  6289. if state is not None:
  6290. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  6291. if authorization is True:
  6292. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  6293. await _restore_usage_tracking_session(printer_id, state, db, logger)
  6294. await _restore_printable_objects(printer_id, state, db, logger)
  6295. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6296. printer = result.scalar_one_or_none()
  6297. if not printer:
  6298. logger.warning(
  6299. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  6300. printer_id,
  6301. )
  6302. return
  6303. # Avoid double-capture: ownership reconciliation above must still run when
  6304. # a baseline already exists, but the camera work itself is one-shot.
  6305. if printer_id in _timelapse_baselines:
  6306. logger.debug(
  6307. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  6308. printer_id,
  6309. )
  6310. return
  6311. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  6312. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  6313. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  6314. against the printer's current MQTT state.
  6315. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  6316. COMPLETE events, typically a print finishing during an MQTT disconnect
  6317. window followed by a smart-plug power cycle):
  6318. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  6319. provably not running anymore — only branch that should fire under
  6320. normal disconnect-then-reconnect timing.
  6321. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  6322. firmware mints a fresh ``subtask_id`` for each print, including the
  6323. ghost replay it runs after a power cycle from a leftover SD file —
  6324. so a mismatch unambiguously means the in-DB archive is no longer
  6325. the print on the printer.
  6326. 3. Printer is running but ``subtask_name`` is empty. The printer
  6327. doesn't know what it's running; the archive's reference to it is
  6328. already broken.
  6329. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  6330. with matching subtask_id+subtask_name is left alone. The cost of a false
  6331. positive is a duplicate archive on the next real PRINT COMPLETE — the
  6332. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  6333. clears on synthesis, so the real completion creates a fresh row instead
  6334. of overwriting the synthesised one (#1679). The cost of a false negative
  6335. is the ghost-print loop in #1542.
  6336. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  6337. MQTT has connected but the first ``push_status`` response hasn't been
  6338. applied yet — ``PrinterState`` is sitting on its construction defaults.
  6339. The reconcile caller in ``on_printer_status_change`` is already gated
  6340. on a real ``state.state``, so in normal operation this branch is
  6341. unreachable; it's kept as belt-and-braces for future callers and for
  6342. the narrow window where a partial state update could arrive
  6343. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  6344. ``not stale`` on degenerate input is strictly conservative: a real
  6345. stale archive will still be caught by the next push_status arriving
  6346. with terminal state.
  6347. """
  6348. current_state = (state.state or "").upper()
  6349. if current_state in ("", "UNKNOWN"):
  6350. # No real push_status yet — PrinterState defaults are not evidence.
  6351. return False, ""
  6352. if current_state in ("IDLE", "FINISH", "FAILED"):
  6353. return True, f"printer state {current_state}"
  6354. # Below here the printer is in a running / pre-running state (RUNNING /
  6355. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  6356. current_subtask_id = (state.subtask_id or "").strip()
  6357. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  6358. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  6359. current_subtask_name = (state.subtask_name or "").strip()
  6360. if not current_subtask_name:
  6361. return True, "printer subtask_name empty"
  6362. return False, ""
  6363. async def prime_kprofile_table(printer_id: int) -> int:
  6364. """Read the printer's calibration table once per connection.
  6365. The AMS slot card shows a K value per slot (#2854). On the printers whose
  6366. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  6367. report ``cali_idx`` and nothing else -- that number can only come from
  6368. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  6369. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  6370. backup, or the printer answering a query BambuStudio made on the report
  6371. topic we share. A Bambuddy that nobody visited showed a card with no K
  6372. values at all.
  6373. Only the diameters actually fitted are asked for, which is one request on a
  6374. single-nozzle printer and two on a dual. Probing the four sizes blind is
  6375. what the backup does, and it is both wasteful and the thing that used to
  6376. blank the table.
  6377. Returns the number of nozzles whose table was read.
  6378. """
  6379. client = printer_manager.get_client(printer_id)
  6380. state = printer_manager.get_status(printer_id)
  6381. if client is None or state is None or not state.connected:
  6382. return 0
  6383. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  6384. # ask once, and both entries are empty until the first push_status lands.
  6385. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  6386. if not diameters:
  6387. logging.getLogger(__name__).debug(
  6388. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  6389. printer_id,
  6390. )
  6391. return 0
  6392. primed = 0
  6393. for diameter in diameters:
  6394. try:
  6395. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  6396. except Exception as exc: # noqa: BLE001
  6397. # A printer that won't answer costs the card its K values, nothing
  6398. # more — never the connection this runs on the back of.
  6399. logging.getLogger(__name__).warning(
  6400. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  6401. )
  6402. continue
  6403. primed += 1
  6404. logging.getLogger(__name__).info(
  6405. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  6406. )
  6407. return primed
  6408. def _sd_files_in_use(state) -> set[str]:
  6409. """Names of the SD-card files the printer may be printing right now (#3009).
  6410. The post-print cleanup works out what to delete from the finished archive,
  6411. not from the printer. When reconciliation closes an old archive because the
  6412. printer has moved on to a new job, and that job is the same file reprinted
  6413. from the printer's screen, the cleanup would delete the file mid-print.
  6414. Empty unless the printer is busy: on an ordinary completion the state is
  6415. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  6416. name, a path or a URL depending on firmware, and some report only the
  6417. plate's G-code, so the job name is matched as well, in the same spellings
  6418. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  6419. ignores case.
  6420. """
  6421. def _text(value) -> str:
  6422. return value.strip() if isinstance(value, str) else ""
  6423. if state is None:
  6424. return set()
  6425. current_state = _text(getattr(state, "state", None)).upper()
  6426. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  6427. return set()
  6428. in_use: set[str] = set()
  6429. gcode_file = _text(getattr(state, "gcode_file", None))
  6430. if gcode_file:
  6431. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  6432. # both legal in a file name, and raises on some inputs.
  6433. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  6434. if name:
  6435. in_use.add(name.lower())
  6436. subtask_name = _text(getattr(state, "subtask_name", None))
  6437. if subtask_name:
  6438. for name in (subtask_name, subtask_name.replace(" ", "_")):
  6439. for ext in (".3mf", ".gcode"):
  6440. in_use.add(f"{name}{ext}".lower())
  6441. return in_use
  6442. async def reconcile_stale_active_prints(printer_id: int) -> int:
  6443. """Synthesise ``on_print_complete`` for archives whose print can't be
  6444. running on the printer anymore.
  6445. Called once per MQTT (re)connection (from on_printer_status_change when
  6446. the connected edge flips False → True) and at Bambuddy startup (from
  6447. the FastAPI lifespan). Without this, a print that completes during a
  6448. disconnect window — followed by a smart-plug-driven power cycle — leaves
  6449. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  6450. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  6451. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  6452. power cycle until the operator notices (#1542 follow-up). Reconciliation
  6453. closes the loop by faking the missed PRINT COMPLETE — the existing
  6454. cleanup chain handles SD-file deletion, status updates, usage tracking,
  6455. and notifications.
  6456. Synthesised ``status="aborted"`` is the conservative label: we have no
  6457. proof the print finished successfully (and no progress evidence to
  6458. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  6459. fires later, overwrites the status with the correct value.
  6460. Returns the number of archives reconciled.
  6461. """
  6462. state = printer_manager.get_status(printer_id)
  6463. if not state:
  6464. return 0
  6465. # Don't reconcile while disconnected — we'd be making a decision against
  6466. # stale cached state. The connected → reconcile edge handles this.
  6467. if not state.connected:
  6468. return 0
  6469. from backend.app.models.archive import PrintArchive
  6470. reconciled = 0
  6471. async with async_session() as db:
  6472. result = await db.execute(
  6473. select(PrintArchive).where(
  6474. PrintArchive.printer_id == printer_id,
  6475. PrintArchive.status == "printing",
  6476. )
  6477. )
  6478. active = list(result.scalars().all())
  6479. if not active:
  6480. return 0
  6481. logger = logging.getLogger(__name__)
  6482. for archive in active:
  6483. is_stale, reason = _is_active_archive_stale(archive, state)
  6484. if not is_stale:
  6485. continue
  6486. logger.info(
  6487. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  6488. printer_id,
  6489. archive.id,
  6490. archive.filename,
  6491. reason,
  6492. )
  6493. # Synthesised payload: minimal fields the on_print_complete chain
  6494. # needs. `_reconciled` marker lets downstream code distinguish this
  6495. # from a real MQTT-driven completion if it ever needs to (e.g. for
  6496. # metrics / debug logging). raw_data is the live printer state so
  6497. # the usage tracker can compare end-of-print remain% against the
  6498. # captured start values.
  6499. try:
  6500. await on_print_complete(
  6501. printer_id,
  6502. {
  6503. "status": "aborted",
  6504. "filename": archive.filename,
  6505. "subtask_name": archive.print_name or "",
  6506. "subtask_id": archive.subtask_id or "",
  6507. "raw_data": state.raw_data or {},
  6508. "_reconciled": True,
  6509. },
  6510. )
  6511. reconciled += 1
  6512. except Exception as e:
  6513. # Catch-all: a reconciliation failure must not block the
  6514. # printer's normal status flow. The archive stays in
  6515. # ``status="printing"`` and the next reconnect retries.
  6516. logger.warning(
  6517. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  6518. archive.id,
  6519. e,
  6520. )
  6521. return reconciled
  6522. # #2547: clearance left between the nozzle and the top of the print when the
  6523. # plate is commanded back into camera framing. The nozzle is parked away from
  6524. # the part by then, so this is belt-and-braces against a max_z_height that
  6525. # under-reports (e.g. a slicer that excludes a final Z hop).
  6526. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  6527. # How far below the restored position to drop the plate again afterwards, so
  6528. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  6529. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  6530. # on machines with less headroom.
  6531. _PLATE_PARK_DROP_MM = 100.0
  6532. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  6533. # this axis, so it is a proven-safe speed for the full travel.
  6534. _PLATE_RESTORE_FEEDRATE = 600
  6535. # Time allowed for the plate to reach the restored position before the camera
  6536. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  6537. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  6538. # How long `_background_finish_photo` waits for this producer. Must cover the
  6539. # settle window plus a worst-case RTSP grab (15s), and stay below the
  6540. # notification path's own photo wait so a slow producer degrades to a
  6541. # photo-less notification rather than a missed one. The chamber light's
  6542. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  6543. # camera_light.MAX_DELAY_SECONDS stays below it.
  6544. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  6545. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  6546. """The ``_active_prints`` keys a finished print may be registered under.
  6547. Matching how they were registered in on_print_start. Shared by
  6548. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  6549. to find the same binding.
  6550. """
  6551. possible_keys = []
  6552. # Try subtask_name variations first (most reliable for matching)
  6553. if subtask_name:
  6554. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  6555. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  6556. possible_keys.append((printer_id, subtask_name))
  6557. # Try filename variations
  6558. if filename:
  6559. # Extract just the filename if it's a path
  6560. fname = filename.split("/")[-1] if "/" in filename else filename
  6561. if fname.endswith(".3mf"):
  6562. possible_keys.append((printer_id, fname))
  6563. elif fname.endswith(".gcode"):
  6564. base_name = fname.rsplit(".", 1)[0]
  6565. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  6566. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6567. possible_keys.append((printer_id, fname))
  6568. else:
  6569. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  6570. possible_keys.append((printer_id, f"{fname}.3mf"))
  6571. possible_keys.append((printer_id, fname))
  6572. # Also try full path versions
  6573. if filename.endswith(".3mf"):
  6574. possible_keys.append((printer_id, filename))
  6575. elif filename.endswith(".gcode"):
  6576. base_name = filename.rsplit(".", 1)[0]
  6577. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6578. possible_keys.append((printer_id, filename))
  6579. else:
  6580. possible_keys.append((printer_id, f"{filename}.3mf"))
  6581. possible_keys.append((printer_id, filename))
  6582. return possible_keys
  6583. def _archive_name_forms(archive) -> set[str]:
  6584. """The names an archive could be echoed back as, in normalised form (#3240).
  6585. Its print name, and its filename with and without the 3MF extension.
  6586. """
  6587. forms = set()
  6588. if archive.print_name:
  6589. forms.add(_normalise_subtask_name(archive.print_name))
  6590. if archive.filename:
  6591. forms.add(_normalise_subtask_name(archive.filename))
  6592. for suffix in (".gcode.3mf", ".3mf"):
  6593. if archive.filename.lower().endswith(suffix):
  6594. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  6595. forms.discard("")
  6596. return forms
  6597. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  6598. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  6599. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  6600. from the plate recorded when the job was dispatched. Neither is touched:
  6601. ``on_print_complete`` pops both, which is why the finish-photo producer
  6602. calls this before its first await, while they are still there.
  6603. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  6604. archive, or that it only knows by a name -- and on any error: the producer
  6605. calls this before the ``try`` that always releases the photo consumer, so
  6606. it must not raise.
  6607. """
  6608. try:
  6609. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  6610. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  6611. if archive_id is None:
  6612. return None, None
  6613. return archive_id, _print_plate_ids.get(archive_id)
  6614. except Exception:
  6615. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  6616. return None, None
  6617. async def _max_z_for_current_print(
  6618. printer_id: int,
  6619. data: dict,
  6620. logger,
  6621. archive_id: int | None,
  6622. plate_id: int | None = None,
  6623. ) -> float | None:
  6624. """Height of the print that just finished on ``printer_id``, or None (#2547).
  6625. This number becomes the target of a real Z move, so every step here refuses
  6626. rather than guesses. A height belonging to some *other* print is the one
  6627. failure that could drive the nozzle into the model: 20 mm carried onto a
  6628. 200 mm print would command the plate up through the part.
  6629. Three independent things therefore have to agree before a height is
  6630. returned:
  6631. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  6632. when it started (see ``_bound_print``), never one found by name. A name
  6633. is not an identity: every plate of a multi-plate file shares one, and a
  6634. reprint reuses its archive row, so the newest archive with the right
  6635. name can be another plate of the same file. Support bundles show the
  6636. old name lookup doing exactly that (archive 288 for a print bound to
  6637. 169, 313 layers against 125), stopped only by the layer check below.
  6638. No binding, no move.
  6639. 2. **Identity.** The bound archive's name still has to be the finished
  6640. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  6641. because the printer echoes spaces as underscores (#3240). Exact: not a
  6642. substring, and not the completion check's tolerance for a truncated
  6643. echo.
  6644. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  6645. match the layer count the printer itself reported over MQTT for the print
  6646. that just ended. These come from genuinely different sources, so a
  6647. mismatch means the row is not this print, whatever its name says.
  6648. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  6649. plate of a multi-plate file reuses the archive row without updating its
  6650. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  6651. ``on_print_complete`` may already have flipped the status by the time we
  6652. run.
  6653. """
  6654. subtask_name = (data.get("subtask_name") or "").strip()
  6655. if not subtask_name:
  6656. # Nothing to identify the print by — refuse rather than fall back to
  6657. # "whatever ran last on this printer".
  6658. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  6659. return None
  6660. if archive_id is None:
  6661. logger.info(
  6662. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  6663. printer_id,
  6664. subtask_name,
  6665. )
  6666. return None
  6667. try:
  6668. from backend.app.models.archive import PrintArchive
  6669. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  6670. async with async_session() as db:
  6671. result = await db.execute(
  6672. select(PrintArchive).where(
  6673. PrintArchive.id == archive_id,
  6674. PrintArchive.printer_id == printer_id,
  6675. PrintArchive.status.in_(("printing", "completed")),
  6676. PrintArchive.deleted_at.is_(None),
  6677. )
  6678. )
  6679. archive = result.scalar_one_or_none()
  6680. if archive is None or not archive.file_path:
  6681. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  6682. return None
  6683. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  6684. logger.warning(
  6685. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  6686. printer_id,
  6687. archive_id,
  6688. subtask_name,
  6689. )
  6690. return None
  6691. client = printer_manager.get_client(printer_id)
  6692. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  6693. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  6694. logger.warning(
  6695. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  6696. "— refusing to move the plate on a height that may not be this print's",
  6697. printer_id,
  6698. archive.id,
  6699. archive.total_layers,
  6700. reported_layers,
  6701. )
  6702. return None
  6703. # Stored relative to the data directory, like every other archive path
  6704. # (#3240: this read a `data_dir` setting that does not exist).
  6705. path = app_settings.base_dir / archive.file_path
  6706. plate = plate_id or archive.plate_id or 1
  6707. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  6708. except Exception as e:
  6709. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  6710. return None
  6711. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  6712. """Raise the plate back into camera framing before the finish photo (#2547).
  6713. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  6714. the time ``gcode_state`` reaches FINISH the finished print sits far below
  6715. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  6716. This commands an absolute ``G1 Z`` back to just above the last printed
  6717. layer.
  6718. Absolute, not relative, is the whole safety argument. ``max_z_height +
  6719. clearance`` is a height the toolhead was physically at seconds earlier, so
  6720. it is inside the travel limits by construction and leaves the nozzle above
  6721. the part. It is also unambiguous across model families: Z is the
  6722. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  6723. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  6724. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  6725. (#2579).
  6726. Returns True if the move was sent and waited out, False if it was skipped.
  6727. """
  6728. client = printer_manager.get_client(printer_id)
  6729. if client is None:
  6730. return False
  6731. # Re-read state immediately before commanding motion. If the queue has
  6732. # already started the next print, the printer is no longer ours to move.
  6733. state = getattr(client, "state", None)
  6734. if state is None or state.state != "FINISH":
  6735. logger.info(
  6736. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  6737. printer_id,
  6738. getattr(state, "state", "unknown"),
  6739. )
  6740. return False
  6741. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  6742. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  6743. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  6744. return False
  6745. logger.info(
  6746. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  6747. printer_id,
  6748. target_z,
  6749. max_z_height,
  6750. _PLATE_RESTORE_CLEARANCE_MM,
  6751. _PLATE_RESTORE_SETTLE_SECONDS,
  6752. )
  6753. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  6754. return True
  6755. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  6756. """Drop the plate again after the finish photo (#2547).
  6757. Without this the user walks up to a finished print sitting just under the
  6758. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  6759. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  6760. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  6761. print homes anyway.
  6762. """
  6763. client = printer_manager.get_client(printer_id)
  6764. state = getattr(client, "state", None) if client else None
  6765. if client is None or state is None or state.state != "FINISH":
  6766. return
  6767. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  6768. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  6769. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  6770. """True if a queue item is about to take this printer (#2547).
  6771. The scheduler dispatches the next job the moment a print completes, and a
  6772. plate move interleaved with a print start is not a race worth having. The
  6773. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  6774. this window; this closes the head of it.
  6775. """
  6776. try:
  6777. from backend.app.models.print_queue import PrintQueueItem
  6778. async with async_session() as db:
  6779. result = await db.execute(
  6780. select(PrintQueueItem.id)
  6781. .where(
  6782. PrintQueueItem.printer_id == printer_id,
  6783. PrintQueueItem.status.in_(("pending", "printing")),
  6784. )
  6785. .limit(1)
  6786. )
  6787. return result.scalar_one_or_none() is not None
  6788. except Exception as e:
  6789. # Fail closed: if we can't tell, don't move the plate.
  6790. logging.getLogger(__name__).debug(
  6791. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  6792. )
  6793. return True
  6794. async def on_finish_photo_moment(printer_id: int, data: dict):
  6795. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  6796. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  6797. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  6798. fallback for prints that skip stage 22 (cancel, external-spool-only,
  6799. HMS halt, firmware variants). Grabs one frame via the same
  6800. external-camera / RTSP path the post-completion fallback uses, stores
  6801. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  6802. ``_background_finish_photo`` consume the cached bytes when it runs.
  6803. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  6804. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  6805. set to Smooth (#1721). No force-on now means the user's explicit
  6806. timelapse=off in the slicer send dialog is respected.
  6807. """
  6808. logger = logging.getLogger(__name__)
  6809. trigger = data.get("trigger", "unknown")
  6810. timelapse_was_active = bool(data.get("timelapse_was_active"))
  6811. logger.info(
  6812. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  6813. printer_id,
  6814. trigger,
  6815. timelapse_was_active,
  6816. )
  6817. # If a timelapse is actively recording, skip the pre-capture — the
  6818. # post-completion path will extract the last frame from the recorded
  6819. # video, which still provides the best framing (toolhead parked,
  6820. # before bed drop) without the per-layer parking side effects.
  6821. if timelapse_was_active:
  6822. logger.info(
  6823. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  6824. printer_id,
  6825. )
  6826. return
  6827. # #1790: register the producer-done event BEFORE the first await so the
  6828. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  6829. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  6830. # The `finally` below guarantees `set()` runs on every exit, including
  6831. # early returns and exceptions, so the consumer's bounded wait can't hang.
  6832. producer_done = asyncio.Event()
  6833. _stage22_finish_in_flight[printer_id] = producer_done
  6834. # #3240: also before the first await. On the FINISH-state path
  6835. # `on_print_complete` is dispatched right behind us and pops both the
  6836. # print's archive binding and its plate; read here, they are still there.
  6837. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  6838. # #2547: set once the plate has actually been raised, and read by the
  6839. # `finally` below. Declared out here so a failure anywhere after the move —
  6840. # a camera timeout, a DB error — still lowers the plate again.
  6841. restore_max_z: float | None = None
  6842. try:
  6843. async with async_session() as db:
  6844. from backend.app.api.routes.settings import get_setting
  6845. from backend.app.models.printer import Printer
  6846. capture_setting = await get_setting(db, "capture_finish_photo")
  6847. if capture_setting is not None and capture_setting.lower() != "true":
  6848. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  6849. return
  6850. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6851. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  6852. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6853. printer = result.scalar_one_or_none()
  6854. if printer is None:
  6855. logger.warning(
  6856. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  6857. printer_id,
  6858. )
  6859. return
  6860. frame_bytes: bytes | None = None
  6861. # #2708: the banked frame arrives already rotated — it comes from
  6862. # `_capture_snapshot_for_notification`, which rotates before returning.
  6863. # Every other source below is a raw grab. Tracking which lets us store
  6864. # exactly one rotation in `_stage22_finish_frames` either way.
  6865. frame_already_rotated = False
  6866. # On the FINISH-state path the End G-code has already run, and two very
  6867. # different situations arrive here needing opposite answers.
  6868. #
  6869. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  6870. # snippet may have ejected the plate — the scene in front of the camera
  6871. # is no longer the finished print, and no amount of moving the plate
  6872. # brings it back. Use the banked in-print frame instead.
  6873. #
  6874. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  6875. # than the camera frames well, and the toolhead is parked out of the
  6876. # way. That is the *best* moment available on firmware that never emits
  6877. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  6878. # back. Preferring the bank here unconditionally, as this code used to,
  6879. # is what shipped a mid-print photo with the toolhead over the part.
  6880. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  6881. banked = _inprint_frame_bank.get(printer_id)
  6882. if banked:
  6883. frame_bytes = banked
  6884. frame_already_rotated = True
  6885. logger.info(
  6886. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  6887. "frame (%d bytes) instead of a post-swap live grab",
  6888. len(banked),
  6889. )
  6890. else:
  6891. logger.warning(
  6892. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  6893. "in-print bank is empty — falling back to a live grab, which may show a "
  6894. "swapped or empty plate",
  6895. printer_id,
  6896. )
  6897. # `restore_max_z` is set only once the plate is actually up, because the
  6898. # `finally` reads it to decide whether it owes a move back down.
  6899. #
  6900. # Never on a print whose End G-code Bambuddy injected, even when the bank
  6901. # came up empty above: that machine may have just ejected its plate, and
  6902. # driving Z into whatever a swap mechanism is doing is not a risk worth
  6903. # taking for a photo of a bed we already know may be bare.
  6904. if (
  6905. frame_bytes is None
  6906. and trigger == "finish_state"
  6907. and restore_plate_enabled
  6908. and not print_dispatch_context.end_gcode_injected(printer_id)
  6909. ):
  6910. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  6911. if wants_restore is None:
  6912. logger.info(
  6913. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  6914. printer_id,
  6915. )
  6916. elif await _plate_restore_is_blocked_by_queue(printer_id):
  6917. logger.info(
  6918. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  6919. printer_id,
  6920. )
  6921. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  6922. restore_max_z = wants_restore
  6923. # Chamber light for the live capture below (#1655). The banked frame
  6924. # above was taken without it, like every in-print bank.
  6925. async with camera_light(printer if frame_bytes is None else None):
  6926. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  6927. from backend.app.api.routes.camera import live_frame_for_capture
  6928. from backend.app.services.external_camera import capture_frame
  6929. # #2707: this used to collide with the live view and fail, which is
  6930. # how finish-photo notifications went out with no image attached.
  6931. # Leaving frame_bytes None keeps the rest of the fallback chain.
  6932. defer, buffered = live_frame_for_capture(printer_id)
  6933. if defer:
  6934. frame_bytes = buffered
  6935. else:
  6936. frame_bytes = await capture_frame(
  6937. printer.external_camera_url,
  6938. printer.external_camera_type or "mjpeg",
  6939. snapshot_url=printer.external_camera_snapshot_url,
  6940. )
  6941. if frame_bytes:
  6942. logger.info(
  6943. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  6944. len(frame_bytes),
  6945. )
  6946. elif frame_bytes is None:
  6947. from backend.app.api.routes.camera import get_buffered_frame
  6948. buffered = get_buffered_frame(printer_id)
  6949. if buffered:
  6950. frame_bytes = buffered
  6951. logger.info(
  6952. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  6953. len(frame_bytes),
  6954. )
  6955. else:
  6956. from backend.app.services.camera import capture_camera_frame_bytes
  6957. frame_bytes = await capture_camera_frame_bytes(
  6958. ip_address=printer.ip_address,
  6959. access_code=printer.access_code,
  6960. model=printer.model,
  6961. timeout=15,
  6962. )
  6963. if frame_bytes:
  6964. logger.info(
  6965. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  6966. len(frame_bytes),
  6967. )
  6968. if frame_bytes:
  6969. if not frame_already_rotated:
  6970. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  6971. _stage22_finish_frames[printer_id] = frame_bytes
  6972. else:
  6973. logger.warning(
  6974. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  6975. printer_id,
  6976. )
  6977. except Exception as e:
  6978. logger.warning(
  6979. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  6980. printer_id,
  6981. e,
  6982. )
  6983. finally:
  6984. # #2547: we raised the plate, so we own lowering it — including when the
  6985. # capture above failed or threw partway through.
  6986. if restore_max_z is not None:
  6987. try:
  6988. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  6989. except Exception as e:
  6990. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6991. # #1790: always unblock the consumer's bounded wait — whether we stored
  6992. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  6993. # dict entry by the consumer doesn't affect signalling.
  6994. producer_done.set()
  6995. def _subtask_name_from_filename(filename: str) -> str:
  6996. """Recover the subtask name a print command would have carried for *filename*.
  6997. The dispatcher derives the printer-facing subtask name from the archive's
  6998. file name, so stripping the extensions back off gives the value MQTT echoes
  6999. on completion. Only the two extensions Bambuddy actually stores are removed,
  7000. and in the order they nest (``.gcode.3mf``), so a model whose own name
  7001. contains a dot -- ``My.Model.3mf`` -- keeps it.
  7002. """
  7003. name = PurePosixPath(filename).name
  7004. for suffix in (".3mf", ".gcode"):
  7005. if name.lower().endswith(suffix):
  7006. name = name[: -len(suffix)]
  7007. return name
  7008. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  7009. """Whether the subtask name is the printed 3MF's own file name.
  7010. A print started from the printer's screen reports the same full name, with
  7011. its extension, as both subtask and file (#3009). A dispatched print reports
  7012. a bare subtask name; one that merely ends in ".3mf" can be a model named
  7013. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  7014. """
  7015. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  7016. return False
  7017. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  7018. # How the printer marks a subtask name it had to cut short. Observed on real
  7019. # hardware at ~100 characters, but the cut-off is not a fixed character count
  7020. # (a name with multibyte characters came back at 98), so match the marker
  7021. # rather than a length.
  7022. _SUBTASK_TRUNCATION_MARKER = "..."
  7023. def _normalise_subtask_name(name: str) -> str:
  7024. """Canonical form for comparing a dispatched name against MQTT's echo.
  7025. The printer does not echo the name back verbatim: it substitutes
  7026. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  7027. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  7028. The 3MF lookup in this module has always known that -- it builds
  7029. space-to-underscore variants of every candidate filename, and its
  7030. directory search normalises both sides before comparing. This exists so
  7031. the completion check reads the same rule from the same place instead of
  7032. growing its own, which is exactly how it came to disagree (#2829).
  7033. A space at either end is substituted too: ``Part .gcode.3mf`` is
  7034. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  7035. are dropped after the substitution so both sides agree (#3241).
  7036. """
  7037. return name.strip().replace(" ", "_").strip("_").casefold()
  7038. def _3mf_files_for_print(paths: list[str], search_term: str) -> list[str]:
  7039. """The 3MF files of the printer's folder listings that are this print's.
  7040. A file of the print's own name wins, in whichever folder. Only without one
  7041. is a file that merely contains the name taken, and then only when it is
  7042. the one such file: "Cube_large.3mf" is not "Cube"'s file, and of several
  7043. candidates none can be told apart. Paths keep the listings' order.
  7044. """
  7045. threemf = [path for path in paths if path.lower().endswith(".3mf")]
  7046. exact = [path for path in threemf if _subtask_names_match(_subtask_name_from_filename(path), search_term)]
  7047. if exact:
  7048. return exact
  7049. term = _normalise_subtask_name(search_term)
  7050. partial = [path for path in threemf if term in _normalise_subtask_name(PurePosixPath(path).name)]
  7051. if len(partial) > 1:
  7052. logging.getLogger(__name__).info(
  7053. "Several 3MF files contain %r and none is named for it: %s", search_term, partial
  7054. )
  7055. return []
  7056. return partial
  7057. def _subtask_names_match(expected: str, observed: str) -> bool:
  7058. """Whether two subtask names describe the same print.
  7059. Beyond the space/underscore substitution, the printer truncates long names
  7060. and marks the cut with ``...``. A truncated echo has to count as a match or
  7061. every print with a long name strands its queue item the same way.
  7062. """
  7063. expected_n = _normalise_subtask_name(expected)
  7064. observed_n = _normalise_subtask_name(observed)
  7065. if expected_n == observed_n:
  7066. return True
  7067. # Either side can be the truncated one: the printer truncates what it
  7068. # echoes, and an archive whose own filename was recorded from a previous
  7069. # truncated echo carries the marker too.
  7070. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  7071. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  7072. continue
  7073. # The full side has lost its edge underscores; a cut that lands right
  7074. # after one keeps it, so drop it here too (#3241). Nothing left before
  7075. # the marker is no evidence of anything, and must not match every name.
  7076. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  7077. if kept and full.startswith(kept):
  7078. return True
  7079. return False
  7080. async def _queue_item_dispatched_name(db, item) -> str:
  7081. """The subtask name *item* was dispatched under, or "" when unknowable.
  7082. A row with no archive, or an archive with no file name, is unverifiable
  7083. rather than wrong; every caller answers that with its permissive branch.
  7084. """
  7085. if item.archive_id is None:
  7086. return ""
  7087. from backend.app.models.archive import PrintArchive
  7088. archive = await db.get(PrintArchive, item.archive_id)
  7089. if archive is None or not archive.filename:
  7090. return ""
  7091. return _subtask_name_from_filename(archive.filename)
  7092. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  7093. """Whether this completion event is plausibly about *item*'s print.
  7094. The caller finds its queue row by printer and ``status='printing'`` alone,
  7095. which is all a completion event gives it -- there is no run identifier in
  7096. the MQTT payload to match on. That makes the lookup indiscriminate: any
  7097. completion delivered for this printer closes whichever row happens to be
  7098. printing, however unrelated. Comparing the subtask name against the archive
  7099. the row was dispatched with costs one primary-key load and rules that out.
  7100. Deliberately permissive: it answers False only on a positive disagreement
  7101. between two names we actually have. A row with no archive, an archive with
  7102. no file name, or an event with no subtask name is unverifiable rather than
  7103. wrong, and refusing those would strand the item in ``printing`` and wedge
  7104. the printer's queue -- a worse failure than the one being prevented.
  7105. """
  7106. observed = (data.get("subtask_name") or "").strip()
  7107. if not observed or item.archive_id is None:
  7108. return True
  7109. from backend.app.models.archive import PrintArchive
  7110. archive = await db.get(PrintArchive, item.archive_id)
  7111. if archive is None or not archive.filename:
  7112. return True
  7113. expected = _subtask_name_from_filename(archive.filename)
  7114. if not expected or _subtask_names_match(expected, observed):
  7115. return True
  7116. logging.getLogger(__name__).warning(
  7117. "Ignoring print completion for queue item %s: it was dispatched as %r "
  7118. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  7119. "printing rather than closing a run this event is not about.",
  7120. item.id,
  7121. expected,
  7122. archive.id,
  7123. archive.filename,
  7124. observed,
  7125. )
  7126. return False
  7127. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  7128. """Spend the 3MF download cache on a still-empty fallback archive.
  7129. ``on_print_complete`` drops the cache as its first act, which deletes the
  7130. file. If the cover endpoint (or anything else) pulled the 3MF while the
  7131. print ran and the archive never got one, this is the last moment those bytes
  7132. exist (#2957).
  7133. """
  7134. logger = logging.getLogger(__name__)
  7135. names = [
  7136. n
  7137. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  7138. if n
  7139. ]
  7140. for name in names:
  7141. try:
  7142. cached = get_cached_3mf(printer_id, name)
  7143. # The print has ended: its completion prices the archive, so no
  7144. # print-start estimate is scheduled to race it.
  7145. if cached and await try_recover_fallback_archive(printer_id, name, cached, price=False):
  7146. return
  7147. except Exception as e:
  7148. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  7149. # Longest the print's end waits for its file to be deleted from the SD card
  7150. _SD_CLEANUP_BUDGET_SECONDS = 45.0
  7151. async def _cleanup_sd_card_after_print(
  7152. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  7153. ) -> None:
  7154. """Delete a finished print's file from the printer's SD card."""
  7155. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  7156. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  7157. # auto-start files found in root on power cycle, causing ghost prints.
  7158. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  7159. try:
  7160. if subtask_name:
  7161. archive_filename: str | None = None
  7162. async with async_session() as db:
  7163. from backend.app.models.archive import PrintArchive
  7164. from backend.app.models.printer import Printer
  7165. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7166. printer = result.scalar_one_or_none()
  7167. if archive_id:
  7168. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  7169. archive_filename = archive_row.scalar_one_or_none()
  7170. if printer:
  7171. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  7172. from backend.app.utils.filename import derive_remote_filename
  7173. # Primary candidate: the exact path the dispatcher uploaded to
  7174. # (derived from archive.filename via the same rule as upload).
  7175. # Without it, a library row that ended up with a doubled
  7176. # .gcode.3mf (#1542) leaves the real file behind because the
  7177. # subtask_name + ext fallbacks below don't match what's on the
  7178. # SD card. Fallbacks remain for archive-less prints (subtask
  7179. # never resolved to an archive) and for older naming variants.
  7180. candidate_paths: list[str] = []
  7181. if archive_filename:
  7182. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  7183. for ext in (".3mf", ".gcode"):
  7184. fallback = f"/{subtask_name}{ext}"
  7185. if fallback not in candidate_paths:
  7186. candidate_paths.append(fallback)
  7187. # Three outcomes track across all candidates so the final log
  7188. # line reflects what actually happened. The A1 in #1721 always
  7189. # ends here with ``any_not_found=True`` and the others False
  7190. # — its firmware auto-cleans the SD card before our cleanup
  7191. # runs, every candidate FTP-DELE returns 550, and the old
  7192. # code burned 3 retries × 2 s × 3 candidates per print
  7193. # logging a misleading "may linger" WARNING on a successful
  7194. # print.
  7195. any_deleted = False
  7196. any_real_failure = False
  7197. any_not_found = False
  7198. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  7199. for remote_path in candidate_paths:
  7200. if PurePosixPath(remote_path).name.lower() in files_in_use:
  7201. logger.info(
  7202. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  7203. remote_path,
  7204. printer.name,
  7205. )
  7206. continue
  7207. # Retry only the FAILED case — 550 NOT_FOUND will never
  7208. # recover by waiting, so a "file isn't here" answer
  7209. # advances immediately to the next candidate without
  7210. # consuming the retry budget.
  7211. for attempt in range(1, 4):
  7212. try:
  7213. delete_result = await delete_file_async(
  7214. printer.ip_address,
  7215. printer.access_code,
  7216. remote_path,
  7217. printer_model=printer.model,
  7218. )
  7219. except Exception as e:
  7220. delete_result = DeleteResult.FAILED
  7221. logger.warning(
  7222. "SD card cleanup attempt %d/3 raised for %s: %s",
  7223. attempt,
  7224. remote_path,
  7225. e,
  7226. )
  7227. if delete_result == DeleteResult.DELETED:
  7228. any_deleted = True
  7229. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  7230. break
  7231. if delete_result == DeleteResult.NOT_FOUND:
  7232. any_not_found = True
  7233. break # 550 will not recover; try next candidate
  7234. # FAILED: real error — retry with backoff, then give up
  7235. if attempt < 3:
  7236. await asyncio.sleep(2)
  7237. else:
  7238. any_real_failure = True
  7239. logger.warning(
  7240. "SD card cleanup failed after 3 attempts for %s "
  7241. "(network/auth/transient error — file may linger on SD card)",
  7242. remote_path,
  7243. )
  7244. if not any_deleted and not any_real_failure and any_not_found:
  7245. # Every candidate said "not here." Either the printer
  7246. # firmware swept the SD card itself (common on A1) or the
  7247. # dispatcher's upload path doesn't match our candidate
  7248. # rule. Either way: nothing to clean up, no warning.
  7249. logger.debug(
  7250. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  7251. "(printer likely self-cleaned)",
  7252. printer.name,
  7253. )
  7254. except Exception as e:
  7255. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  7256. async def on_print_complete(printer_id: int, data: dict):
  7257. """Handle print completion - update the archive status.
  7258. The printer counts as printing until the print's usage is booked (or this
  7259. ends), so the AMS remain% weight sync can't charge it a second time while
  7260. the usage tracker works (WU-3). Marked before the first await.
  7261. """
  7262. from backend.app.services.usage_tracker import done_completing, mark_completing
  7263. mark_completing(printer_id)
  7264. try:
  7265. await _close_out_print(printer_id, data)
  7266. finally:
  7267. done_completing(printer_id)
  7268. async def _close_out_print(printer_id: int, data: dict):
  7269. import time
  7270. logger = logging.getLogger(__name__)
  7271. start_time = time.time()
  7272. def log_timing(section: str):
  7273. elapsed = time.time() - start_time
  7274. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  7275. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  7276. # A kill-switch stop sends its provider notification immediately. Keep the
  7277. # task so the later notification path can await it and avoid a duplicate;
  7278. # if that immediate attempt failed, the regular completion path retries.
  7279. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  7280. # Last chance before the bytes go: if this print's archive is still an empty
  7281. # fallback and something downloaded the 3MF while it ran, fill the archive in
  7282. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  7283. # below deletes the file (#2957).
  7284. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  7285. # A pending cool-off retry has nothing left to recover for — the cache is
  7286. # about to be dropped and the print is over.
  7287. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  7288. if retry_task and not retry_task.done():
  7289. retry_task.cancel()
  7290. # Drop the 3MF download cache for this printer (#972). The print is over,
  7291. # nothing else legitimately needs the bytes; keeping them would only risk
  7292. # handing a stale file to the next print if it reuses the same name.
  7293. clear_3mf_cache(printer_id)
  7294. try:
  7295. ws_data = {
  7296. "status": data.get("status"),
  7297. "filename": data.get("filename"),
  7298. "subtask_name": data.get("subtask_name"),
  7299. "timelapse_was_active": data.get("timelapse_was_active"),
  7300. }
  7301. await ws_manager.send_print_complete(printer_id, ws_data)
  7302. log_timing("WebSocket send_print_complete")
  7303. except Exception as e:
  7304. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  7305. # Capture user info before clearing (needed for print log entry)
  7306. _print_user_info = printer_manager.get_current_print_user(printer_id)
  7307. # Clear current print user tracking (Issue #206)
  7308. printer_manager.clear_current_print_user(printer_id)
  7309. # If the user explicitly stopped this print from the queue UI the printer will
  7310. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  7311. # correct "print stopped" notification/email is sent instead of a failure alert.
  7312. _raw_status = data.get("status", "completed")
  7313. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  7314. logger.info(
  7315. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  7316. _raw_status,
  7317. printer_id,
  7318. )
  7319. data = {**data, "status": "cancelled"}
  7320. elif printer_id in _kill_switch_stopped and _raw_status in ("failed", "aborted"):
  7321. logger.info(
  7322. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (stopped by the printer kill switch)",
  7323. _raw_status,
  7324. printer_id,
  7325. )
  7326. data = {**data, "status": "cancelled", "_kill_switch": True}
  7327. _user_stopped_printers.discard(printer_id)
  7328. _kill_switch_stopped.discard(printer_id)
  7329. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  7330. # may have left material on the bed: a user can cancel ten hours into a
  7331. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  7332. # touchscreen-stop reports `aborted` rather than `cancelled` because
  7333. # `_user_stopped_printers` is only populated when the user stops via the
  7334. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  7335. # which auto-dispatched the next queued print onto a fouled bed two seconds
  7336. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  7337. # Auto Off power cycles and Bambuddy restarts.
  7338. try:
  7339. notify_live_activities.print_finished(printer_id, data)
  7340. except Exception:
  7341. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  7342. _final_status = data.get("status", "completed")
  7343. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  7344. printer_manager.set_awaiting_plate_clear(printer_id, True)
  7345. # MQTT relay - publish print complete
  7346. try:
  7347. printer_info = printer_manager.get_printer(printer_id)
  7348. if printer_info:
  7349. await mqtt_relay.on_print_complete(
  7350. printer_id,
  7351. printer_info.name,
  7352. printer_info.serial_number,
  7353. data.get("filename", ""),
  7354. data.get("subtask_name", ""),
  7355. data.get("status", "completed"),
  7356. )
  7357. except Exception:
  7358. pass # Don't fail print complete callback if MQTT fails
  7359. filename = data.get("filename", "")
  7360. subtask_name = data.get("subtask_name", "")
  7361. if not filename and not subtask_name:
  7362. # Which print ended can't be told: the printer reported no name since
  7363. # Bambuddy started (a print that failed while preparing, a calibration).
  7364. # Charge nothing, but close the print session, which otherwise kept the
  7365. # AMS weight sync off until the next print (AS-5). A print archived as
  7366. # running is closed and charged by the reconnect reconcile.
  7367. logger.warning("Print complete without filename or subtask_name")
  7368. try:
  7369. from backend.app.services.usage_tracker import discard_session
  7370. async with async_session() as db:
  7371. await discard_session(db, printer_id)
  7372. except Exception as e:
  7373. logger.warning("Failed to clear print session for printer %s: %s", printer_id, e)
  7374. return
  7375. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  7376. # Build list of possible keys to try (matching how they were registered in on_print_start)
  7377. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  7378. # Find the archive for this print
  7379. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  7380. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  7381. archive_id = None
  7382. for key in possible_keys:
  7383. archive_id = _active_prints.pop(key, None)
  7384. if archive_id:
  7385. _owned_print_archive_ids.discard(archive_id)
  7386. logger.info("Found archive %s with key %s", archive_id, key)
  7387. # Also clean up any other keys pointing to this archive
  7388. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  7389. for k in keys_to_remove:
  7390. _active_prints.pop(k, None)
  7391. break
  7392. # The archive bound when the print started, before the name search below.
  7393. # Only this one may give the finish-photo plate restore a height (#3240):
  7394. # the search matches names by substring.
  7395. bound_archive_id = archive_id
  7396. if not archive_id:
  7397. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  7398. async with async_session() as db:
  7399. from backend.app.models.archive import PrintArchive
  7400. # Try matching by subtask_name (stored as print_name) first. The
  7401. # same name rule as the queue's completion check: a name inside
  7402. # another ("Clip" in "Cable Clip") is a different print, and the
  7403. # printer's underscores for spaces and truncation still match.
  7404. if subtask_name:
  7405. printing = await db.scalars(
  7406. select(PrintArchive)
  7407. .where(PrintArchive.printer_id == printer_id)
  7408. .where(PrintArchive.status == "printing")
  7409. .order_by(PrintArchive.created_at.desc())
  7410. )
  7411. # A print started from the printer's screen reports its file
  7412. # name, extensions included, as the subtask (#3009).
  7413. reported = {subtask_name, _subtask_name_from_filename(subtask_name)}
  7414. archive = next(
  7415. (
  7416. candidate
  7417. for candidate in printing
  7418. if any(
  7419. (candidate.print_name and _subtask_names_match(candidate.print_name, name))
  7420. or (
  7421. candidate.filename
  7422. and _subtask_names_match(_subtask_name_from_filename(candidate.filename), name)
  7423. )
  7424. for name in reported
  7425. )
  7426. ),
  7427. None,
  7428. )
  7429. if archive:
  7430. archive_id = archive.id
  7431. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  7432. # Also try by filename
  7433. if not archive_id and filename:
  7434. result = await db.execute(
  7435. select(PrintArchive)
  7436. .where(PrintArchive.printer_id == printer_id)
  7437. .where(PrintArchive.filename == filename)
  7438. .where(PrintArchive.status == "printing")
  7439. .order_by(PrintArchive.created_at.desc())
  7440. .limit(1)
  7441. )
  7442. archive = result.scalar_one_or_none()
  7443. if archive:
  7444. archive_id = archive.id
  7445. # Bounded: a printer whose FTP hangs on DELE took up to 3 candidates x 3
  7446. # attempts x a 60 s timeout, about nine minutes, before the queue item was
  7447. # closed below. The stranded-job closer gives up after five and closed it
  7448. # first, so the job's auto-off and its billing never ran. Inline rather
  7449. # than in the background, so the next job of the same file isn't released
  7450. # (and uploaded under the name being deleted) while the cleanup still
  7451. # works on it. A delete already sent may still finish in its FTP thread
  7452. # after the cutoff, as one past delete_file_async's own timeout always did.
  7453. try:
  7454. await asyncio.wait_for(
  7455. _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger),
  7456. timeout=_SD_CLEANUP_BUDGET_SECONDS,
  7457. )
  7458. except TimeoutError:
  7459. logger.warning(
  7460. "SD card cleanup on printer %s took over %ss; leaving the file there and closing the print",
  7461. printer_id,
  7462. _SD_CLEANUP_BUDGET_SECONDS,
  7463. )
  7464. log_timing("SD card cleanup")
  7465. # Update queue item status early — must run before the archive_id early-return
  7466. # so queue items don't get stuck in "printing" when archive lookup fails.
  7467. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  7468. queue_item_id = None
  7469. billing_run_id: str | None = None
  7470. billing_user_id: int | None = None
  7471. billing_cost_center_id: int | None = None
  7472. billing_plate_id: int | None = None
  7473. queue_status = None
  7474. queue_auto_off = False
  7475. try:
  7476. from backend.app.core.database import run_with_retry
  7477. from backend.app.models.print_queue import PrintQueueItem
  7478. async def _update_queue_status(db):
  7479. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  7480. nonlocal queue_item_id, queue_status, queue_auto_off
  7481. result = await db.execute(
  7482. select(PrintQueueItem)
  7483. .where(PrintQueueItem.printer_id == printer_id)
  7484. .where(PrintQueueItem.status == "printing")
  7485. )
  7486. printing_items = list(result.scalars().all())
  7487. if len(printing_items) > 1:
  7488. logger.warning(
  7489. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  7490. printer_id,
  7491. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  7492. )
  7493. item = printing_items[0] if printing_items else None
  7494. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  7495. return
  7496. if item:
  7497. queue_status = data.get("status", "completed")
  7498. # MQTT sends "aborted" for cancelled prints; normalise to
  7499. # "cancelled" so it matches the queue schema Literal.
  7500. if queue_status == "aborted":
  7501. queue_status = "cancelled"
  7502. item.status = queue_status
  7503. item.completed_at = datetime.now(timezone.utc)
  7504. if queue_status == "failed" and not item.error_message:
  7505. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  7506. # Bump usage counters on the source library file so admins can
  7507. # sort by "last printed" and (eventually) auto-purge stale
  7508. # files — #1008.
  7509. await _bump_library_file_usage_if_completed(db, item, queue_status)
  7510. await db.commit()
  7511. queue_item_id = item.id
  7512. billing_run_id = item.billing_run_id
  7513. billing_user_id = item.created_by_id
  7514. billing_cost_center_id = item.cost_center_id
  7515. billing_plate_id = item.plate_id
  7516. queue_auto_off = item.auto_off_after
  7517. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  7518. await run_with_retry(_update_queue_status, label="queue status update")
  7519. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  7520. # their own sessions and have their own error handling — no retry needed.
  7521. if queue_item_id is not None:
  7522. # Batch orders (#342): this run may have been the last one an order
  7523. # owed. Re-evaluate here rather than lazily on read, so a finished
  7524. # order reports itself complete without someone opening the page.
  7525. try:
  7526. from backend.app.services.print_batch import refresh_batch_status_for_item
  7527. async with async_session() as db:
  7528. await refresh_batch_status_for_item(db, queue_item_id)
  7529. await db.commit()
  7530. except Exception as e:
  7531. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  7532. # MQTT relay - publish queue job completed
  7533. try:
  7534. printer_info = printer_manager.get_printer(printer_id)
  7535. await mqtt_relay.on_queue_job_completed(
  7536. job_id=queue_item_id,
  7537. filename=filename or subtask_name,
  7538. printer_id=printer_id,
  7539. printer_name=printer_info.name if printer_info else "Unknown",
  7540. status=queue_status,
  7541. )
  7542. except Exception:
  7543. pass # Don't fail if MQTT fails
  7544. # Check if queue is now empty and send notification
  7545. try:
  7546. from sqlalchemy import func as sa_func
  7547. async with async_session() as db:
  7548. count_result = await db.execute(
  7549. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  7550. )
  7551. pending_count = count_result.scalar() or 0
  7552. if pending_count == 0:
  7553. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  7554. completed_result = await db.execute(
  7555. select(sa_func.count(PrintQueueItem.id)).where(
  7556. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  7557. PrintQueueItem.completed_at >= today_start,
  7558. )
  7559. )
  7560. completed_count = completed_result.scalar() or 1
  7561. await notification_service.on_queue_completed(
  7562. completed_count=completed_count,
  7563. db=db,
  7564. )
  7565. except Exception:
  7566. pass # Don't fail if notification fails
  7567. # Handle auto_off_after - power off printer if the queue item opted
  7568. # in. Delegates to the smart-plug manager so the off honours each
  7569. # plug's configured strategy (time delay or temperature threshold),
  7570. # is cancelled if the printer starts printing again, and never cuts
  7571. # power on a loaded print (#1890). Previously an inline block here
  7572. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  7573. # timeout regardless of print state — cutting a touchscreen reprint.
  7574. if queue_auto_off:
  7575. try:
  7576. async with async_session() as db:
  7577. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  7578. except Exception as e:
  7579. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  7580. except Exception as e:
  7581. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  7582. log_timing("Queue item update")
  7583. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  7584. # Must run before archive_id early-return so it fires for all prints (including
  7585. # prints started from BambuStudio/touchscreen that have no archive).
  7586. if data.get("status") == "completed":
  7587. try:
  7588. from backend.app.api.routes.settings import get_setting
  7589. async with async_session() as db:
  7590. threshold_str = await get_setting(db, "bed_cooled_threshold")
  7591. threshold = float(threshold_str) if threshold_str else 35.0
  7592. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  7593. async with async_session() as db:
  7594. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  7595. if providers:
  7596. _bed_cool_waiters[printer_id] = {
  7597. "threshold": threshold,
  7598. "filename": filename or subtask_name or "",
  7599. "registered_at": time.time(),
  7600. }
  7601. logger.info(
  7602. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  7603. printer_id,
  7604. threshold,
  7605. )
  7606. else:
  7607. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  7608. except Exception as e:
  7609. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  7610. # Capture the slicer estimate before usage tracking runs. The tracker may
  7611. # update archive.cost with this run's measured cost; billing partial runs
  7612. # against that already-partial value would discount the charge twice.
  7613. billing_planned_grams: float | None = None
  7614. billing_base_cost: float | None = None
  7615. if archive_id:
  7616. try:
  7617. async with async_session() as db:
  7618. from backend.app.models.archive import PrintArchive
  7619. billing_archive = await db.get(PrintArchive, archive_id)
  7620. if billing_archive:
  7621. billing_path = (
  7622. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  7623. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7624. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  7625. billing_archive,
  7626. billing_path,
  7627. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  7628. )
  7629. except Exception as e:
  7630. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  7631. # --- Track filament consumption (must run before archive_id early-return so usage
  7632. # is recorded even when auto-archive is disabled) ---
  7633. usage_results: list[dict] = []
  7634. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  7635. stored_ams_mapping = data.get("ams_mapping")
  7636. # Fallback to _print_ams_mappings for queue/reprint (set before print starts).
  7637. # Drained either way, like the plate below: left over, it would be read by
  7638. # the archive's next run, dispatched without a mapping.
  7639. registered_ams_mapping = _print_ams_mappings.pop(archive_id, None) if archive_id else None
  7640. if not stored_ams_mapping:
  7641. stored_ams_mapping = registered_ams_mapping
  7642. # Always drain the plate_id register on completion — the session already
  7643. # consumed it at print-start injection; leaving it would leak into the next
  7644. # print on the same archive_id (rare but possible with reprints) (#1697).
  7645. # Capture the popped value so the completion notification can scope the
  7646. # archive-level (summed-across-plates per #1593) filament + time totals
  7647. # down to the single plate that was actually printed (#1785).
  7648. notify_plate_id: int | None = None
  7649. if archive_id:
  7650. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  7651. # The start estimate must not outlive the real cost written below (COST-4).
  7652. if archive_id:
  7653. await _settle_archive_cost_estimate(archive_id)
  7654. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  7655. try:
  7656. async with async_session() as db:
  7657. from backend.app.api.routes.settings import get_setting
  7658. _spoolman_on = await get_setting(db, "spoolman_enabled")
  7659. if not _spoolman_on or _spoolman_on.lower() != "true":
  7660. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  7661. async with async_session() as db:
  7662. usage_results = await usage_on_print_complete(
  7663. printer_id,
  7664. data,
  7665. printer_manager,
  7666. db,
  7667. archive_id=archive_id,
  7668. ams_mapping=stored_ams_mapping,
  7669. )
  7670. if usage_results:
  7671. await ws_manager.broadcast(
  7672. {
  7673. "type": "spool_usage_logged",
  7674. "printer_id": printer_id,
  7675. "usage": usage_results,
  7676. }
  7677. )
  7678. log_timing("Usage tracker")
  7679. except Exception as e:
  7680. logger.warning("Usage tracker on_print_complete failed: %s", e)
  7681. # Drop the print-start context unconditionally — the Spoolman branch above
  7682. # skips the internal tracker entirely, so nothing else would clear what
  7683. # print start captured, and a row surviving its print would be restored
  7684. # onto the next one after a restart.
  7685. try:
  7686. from backend.app.services.usage_tracker import discard_session
  7687. async with async_session() as db:
  7688. await discard_session(db, printer_id)
  7689. except Exception as e:
  7690. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  7691. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  7692. # A partial run's cost from the Spoolman spools it was charged to; the
  7693. # built-in inventory's comes in usage_results.
  7694. spoolman_run_cost: float | None = None
  7695. if archive_id:
  7696. if data.get("status") == "completed":
  7697. try:
  7698. await _report_spoolman_usage(printer_id, archive_id)
  7699. log_timing("Spoolman usage report")
  7700. except Exception as e:
  7701. logger.warning("Spoolman usage reporting failed: %s", e)
  7702. else:
  7703. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  7704. try:
  7705. async with async_session() as db:
  7706. spoolman_run_cost = await _cleanup_spoolman_tracking(
  7707. printer_id,
  7708. archive_id,
  7709. db,
  7710. last_layer_num=data.get("last_layer_num"),
  7711. last_progress=data.get("last_progress"),
  7712. )
  7713. except Exception as e:
  7714. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  7715. await _release_archived_spoolman_slots(printer_id)
  7716. log_timing("Filament usage tracking")
  7717. if not archive_id:
  7718. # The printer's own calibration run has no archive by design, so this
  7719. # arrives here every time one finishes. Returning before the no-archive
  7720. # notification keeps a calibration from being announced as a finished
  7721. # print. Everything above this point has already run — the plate-clear
  7722. # gate, the queue reconciliation, the SD-card cleanup — so only the
  7723. # notification is skipped.
  7724. if is_internal_printer_job(filename, subtask_name):
  7725. logger.info(
  7726. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  7727. filename,
  7728. subtask_name,
  7729. )
  7730. return
  7731. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  7732. # Still send print-complete/failed/stopped notifications even without an archive.
  7733. # Try to enrich with queue/library-file data so user-specific emails work too.
  7734. async def _notify_no_archive():
  7735. try:
  7736. async with async_session() as db:
  7737. from backend.app.models.library import LibraryFile
  7738. from backend.app.models.print_queue import PrintQueueItem
  7739. from backend.app.models.printer import Printer
  7740. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7741. printer_obj = result.scalar_one_or_none()
  7742. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  7743. # Only the queue item this completion itself closed (the
  7744. # reconciliation above, which checks the run belongs to it).
  7745. # A print started outside Bambuddy closed none, and must not
  7746. # borrow an earlier job's owner, email or times.
  7747. no_archive_data: dict | None = None
  7748. try:
  7749. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  7750. if queue_item:
  7751. no_archive_data = {"created_by_id": queue_item.created_by_id}
  7752. # How long it really ran, as the archive path reports it (#1198).
  7753. started = to_naive_utc(queue_item.started_at)
  7754. ended = to_naive_utc(queue_item.completed_at)
  7755. # Not for a completion reconciled at reconnect: it
  7756. # ended at an unknown time while the printer was
  7757. # offline, and "now" is the reconnect (DB-C9).
  7758. if (
  7759. not data.get("_reconciled")
  7760. and started
  7761. and ended
  7762. and (ended - started).total_seconds() > 0
  7763. ):
  7764. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  7765. # Estimated time: the queue item caches it from its
  7766. # archive or library file; otherwise read the library
  7767. # file's metadata (LibraryFile has no column for it).
  7768. if queue_item.print_time_seconds:
  7769. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  7770. elif queue_item.library_file_id:
  7771. lib_result = await db.execute(
  7772. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  7773. )
  7774. lib_file = lib_result.scalar_one_or_none()
  7775. estimate = (
  7776. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  7777. )
  7778. if estimate:
  7779. no_archive_data["print_time_seconds"] = estimate
  7780. except Exception as lookup_err:
  7781. logger.debug(
  7782. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  7783. )
  7784. # Enrich with usage tracker results (captured in enclosing scope)
  7785. if usage_results:
  7786. if no_archive_data is None:
  7787. no_archive_data = {}
  7788. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7789. if total_from_usage > 0:
  7790. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7791. no_archive_data["usage_results"] = usage_results
  7792. # Try MQTT remaining_time for print duration when no queue/library data
  7793. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  7794. mqtt_remaining = data.get("remaining_time")
  7795. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  7796. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  7797. ps = data.get("status", "completed")
  7798. logger.info(
  7799. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  7800. )
  7801. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7802. await notification_service.on_print_complete(
  7803. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  7804. )
  7805. else:
  7806. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7807. # Send user-specific email if we have a created_by_id
  7808. if no_archive_data and no_archive_data.get("created_by_id"):
  7809. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7810. await _dispatch_user_print_email(
  7811. ps,
  7812. no_archive_data["created_by_id"],
  7813. p_name,
  7814. raw_filename,
  7815. db,
  7816. )
  7817. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  7818. except Exception as e:
  7819. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  7820. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  7821. return
  7822. log_timing("Archive lookup")
  7823. # Update archive status
  7824. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  7825. try:
  7826. async with async_session() as db:
  7827. service = ArchiveService(db)
  7828. status = data.get("status", "completed")
  7829. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  7830. if hms_errors:
  7831. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  7832. failure_reason = derive_failure_reason(status, hms_errors)
  7833. if data.get("_reconciled"):
  7834. # A reconciled completion closes out a stale archive at
  7835. # reconnect — it is not a user action, so don't mislabel it
  7836. # "userCancelled". It shares the stale-cleanup path's key
  7837. # (issue #2974) and records that the real end time is unknown,
  7838. # which is also why its logged duration is 0 (#2592).
  7839. failure_reason = "noStatusUpdate"
  7840. elif data.get("_kill_switch"):
  7841. # Not the user's cancel: the kill switch stopped a print that did
  7842. # not come from Bambuddy.
  7843. failure_reason = "killSwitch"
  7844. if failure_reason:
  7845. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  7846. elif status == "failed" and hms_errors:
  7847. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  7848. await service.update_archive_status(
  7849. archive_id,
  7850. status=status,
  7851. completed_at=(
  7852. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  7853. ),
  7854. failure_reason=failure_reason,
  7855. )
  7856. logger.info(
  7857. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  7858. )
  7859. await ws_manager.send_archive_updated(
  7860. {
  7861. "id": archive_id,
  7862. "status": status,
  7863. }
  7864. )
  7865. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  7866. # MQTT relay - publish archive updated
  7867. try:
  7868. await mqtt_relay.on_archive_updated(
  7869. archive_id=archive_id,
  7870. print_name=filename or subtask_name,
  7871. status=status,
  7872. )
  7873. except Exception:
  7874. pass # Don't fail if MQTT fails
  7875. except Exception as e:
  7876. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  7877. # Continue with other operations even if archive update fails
  7878. log_timing("Archive status update")
  7879. # Apply finance wallet charge or release reservations once. For all partial
  7880. # terminal states (failed, aborted at the printer display, or cancelled via
  7881. # Bambuddy) use this run's measured spool delta, falling back to the last
  7882. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  7883. # estimate and therefore cannot represent an interrupted run.
  7884. try:
  7885. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  7886. async with async_session() as db:
  7887. from backend.app.models.archive import PrintArchive
  7888. from backend.app.services.finance_billing import apply_print_charge_for_archive
  7889. archive = await db.get(PrintArchive, archive_id)
  7890. if archive and billing_run_id is None:
  7891. billing_run_id = getattr(archive, "billing_run_id", None)
  7892. if archive and archive.created_by_id is None and _print_user_info:
  7893. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  7894. await db.flush()
  7895. run_status = data.get("status", "completed")
  7896. last_progress = data.get("last_progress")
  7897. if last_progress is None:
  7898. last_progress = data.get("progress")
  7899. actual_run_grams = _compute_run_filament_grams(
  7900. run_status,
  7901. billing_planned_grams,
  7902. last_progress,
  7903. usage_results,
  7904. )
  7905. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  7906. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  7907. charged = await apply_print_charge_for_archive(
  7908. db,
  7909. archive_id,
  7910. charged_user_id=billing_user_id,
  7911. cost_center_id=(
  7912. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  7913. ),
  7914. print_queue_id=queue_item_id,
  7915. print_run_id=billing_run_id,
  7916. base_cost_override=billing_base_cost,
  7917. filament_usage=filament_usage,
  7918. )
  7919. await db.commit()
  7920. if charged:
  7921. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  7922. except Exception as e:
  7923. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  7924. printer_info = printer_manager.get_printer(printer_id)
  7925. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7926. billing_filename = filename or subtask_name or "Unknown"
  7927. billing_error = str(e)
  7928. try:
  7929. await ws_manager.broadcast(
  7930. {
  7931. "type": "billing_charge_failed",
  7932. "printer_id": printer_id,
  7933. "printer_name": billing_printer_name,
  7934. "filename": billing_filename,
  7935. "archive_id": archive_id,
  7936. }
  7937. )
  7938. except Exception as notification_error:
  7939. logger.error(
  7940. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  7941. archive_id,
  7942. notification_error,
  7943. )
  7944. async def _notify_billing_charge_failed() -> None:
  7945. try:
  7946. async with async_session() as notification_db:
  7947. await notification_service.on_billing_charge_failed(
  7948. printer_id,
  7949. billing_printer_name,
  7950. billing_filename,
  7951. archive_id,
  7952. billing_error,
  7953. notification_db,
  7954. )
  7955. except Exception as provider_error:
  7956. logger.error(
  7957. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  7958. archive_id,
  7959. provider_error,
  7960. exc_info=True,
  7961. )
  7962. spawn_background_task(
  7963. _notify_billing_charge_failed(),
  7964. name=f"billing-charge-failed-{archive_id}",
  7965. )
  7966. log_timing("Finance charge update")
  7967. # Write independent print log entry (separate table, never touches archives)
  7968. try:
  7969. async with async_session() as db:
  7970. from backend.app.models.archive import PrintArchive
  7971. from backend.app.services.print_log import record_archive_wear, write_log_entry
  7972. archive = await db.get(PrintArchive, archive_id)
  7973. if archive:
  7974. # Back-fill created_by_id on reprint (#730): reprint reuses the
  7975. # source archive row rather than creating a new one, so an
  7976. # archive that was auto-created from a printer-initiated
  7977. # print (created_by_id=NULL) would otherwise stay unattributed
  7978. # forever. When we have a print-session user AND the archive
  7979. # has no attribution yet, credit the current user. Never
  7980. # overwrite an existing attribution — the original uploader
  7981. # keeps ownership.
  7982. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  7983. if archive.created_by_id is None and _print_user_id is not None:
  7984. archive.created_by_id = _print_user_id
  7985. p_info = printer_manager.get_printer(printer_id)
  7986. # Per-run actuals — written to PrintLogEntry so stats reflect
  7987. # what THIS print actually used, not the source archive's
  7988. # first-run values (#1378). Helper handles the partial-print
  7989. # math (failed / cancelled / stopped get scaled to progress
  7990. # or to tracked spool deltas).
  7991. _run_status = data.get("status", "completed")
  7992. # #2614: scope the per-run estimate to the printed plate. For a
  7993. # multi-plate 3MF dispatched one plate at a time, the archive's
  7994. # filament/cost are the whole-file totals; the PrintLogEntry must
  7995. # reflect only this plate. No effect on single-plate archives (the
  7996. # plate estimate equals the whole-file value) or on the tracker
  7997. # path (measured spool deltas win in _compute_run_filament_grams).
  7998. _est_full_path = (
  7999. app_settings.base_dir / archive.file_path if archive.file_path else None
  8000. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  8001. # The plate that printed, as billing reads it: a reprint of
  8002. # another plate must not log the archive's first plate.
  8003. _est_grams, _est_cost = _plate_scoped_run_estimate(
  8004. archive,
  8005. _est_full_path,
  8006. billing_plate_id if billing_plate_id is not None else notify_plate_id,
  8007. )
  8008. _run_grams = _compute_run_filament_grams(
  8009. _run_status,
  8010. _est_grams,
  8011. data.get("last_progress", data.get("progress")),
  8012. usage_results,
  8013. )
  8014. # Per-run cost — prefer usage_results sum. For partial prints
  8015. # we deliberately skip the topup-to-estimate logic in
  8016. # usage_tracker (which assumes the print completed); the raw
  8017. # tracked-spool sum is closer to what THIS run actually cost.
  8018. _run_cost: float | None = None
  8019. if usage_results:
  8020. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  8021. if _run_cost is None and _run_status != "completed":
  8022. _run_cost = spoolman_run_cost
  8023. if _run_cost is None and _run_status == "completed":
  8024. _run_cost = _est_cost
  8025. from backend.app.models.printer import Printer as _Printer
  8026. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  8027. run_entry = await write_log_entry(
  8028. db,
  8029. archive_id=archive.id,
  8030. # Captured by _update_queue_status above; None for
  8031. # printer-initiated prints with no queue row. Batch
  8032. # cost/energy roll-up joins on it (#342).
  8033. queue_item_id=queue_item_id,
  8034. status=_run_status,
  8035. print_name=archive.print_name,
  8036. printer_name=p_info.name if p_info else None,
  8037. printer_id=printer_id,
  8038. started_at=archive.started_at,
  8039. completed_at=archive.completed_at,
  8040. filament_type=archive.filament_type,
  8041. filament_color=archive.filament_color,
  8042. filament_used_grams=_run_grams,
  8043. cost=_run_cost,
  8044. wear_cost_per_hour=_wear_rate,
  8045. failure_reason=archive.failure_reason,
  8046. thumbnail_path=archive.thumbnail_path,
  8047. created_by_id=archive.created_by_id,
  8048. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  8049. # Reconciled completions have an unknown real end time —
  8050. # log 0 duration instead of the whole disconnect gap (#2592).
  8051. reconciled=bool(data.get("_reconciled")),
  8052. )
  8053. await record_archive_wear(db, archive, run_entry)
  8054. await db.commit()
  8055. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  8056. except Exception as e:
  8057. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  8058. log_timing("Print log entry")
  8059. # Run slow operations as background tasks to avoid blocking the event loop
  8060. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  8061. async def _background_energy_calculation():
  8062. """Calculate and save energy usage in background.
  8063. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  8064. backend restart no longer loses per-print energy data).
  8065. """
  8066. try:
  8067. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  8068. async with async_session() as db:
  8069. from backend.app.models.archive import PrintArchive
  8070. archive = await db.get(PrintArchive, archive_id)
  8071. if archive is None:
  8072. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  8073. return
  8074. starting_kwh = archive.energy_start_kwh
  8075. if starting_kwh is None:
  8076. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  8077. return
  8078. candidates = await energy_plug_candidates(db, printer_id)
  8079. if not candidates:
  8080. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  8081. return
  8082. # Same ordering as the start reading, so the delta below is
  8083. # against the counter that produced `starting_kwh` (#2859).
  8084. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  8085. if selected is None:
  8086. logger.warning(
  8087. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  8088. printer_id,
  8089. ", ".join(plug.name for plug in candidates),
  8090. )
  8091. return
  8092. plug, energy = selected
  8093. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  8094. energy_used = round(energy["total"] - starting_kwh, 4)
  8095. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  8096. if energy_used < 0:
  8097. logger.warning(
  8098. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  8099. archive_id,
  8100. starting_kwh,
  8101. energy["total"],
  8102. )
  8103. return
  8104. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  8105. # Each hour of the print at the price of that hour (#1251). If
  8106. # that fails, the last price known, as before, rather than no
  8107. # energy at all. Read first: the session may be unusable after.
  8108. last_price = await stored_price(db)
  8109. try:
  8110. energy_cost_value = round(
  8111. await print_energy_cost(
  8112. db,
  8113. plug_id=archive.energy_start_plug_id,
  8114. start_at=archive.energy_start_at,
  8115. start_kwh=starting_kwh,
  8116. start_price=archive.energy_start_price,
  8117. end_kwh=energy["total"],
  8118. end_plug_id=plug.id,
  8119. price_now=await current_price(db),
  8120. ),
  8121. 3,
  8122. )
  8123. except Exception as e:
  8124. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  8125. energy_cost_value = round(energy_used * last_price, 3)
  8126. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  8127. # reprint doesn't visually clobber the source archive's energy data
  8128. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  8129. from sqlalchemy import func
  8130. from backend.app.models.print_log import PrintLogEntry
  8131. existing_runs = await db.scalar(
  8132. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  8133. )
  8134. if (existing_runs or 0) <= 1:
  8135. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  8136. # we just wrote for THIS print. Either way it's the first run.
  8137. archive.energy_kwh = energy_used
  8138. archive.energy_cost = energy_cost_value
  8139. # Backfill the latest PrintLogEntry for this archive with energy
  8140. # (write_log_entry above ran before this background task completed,
  8141. # so energy fields are still NULL on that row).
  8142. latest_run = await db.execute(
  8143. select(PrintLogEntry)
  8144. .where(PrintLogEntry.archive_id == archive_id)
  8145. .order_by(PrintLogEntry.id.desc())
  8146. .limit(1)
  8147. )
  8148. run_row = latest_run.scalar_one_or_none()
  8149. if run_row is not None:
  8150. run_row.energy_kwh = energy_used
  8151. run_row.energy_cost = energy_cost_value
  8152. await db.commit()
  8153. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  8154. except Exception as e:
  8155. logger.warning("[ENERGY-BG] Failed: %s", e)
  8156. async def _background_finish_photo() -> str | None:
  8157. """Capture finish photo in background. Returns photo filename if captured."""
  8158. # #2547: set once this function has raised the plate itself (the
  8159. # timelapse path, where the moment producer returned without doing it).
  8160. # Declared out here so the `finally` can lower it again no matter where
  8161. # the capture below fails.
  8162. plate_restored_z: float | None = None
  8163. try:
  8164. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  8165. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  8166. # Read phase: settings + printer + archive in a short session, released
  8167. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  8168. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  8169. # tens of seconds; holding this session across it pinned one pooled
  8170. # connection idle-in-transaction per finishing print (issue #2572).
  8171. async with async_session() as db:
  8172. from backend.app.api.routes.settings import get_setting
  8173. from backend.app.models.archive import PrintArchive
  8174. from backend.app.models.printer import Printer
  8175. capture_enabled = await get_setting(db, "capture_finish_photo")
  8176. if capture_enabled is not None and capture_enabled.lower() != "true":
  8177. return None
  8178. if not archive_id:
  8179. return None
  8180. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  8181. archive = (
  8182. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8183. ).scalar_one_or_none()
  8184. if not printer or not archive:
  8185. return None
  8186. import uuid
  8187. from datetime import datetime
  8188. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  8189. if not archive.file_path:
  8190. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  8191. archive_dir = resolve_archive_dir(archive)
  8192. photo_filename = None
  8193. # Prefer the timelapse last-frame source when a timelapse was
  8194. # recording — it captures the moment after the toolhead parks
  8195. # but before the bed drops, which the live-camera grab below
  8196. # would miss (#1397). Skipped for external cameras (those have
  8197. # their own framing and don't see a Bambu timelapse). Only
  8198. # runs when the USER explicitly enabled timelapse for this
  8199. # print — #1721 removed Bambuddy's force-on at dispatch
  8200. # because it caused per-layer nozzle parking on Smooth-mode
  8201. # slicer profiles.
  8202. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  8203. printer.external_camera_enabled and printer.external_camera_url
  8204. )
  8205. timelapse_still_pending = False
  8206. if prefer_timelapse_source:
  8207. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  8208. archive_id=archive_id,
  8209. archive_dir=archive_dir,
  8210. rotation=getattr(printer, "camera_rotation", 0),
  8211. )
  8212. # #1721: replacement framing path — on_finish_photo_moment
  8213. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  8214. # parked, bed not yet dropped) and cached the JPEG bytes in
  8215. # _stage22_finish_frames. Consume them now so the saved photo
  8216. # has the better framing instead of the post-bed-drop angle
  8217. # the live-camera fallback below would give.
  8218. if not photo_filename:
  8219. # #1790: on the FINISH-state fallback path the producer
  8220. # task is dispatched back-to-back with this consumer, so
  8221. # a bare pop would race past with an empty result and
  8222. # the RTSP fallback below would collide with the
  8223. # producer's still-in-flight grab (single-client RTSP
  8224. # on Bambu printers). Wait for the producer to finish
  8225. # or give up before touching the cache.
  8226. #
  8227. # #2547: 20s was enough when the producer only ever grabbed a
  8228. # frame. It now also raises the plate first, which costs the
  8229. # settle window before the grab even starts — so the budget has
  8230. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  8231. # under the notification's own photo wait below.
  8232. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  8233. if in_flight is not None:
  8234. try:
  8235. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  8236. except TimeoutError:
  8237. logger.warning(
  8238. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  8239. printer_id,
  8240. )
  8241. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  8242. if cached_frame:
  8243. # Already rotated by the producer (#2708) — rotating again
  8244. # here would undo the fix on the banked-frame path, whose
  8245. # bytes reach the cache having been rotated once already.
  8246. photos_dir = archive_dir / "photos"
  8247. photos_dir.mkdir(parents=True, exist_ok=True)
  8248. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8249. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8250. photo_path = photos_dir / photo_filename
  8251. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  8252. logger.info(
  8253. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  8254. photo_filename,
  8255. len(cached_frame),
  8256. )
  8257. # #2547: the timelapse path reaches the live grab below whenever the
  8258. # video hasn't landed in time — the documented usual outcome on
  8259. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  8260. # returned early for those prints without raising the plate, so
  8261. # without this the photo that actually ships in the notification is
  8262. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  8263. # asked us to fix. The archive still gets the better video frame
  8264. # later; this is about the image the user is sent.
  8265. #
  8266. # Gated on `timelapse_was_active` precisely because that is the
  8267. # condition under which the producer skipped. On every other path it
  8268. # has already raised and lowered the plate, and repeating that here
  8269. # would be a second pointless round trip.
  8270. if (
  8271. not photo_filename
  8272. and data.get("timelapse_was_active")
  8273. and not print_dispatch_context.end_gcode_injected(printer_id)
  8274. ):
  8275. try:
  8276. async with async_session() as db:
  8277. from backend.app.api.routes.settings import get_setting
  8278. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  8279. if restore_setting is None or restore_setting.lower() == "true":
  8280. max_z = await _max_z_for_current_print(
  8281. printer_id, data, logger, bound_archive_id, notify_plate_id
  8282. )
  8283. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  8284. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  8285. plate_restored_z = max_z
  8286. except Exception as e:
  8287. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  8288. # Fallback chain: external camera → buffered live frame →
  8289. # fresh RTSP capture. Only runs if the timelapse path above
  8290. # didn't already produce a photo.
  8291. # Chamber light for the live capture below (#1655).
  8292. async with camera_light(printer if not photo_filename else None):
  8293. if not photo_filename:
  8294. if printer.external_camera_enabled and printer.external_camera_url:
  8295. logger.info("[PHOTO-BG] Using external camera")
  8296. from backend.app.api.routes.camera import live_frame_for_capture
  8297. from backend.app.services.external_camera import capture_frame
  8298. # #2707: the second half of the finish-photo failure — the
  8299. # pre-capture and this fallback both collided with the live
  8300. # view. None here continues down the fallback chain.
  8301. defer, buffered = live_frame_for_capture(printer_id)
  8302. if defer:
  8303. frame_data = buffered
  8304. else:
  8305. frame_data = await capture_frame(
  8306. printer.external_camera_url,
  8307. printer.external_camera_type or "mjpeg",
  8308. snapshot_url=printer.external_camera_snapshot_url,
  8309. )
  8310. if frame_data:
  8311. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  8312. photos_dir = archive_dir / "photos"
  8313. photos_dir.mkdir(parents=True, exist_ok=True)
  8314. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8315. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8316. photo_path = photos_dir / photo_filename
  8317. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  8318. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  8319. else:
  8320. # Check if camera stream is active - use buffered frame to avoid freeze
  8321. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  8322. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  8323. active_chamber_for_printer = [
  8324. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  8325. ]
  8326. buffered_frame = get_buffered_frame(printer_id)
  8327. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  8328. # Use frame from active stream
  8329. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  8330. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  8331. photos_dir = archive_dir / "photos"
  8332. photos_dir.mkdir(parents=True, exist_ok=True)
  8333. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  8334. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  8335. photo_path = photos_dir / photo_filename
  8336. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  8337. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  8338. else:
  8339. # No active stream - capture new frame
  8340. from backend.app.services.camera import capture_finish_photo
  8341. photo_filename = await capture_finish_photo(
  8342. printer_id=printer_id,
  8343. ip_address=printer.ip_address,
  8344. access_code=printer.access_code,
  8345. model=printer.model,
  8346. archive_dir=archive_dir,
  8347. rotation=getattr(printer, "camera_rotation", 0),
  8348. )
  8349. # Write phase: attach the photo in a fresh short-lived session.
  8350. if photo_filename:
  8351. async with async_session() as db:
  8352. from backend.app.models.archive import PrintArchive
  8353. arch = await db.get(PrintArchive, archive_id)
  8354. if arch is not None:
  8355. photos = arch.photos or []
  8356. photos.append(photo_filename)
  8357. arch.photos = photos
  8358. await db.commit()
  8359. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  8360. # The short wait above is bounded so a slow printer can't hold up
  8361. # the print-complete notification, which is what the caller is
  8362. # blocking on. When it ran out with the video still on its way,
  8363. # keep waiting off to the side and add the better frame to the
  8364. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  8365. # users, whose videos routinely take minutes to transfer, never get
  8366. # the pre-bed-drop framing this path exists to provide.
  8367. #
  8368. # Spawned here rather than at the point the wait gave up: both this
  8369. # function and the upgrade do a read-modify-write on `photos`, and
  8370. # the live-camera fallback above can take tens of seconds. Starting
  8371. # the upgrade before that write means the two can interleave and one
  8372. # silently drops the other's entry, leaving a JPEG on disk that the
  8373. # gallery never lists.
  8374. if timelapse_still_pending:
  8375. spawn_background_task(
  8376. _upgrade_finish_photo_from_timelapse(
  8377. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  8378. ),
  8379. name=f"finish-photo-upgrade-{archive_id}",
  8380. )
  8381. return photo_filename
  8382. except Exception as e:
  8383. logger.warning("[PHOTO-BG] Failed: %s", e)
  8384. return None
  8385. finally:
  8386. # #2547: we raised the plate, so we owe the move back down — even if
  8387. # the capture in between threw. Otherwise the user finds the print
  8388. # pinned under the nozzle.
  8389. if plate_restored_z is not None:
  8390. try:
  8391. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  8392. except Exception as e:
  8393. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  8394. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  8395. # Photo capture task - result will be used by notifications
  8396. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  8397. log_timing("Background tasks scheduled (energy, photo)")
  8398. # Also run smart plug, notifications, and maintenance as background tasks
  8399. print_status = data.get("status", "completed")
  8400. async def _background_smart_plug():
  8401. """Handle smart plug automation in background."""
  8402. try:
  8403. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  8404. async with async_session() as db:
  8405. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  8406. logger.info("[AUTO-OFF-BG] Completed")
  8407. except Exception as e:
  8408. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  8409. async def _background_notifications(finish_photo_filename: str | None = None):
  8410. """Send print complete notifications in background."""
  8411. try:
  8412. logger.info(
  8413. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  8414. )
  8415. async with async_session() as db:
  8416. from backend.app.models.archive import PrintArchive
  8417. from backend.app.models.printer import Printer
  8418. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8419. printer = result.scalar_one_or_none()
  8420. printer_name = printer.name if printer else f"Printer {printer_id}"
  8421. archive_data = None
  8422. if archive_id:
  8423. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  8424. archive = archive_result.scalar_one_or_none()
  8425. if archive:
  8426. # Actual elapsed time from started_at/completed_at when both are
  8427. # populated (every terminal status sets completed_at after #1198).
  8428. # Falls back to None so the notification path can decide whether to
  8429. # render the slicer estimate as a last resort.
  8430. actual_time_seconds = None
  8431. # Unknown for a completion reconciled at reconnect: the
  8432. # print ended while the printer was offline and
  8433. # completed_at is the reconnect, so the gap would read
  8434. # as the duration -- 14 h for a night offline (DB-C9).
  8435. if archive.started_at and archive.completed_at and not data.get("_reconciled"):
  8436. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  8437. if elapsed > 0:
  8438. actual_time_seconds = int(elapsed)
  8439. archive_data = {
  8440. "print_time_seconds": archive.print_time_seconds,
  8441. "actual_time_seconds": actual_time_seconds,
  8442. "actual_filament_grams": archive.filament_used_grams,
  8443. "failure_reason": archive.failure_reason,
  8444. "created_by_id": archive.created_by_id,
  8445. }
  8446. # Scale filament usage for partial prints
  8447. if print_status != "completed" and archive.filament_used_grams:
  8448. progress = data.get("progress") or 0
  8449. scale = _partial_progress_scale(progress)
  8450. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  8451. archive_data["progress"] = progress
  8452. # Pass per-slot data from archive.extra_data
  8453. if archive.extra_data and archive.extra_data.get("filament_slots"):
  8454. slots = archive.extra_data["filament_slots"]
  8455. if print_status != "completed":
  8456. scale = _partial_progress_scale(data.get("progress"))
  8457. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  8458. archive_data["filament_slots"] = slots
  8459. # Scope project-summed totals down to the plate that was
  8460. # actually printed — see _scope_notification_archive_data_to_plate
  8461. # for the why (#1785).
  8462. archive_data = _scope_notification_archive_data_to_plate(
  8463. archive_data,
  8464. archive.file_path,
  8465. notify_plate_id,
  8466. print_status,
  8467. data.get("progress"),
  8468. app_settings.base_dir,
  8469. )
  8470. # Enrich filament_grams from usage_results when archive has no 3MF data
  8471. if not archive_data.get("actual_filament_grams") and usage_results:
  8472. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8473. if total_from_usage > 0:
  8474. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8475. # Pass usage tracker results for AMS slot info in notifications
  8476. if usage_results:
  8477. archive_data["usage_results"] = usage_results
  8478. # Add finish photo URL and image bytes if available
  8479. if finish_photo_filename:
  8480. photo_url, photo_bytes = await _finish_photo_for_notification(
  8481. db, archive, archive_id, finish_photo_filename
  8482. )
  8483. if photo_url:
  8484. archive_data["finish_photo_url"] = photo_url
  8485. if photo_bytes:
  8486. archive_data["image_data"] = photo_bytes
  8487. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8488. await notification_service.on_print_complete(
  8489. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  8490. )
  8491. else:
  8492. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8493. # Post-print outcome confirmation (#1898). Runs in this
  8494. # background task so the finish photo fetched above rides
  8495. # along with the prompt.
  8496. if print_status == "completed" and archive_id:
  8497. await _dispatch_outcome_confirmation_safely(
  8498. db, printer_id, printer_name, data, archive_id, archive_data
  8499. )
  8500. # Send user-specific email notification
  8501. if archive_data:
  8502. created_by_id = archive_data.get("created_by_id")
  8503. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8504. await _dispatch_user_print_email(
  8505. print_status,
  8506. created_by_id,
  8507. printer_name,
  8508. raw_filename,
  8509. db,
  8510. image_data=archive_data.get("image_data"),
  8511. finish_photo_url=archive_data.get("finish_photo_url"),
  8512. )
  8513. logger.info("[NOTIFY-BG] Completed")
  8514. except Exception as e:
  8515. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  8516. async def _background_maintenance_check():
  8517. """Check for maintenance due in background."""
  8518. if print_status != "completed":
  8519. return
  8520. try:
  8521. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  8522. async with async_session() as db:
  8523. from backend.app.models.printer import Printer
  8524. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8525. printer = result.scalar_one_or_none()
  8526. printer_name = printer.name if printer else f"Printer {printer_id}"
  8527. await ensure_default_types(db)
  8528. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  8529. attention = [
  8530. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  8531. ]
  8532. items_needing_attention = [
  8533. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  8534. for item in attention
  8535. ]
  8536. if items_needing_attention:
  8537. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  8538. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  8539. # MQTT relay - publish maintenance alerts
  8540. for item in attention:
  8541. current_value, threshold, unit = maintenance_alert_values(item)
  8542. try:
  8543. await mqtt_relay.on_maintenance_alert(
  8544. printer_id=printer_id,
  8545. printer_name=printer_name,
  8546. maintenance_type=item.maintenance_type_name,
  8547. current_value=current_value,
  8548. threshold=threshold,
  8549. unit=unit,
  8550. )
  8551. except Exception:
  8552. pass # Don't fail if MQTT fails
  8553. else:
  8554. logger.info("[MAINT-BG] Completed (no items need attention)")
  8555. except Exception as e:
  8556. logger.warning("[MAINT-BG] Failed: %s", e)
  8557. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  8558. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  8559. # Notification task waits for photo capture to complete first (with timeout).
  8560. # When a timelapse was recording, photo sourcing polls the per-print
  8561. # timelapse for up to 60s (#1397) — extend the budget so the notification
  8562. # carries the correct bed-up photo instead of falling through to the
  8563. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  8564. #
  8565. # #2547: both budgets now have to cover a plate restore as well.
  8566. #
  8567. # Without timelapse, the wait is on the moment producer, which raises the
  8568. # plate before its grab — so this has to outlast that producer's own budget.
  8569. #
  8570. # With timelapse, the capture polls up to
  8571. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  8572. # falls back to a live grab, which is the case that raises the plate. At the
  8573. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  8574. # restore would have moved the plate for a photo nobody waited for.
  8575. photo_wait_timeout = (
  8576. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  8577. if data.get("timelapse_was_active")
  8578. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  8579. )
  8580. async def _photo_then_notify():
  8581. """Wait for photo capture, then send notification with photo URL."""
  8582. finish_photo = None
  8583. try:
  8584. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  8585. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  8586. except TimeoutError:
  8587. logger.warning(
  8588. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  8589. photo_wait_timeout,
  8590. )
  8591. except Exception as e:
  8592. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  8593. try:
  8594. await _background_notifications(finish_photo)
  8595. except Exception as e:
  8596. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  8597. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  8598. # Stitch external camera layer timelapse if session was active
  8599. print_status = data.get("status", "completed")
  8600. async def _background_layer_timelapse():
  8601. """Stitch layer timelapse and attach to archive."""
  8602. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  8603. try:
  8604. if print_status == "completed":
  8605. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  8606. # The run the frames belong to, read before the stitch: it can
  8607. # take long enough for the archive to start printing again.
  8608. run_started_at = None
  8609. if archive_id:
  8610. async with async_session() as db:
  8611. run_archive = await ArchiveService(db).get_archive(archive_id)
  8612. run_started_at = run_archive.started_at if run_archive else None
  8613. timelapse_path = await tl_complete(printer_id)
  8614. if timelapse_path and archive_id:
  8615. await _attach_layer_timelapse(archive_id, timelapse_path, notify_plate_id, run_started_at)
  8616. elif timelapse_path:
  8617. # Timelapse created but no archive - just clean up
  8618. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  8619. else:
  8620. # Print failed or cancelled - cancel timelapse session
  8621. cancel_session(printer_id)
  8622. logger.info(
  8623. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  8624. )
  8625. except Exception as e:
  8626. logger.warning("[LAYER-TL] Failed: %s", e)
  8627. # A completed print's session left _active_sessions when its stitch
  8628. # began: the one there now belongs to the next print, which may have
  8629. # started during the stitch, and must not lose its frames.
  8630. if print_status != "completed":
  8631. try:
  8632. cancel_session(printer_id)
  8633. except Exception:
  8634. pass # Best-effort timelapse session cancellation on error
  8635. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  8636. log_timing("All background tasks scheduled")
  8637. # Auto-scan for timelapse if recording was active during the print
  8638. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  8639. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  8640. # Schedule timelapse scan as background task with retries
  8641. # The printer needs time to encode the video after print completion
  8642. baseline = _timelapse_baselines.pop(printer_id, None)
  8643. spawn_background_task(
  8644. _scan_for_timelapse_with_retries(archive_id, baseline, plate_id=notify_plate_id),
  8645. name=f"scan-timelapse-{archive_id}",
  8646. )
  8647. log_timing("Timelapse scan scheduled")
  8648. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  8649. # AMS sensor history recording
  8650. _ams_history_task: asyncio.Task | None = None
  8651. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  8652. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  8653. def _retention_days(stored: str | None, default: int) -> int:
  8654. """A history retention setting as days to keep: at least 1, the default
  8655. when unset or unreadable. A stored 0 or less (the API took one before it
  8656. had a minimum) would put the cutoff at now and delete all history."""
  8657. try:
  8658. return max(1, int(stored)) if stored is not None else default
  8659. except (TypeError, ValueError):
  8660. return default
  8661. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  8662. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  8663. _ams_alarm_cooldown: dict[str, datetime] = {}
  8664. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  8665. # (printer_id, ams_id) already reported as sending the drop index and no
  8666. # percentage. Logged once each so a supported printer that turns out to do this
  8667. # shows up in a support bundle rather than as a user wondering where the
  8668. # humidity reading went -- see the note at the read site below (#3140).
  8669. _ams_index_only_logged: set[tuple[int, int]] = set()
  8670. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  8671. """Temperature at which the AMS alarm fires, falling back to the display band.
  8672. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  8673. when a notification was sent as well, which is why a room above it made the
  8674. alarm fire once an hour for as long as the weather lasted -- and the only way
  8675. to stop that was to raise the display band and lose the colour that says the
  8676. unit is warm (#2905).
  8677. Unset resolves to the fair threshold, so an install that never sets one is
  8678. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  8679. so that arrives here as a string and is handled by the same branch as any
  8680. other unparseable value -- there is no separate sentinel to keep in sync.
  8681. A non-positive value is refused rather than honoured: zero would alarm
  8682. permanently, and it is far more likely to be a cleared field than a
  8683. deliberate choice.
  8684. """
  8685. if raw_alarm_value is None:
  8686. return fair_threshold
  8687. try:
  8688. value = float(raw_alarm_value)
  8689. except (TypeError, ValueError):
  8690. return fair_threshold
  8691. if not math.isfinite(value) or value <= 0:
  8692. return fair_threshold
  8693. return value
  8694. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  8695. # through a cycle and the cool-down after it (#1802). Stored in the settings
  8696. # table rather than alongside _ams_alarm_cooldown above, because a restart
  8697. # partway through a cool-down would otherwise resume alarming about heat the
  8698. # user asked for — the same internal-timestamp-row pattern as
  8699. # support.py's debug_logging_enabled_at.
  8700. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  8701. # Upper bound on that suppression. The latch normally clears as soon as the unit
  8702. # reads at or below the threshold; see utils.ams_drying for why this cap only
  8703. # matters when it never does.
  8704. AMS_DRYING_GRACE_MINUTES = 120
  8705. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  8706. """Read the persisted per-AMS drying latch, dropping entries out of window.
  8707. Anything older than the grace cap would expire on its next visit anyway, so
  8708. discarding it here costs nothing and stops rows for deleted printers from
  8709. accumulating.
  8710. Stamps ahead of now get two defences, because a box whose clock jumps
  8711. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  8712. ones are discarded outright, and the rest are clamped to now. Without the
  8713. clamp the cap would measure from a moment that has not happened yet and hold
  8714. the alarm quiet for the skew on top of the cap. One unnecessary notification
  8715. after a clock jump is a far better failure than an alarm silently disabled
  8716. for hours.
  8717. """
  8718. from backend.app.models.settings import Settings
  8719. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8720. setting = result.scalar_one_or_none()
  8721. if not setting or not setting.value:
  8722. return {}
  8723. try:
  8724. raw = json.loads(setting.value)
  8725. except (ValueError, TypeError):
  8726. return {} # Corrupted row → no latch, alarms behave as they did before
  8727. if not isinstance(raw, dict):
  8728. return {}
  8729. now = datetime.now(timezone.utc)
  8730. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  8731. latch: dict[str, datetime] = {}
  8732. for key, value in raw.items():
  8733. try:
  8734. stamp = datetime.fromisoformat(str(value))
  8735. except (ValueError, TypeError):
  8736. continue
  8737. if stamp.tzinfo is None:
  8738. stamp = stamp.replace(tzinfo=timezone.utc)
  8739. if not (now - window <= stamp <= now + window):
  8740. continue
  8741. # Nothing may sit in the future: suppression is measured as now minus
  8742. # the stamp, so a stamp ahead of now would extend it by the skew on top
  8743. # of the cap. Clamping the survivors keeps the cap an actual cap.
  8744. latch[str(key)] = min(stamp, now)
  8745. return latch
  8746. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  8747. """Persist the latch, writing only when it actually changed.
  8748. Adds the session change but does not commit — the caller's own commit
  8749. carries it, so the latch lands in the same transaction as the sensor rows
  8750. that produced it.
  8751. """
  8752. from backend.app.models.settings import Settings
  8753. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  8754. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8755. setting = result.scalar_one_or_none()
  8756. if setting is None:
  8757. # Don't create the row on installs that never dry anything.
  8758. if payload != "{}":
  8759. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  8760. elif setting.value != payload:
  8761. setting.value = payload
  8762. def _ams_has_filament(ams_data: dict) -> bool:
  8763. """True if this AMS unit has at least one tray slot holding filament.
  8764. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  8765. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  8766. still report sensor readings, but those readings are ambient and not
  8767. actionable: no filament to dry, no humidity to push down. #1619 — gate
  8768. humidity/temperature alarms on this check so empty units don't generate
  8769. hourly noise. Sensor history still records regardless so the UI charts
  8770. stay continuous.
  8771. Fallback path inspects the `tray` array's `tray_type` fields for setups
  8772. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  8773. """
  8774. bits = ams_data.get("tray_exist_bits")
  8775. if isinstance(bits, str) and bits.strip():
  8776. try:
  8777. return int(bits, 16) > 0
  8778. except ValueError:
  8779. pass
  8780. trays = ams_data.get("tray")
  8781. if isinstance(trays, list):
  8782. return any(
  8783. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  8784. )
  8785. return False
  8786. async def record_ams_history():
  8787. """Background task to record AMS humidity and temperature data."""
  8788. logger = logging.getLogger(__name__)
  8789. # Wait a short time for MQTT connections to establish on startup
  8790. await asyncio.sleep(10)
  8791. while True:
  8792. try:
  8793. from backend.app.models.ams_history import AMSSensorHistory
  8794. from backend.app.models.printer import Printer
  8795. from backend.app.models.settings import Settings
  8796. async with async_session() as db:
  8797. # Get all active printers
  8798. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8799. printers = result.scalars().all()
  8800. # Get alarm thresholds from settings
  8801. humidity_threshold = 60.0 # Default: fair threshold
  8802. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  8803. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  8804. setting = result.scalar_one_or_none()
  8805. if setting:
  8806. try:
  8807. humidity_threshold = float(setting.value)
  8808. except (ValueError, TypeError):
  8809. pass # Keep default threshold if stored value is invalid
  8810. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  8811. setting = result.scalar_one_or_none()
  8812. if setting:
  8813. try:
  8814. temp_fair_threshold = float(setting.value)
  8815. except (ValueError, TypeError):
  8816. pass # Keep default threshold if stored value is invalid
  8817. # The alarm gets its own threshold, seeded from the resolved fair
  8818. # value so an install that has never set one behaves exactly as
  8819. # it did before (#2905). ams_temp_fair decides when the card turns
  8820. # amber; 35 C is a reasonable place to change a colour and not a
  8821. # reasonable place to page someone. A room above it makes the
  8822. # alarm fire once an hour for as long as the weather lasts, and
  8823. # the only way to stop it was to raise the display band and lose
  8824. # the colour that says the unit is warm.
  8825. #
  8826. # An unset value is stored as the literal "None", which the except
  8827. # below swallows the same way it swallows garbage -- so the
  8828. # fallback costs nothing and needs no sentinel of its own.
  8829. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  8830. setting = result.scalar_one_or_none()
  8831. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  8832. temp_fair_threshold, setting.value if setting else None
  8833. )
  8834. # Per-filament humidity threshold overrides (#1605) — resolved
  8835. # per-AMS below from the loaded tray types. Reuses the same
  8836. # resolver as the auto-drying scheduler so behavior stays in
  8837. # lockstep across both consumers.
  8838. from backend.app.services.print_scheduler import PrintScheduler
  8839. per_type_humidity_thresholds: dict[str, int] = {}
  8840. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  8841. setting = result.scalar_one_or_none()
  8842. if setting and setting.value:
  8843. try:
  8844. raw = json.loads(setting.value)
  8845. if isinstance(raw, dict):
  8846. for k, v in raw.items():
  8847. try:
  8848. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  8849. v
  8850. )
  8851. except (TypeError, ValueError):
  8852. continue
  8853. except (ValueError, TypeError):
  8854. pass # Invalid JSON → no overrides, fall through to global threshold
  8855. # Per-AMS drying latch (#1802), loaded once per pass and written
  8856. # back below only if a unit changed it.
  8857. drying_latch = await _load_ams_drying_latch(db)
  8858. drying_latch_before = dict(drying_latch)
  8859. recorded_count = 0
  8860. for printer in printers:
  8861. # Get current state from printer manager
  8862. state = printer_manager.get_status(printer.id)
  8863. if not state or not state.connected or not state.raw_data:
  8864. continue # Skip disconnected printers - don't use stale data
  8865. raw_data = state.raw_data
  8866. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  8867. continue
  8868. # Record data for each AMS unit
  8869. for ams_data in raw_data["ams"]:
  8870. ams_id = int(ams_data.get("id", 0))
  8871. # Percentage only. The 1-5 index is inverted, so
  8872. # charting it as a percentage drew the wettest units as
  8873. # the driest (#3140); a unit that reports no percentage
  8874. # leaves a gap in the chart instead. See
  8875. # utils/ams_humidity.
  8876. humidity = ams_humidity_percent(ams_data)
  8877. # No supported printer is known to send the index
  8878. # alone -- the report came from unsupported firmware,
  8879. # and no install has been seen using the old fallback.
  8880. # "Known" is doing work there, so say so once per unit:
  8881. # the alternative is a silent blank card.
  8882. if humidity is None and ams_data.get("humidity") is not None:
  8883. unit_key = (printer.id, ams_id)
  8884. if unit_key not in _ams_index_only_logged:
  8885. _ams_index_only_logged.add(unit_key)
  8886. logger.info(
  8887. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  8888. "percentage. The index is inverted and is not shown as a percentage "
  8889. "(#3140), so this unit has no humidity reading, chart or alarm. "
  8890. "Please report this with the printer and AMS firmware versions.",
  8891. printer.name,
  8892. ams_id,
  8893. )
  8894. # Get temperature
  8895. temperature = None
  8896. temp_str = ams_data.get("temp")
  8897. if temp_str is not None:
  8898. try:
  8899. temperature = float(temp_str)
  8900. except (ValueError, TypeError):
  8901. pass # Skip unparseable temperature value
  8902. # Skip if no data
  8903. if humidity is None and temperature is None:
  8904. continue
  8905. # Record the data point
  8906. history = AMSSensorHistory(
  8907. printer_id=printer.id,
  8908. ams_id=ams_id,
  8909. humidity=humidity,
  8910. # Both columns hold the same reading now that the
  8911. # index can no longer reach ``humidity``. Writing it
  8912. # through the same value also stops a genuine 0%
  8913. # from being stored as NULL, which the old truthiness
  8914. # test did.
  8915. humidity_raw=humidity,
  8916. temperature=temperature,
  8917. )
  8918. db.add(history)
  8919. recorded_count += 1
  8920. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  8921. is_ams_ht = ams_id >= 128
  8922. if is_ams_ht:
  8923. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  8924. else:
  8925. ams_label = f"AMS-{chr(65 + ams_id)}"
  8926. # Skip alarm dispatch for empty AMS units — humidity /
  8927. # temperature readings are ambient with no filament to
  8928. # protect, and the hourly notification just becomes
  8929. # noise. Sensor history was already recorded above so
  8930. # the UI charts stay continuous (#1619). Per-AMS check
  8931. # so a multi-AMS setup with one loaded + one empty
  8932. # still alarms on the loaded unit.
  8933. if not _ams_has_filament(ams_data):
  8934. continue
  8935. # Resolve per-filament humidity threshold for this AMS
  8936. # unit (#1605). Falls back to the global ams_humidity_fair
  8937. # when no per-type overrides are configured.
  8938. trays = ams_data.get("tray", []) or []
  8939. effective_humidity_threshold = float(
  8940. PrintScheduler.resolve_humidity_threshold(
  8941. trays, per_type_humidity_thresholds, int(humidity_threshold)
  8942. )
  8943. )
  8944. # Check humidity alarm (only if above threshold)
  8945. if humidity is not None and humidity > effective_humidity_threshold:
  8946. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  8947. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8948. now = datetime.now(timezone.utc)
  8949. if (
  8950. last_alarm is None
  8951. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8952. ):
  8953. _ams_alarm_cooldown[cooldown_key] = now
  8954. logger.info(
  8955. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  8956. )
  8957. try:
  8958. # Call different notification method based on AMS type
  8959. if is_ams_ht:
  8960. await notification_service.on_ams_ht_humidity_high(
  8961. printer.id,
  8962. printer.name,
  8963. ams_label,
  8964. humidity,
  8965. effective_humidity_threshold,
  8966. db,
  8967. )
  8968. else:
  8969. await notification_service.on_ams_humidity_high(
  8970. printer.id,
  8971. printer.name,
  8972. ams_label,
  8973. humidity,
  8974. effective_humidity_threshold,
  8975. db,
  8976. )
  8977. except Exception as e:
  8978. logger.warning("Failed to send humidity alarm: %s", e)
  8979. # A drying cycle heats the unit far past ams_temp_fair on
  8980. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  8981. # AMS-HT, against a 35 C default — so the alarm fired
  8982. # once an hour for the whole cycle and kept firing while
  8983. # the unit cooled back down (#1802). Latch on the
  8984. # firmware's own drying state and hold until the reading
  8985. # returns to normal. Humidity is deliberately left alone:
  8986. # it falls during drying, which is the whole point.
  8987. latch_key = f"{printer.id}:{ams_id}"
  8988. # The latch releases at `threshold`, so it takes the alarm
  8989. # number too. Handing it the display band would strand the
  8990. # latch on any unit that settles back above it -- a room
  8991. # where the AMS rests at 37.7 C never returns under a 35 C
  8992. # band, so the latch could only expire on the grace cap
  8993. # rather than releasing when the unit had actually cooled.
  8994. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  8995. drying_active=is_drying_active(ams_data),
  8996. temperature=temperature,
  8997. threshold=temp_alarm_threshold,
  8998. latched_at=drying_latch.get(latch_key),
  8999. now=datetime.now(timezone.utc),
  9000. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  9001. )
  9002. if new_latch is None:
  9003. drying_latch.pop(latch_key, None)
  9004. else:
  9005. drying_latch[latch_key] = new_latch
  9006. # Check temperature alarm (only if above threshold)
  9007. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  9008. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  9009. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  9010. now = datetime.now(timezone.utc)
  9011. if (
  9012. last_alarm is None
  9013. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  9014. ):
  9015. _ams_alarm_cooldown[cooldown_key] = now
  9016. logger.info(
  9017. f"Sending temperature alarm for {printer.name} {ams_label}: "
  9018. f"{temperature}°C > {temp_alarm_threshold}°C"
  9019. )
  9020. try:
  9021. # Call different notification method based on AMS type
  9022. if is_ams_ht:
  9023. # The reported threshold has to be the one
  9024. # that fired, or the message says "> 35 °C"
  9025. # while firing at 45.
  9026. await notification_service.on_ams_ht_temperature_high(
  9027. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9028. )
  9029. else:
  9030. await notification_service.on_ams_temperature_high(
  9031. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  9032. )
  9033. except Exception as e:
  9034. logger.warning("Failed to send temperature alarm: %s", e)
  9035. if drying_latch != drying_latch_before:
  9036. await _save_ams_drying_latch(db, drying_latch)
  9037. await db.commit()
  9038. if recorded_count > 0:
  9039. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  9040. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  9041. global _ams_cleanup_counter
  9042. _ams_cleanup_counter += 1
  9043. if _ams_cleanup_counter >= 288:
  9044. _ams_cleanup_counter = 0
  9045. # Get retention days from settings
  9046. from backend.app.models.settings import Settings
  9047. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  9048. setting = result.scalar_one_or_none()
  9049. retention_days = _retention_days(setting.value if setting else None, AMS_HISTORY_RETENTION_DAYS)
  9050. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9051. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  9052. await db.commit()
  9053. if result.rowcount > 0:
  9054. logger.info(
  9055. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  9056. )
  9057. # Wait until next recording interval
  9058. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  9059. except asyncio.CancelledError:
  9060. break
  9061. except Exception as e:
  9062. logger.warning("AMS history recording failed: %s", e)
  9063. await asyncio.sleep(60) # Wait a bit before retrying
  9064. def start_ams_history_recording():
  9065. """Start the AMS history recording background task."""
  9066. global _ams_history_task
  9067. if _ams_history_task is None:
  9068. _ams_history_task = asyncio.create_task(record_ams_history())
  9069. logging.getLogger(__name__).info("AMS history recording started")
  9070. def stop_ams_history_recording():
  9071. """Stop the AMS history recording background task."""
  9072. global _ams_history_task
  9073. if _ams_history_task:
  9074. _ams_history_task.cancel()
  9075. _ams_history_task = None
  9076. logging.getLogger(__name__).info("AMS history recording stopped")
  9077. # Printer sensor history recording (nozzle / bed / chamber)
  9078. _printer_sensor_history_task: asyncio.Task | None = None
  9079. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  9080. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  9081. _printer_sensor_cleanup_counter = 0
  9082. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  9083. # MQTT parser writes, so we don't need to handle per-model field aliases here
  9084. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  9085. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  9086. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  9087. _SENSOR_TARGET_KEYS = {
  9088. "nozzle": "nozzle_target",
  9089. "nozzle_2": "nozzle_2_target",
  9090. "bed": "bed_target",
  9091. "chamber": "chamber_target",
  9092. }
  9093. async def record_printer_sensor_history():
  9094. """Background task to record nozzle / bed / chamber readings.
  9095. Pulls from `state.temperatures` (already normalised across all printer
  9096. models by the MQTT parser) rather than re-parsing raw_data, so we get
  9097. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  9098. """
  9099. logger = logging.getLogger(__name__)
  9100. await asyncio.sleep(10)
  9101. while True:
  9102. try:
  9103. from backend.app.models.printer import Printer
  9104. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  9105. from backend.app.models.settings import Settings
  9106. async with async_session() as db:
  9107. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  9108. printers = result.scalars().all()
  9109. recorded_count = 0
  9110. for printer in printers:
  9111. state = printer_manager.get_status(printer.id)
  9112. if not state or not state.connected:
  9113. continue
  9114. temps = getattr(state, "temperatures", None) or {}
  9115. if not isinstance(temps, dict):
  9116. continue
  9117. for kind in _SENSOR_KINDS:
  9118. if kind not in temps:
  9119. continue
  9120. try:
  9121. value = float(temps[kind])
  9122. except (ValueError, TypeError):
  9123. continue
  9124. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  9125. target_val: float | None = None
  9126. if target_raw is not None:
  9127. try:
  9128. target_val = float(target_raw)
  9129. except (ValueError, TypeError):
  9130. target_val = None
  9131. db.add(
  9132. PrinterSensorHistory(
  9133. printer_id=printer.id,
  9134. sensor_kind=kind,
  9135. value=value,
  9136. target=target_val,
  9137. )
  9138. )
  9139. recorded_count += 1
  9140. await db.commit()
  9141. if recorded_count > 0:
  9142. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  9143. # Periodic cleanup — once every ~24h at this interval.
  9144. global _printer_sensor_cleanup_counter
  9145. _printer_sensor_cleanup_counter += 1
  9146. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  9147. if _printer_sensor_cleanup_counter >= cleanup_every:
  9148. _printer_sensor_cleanup_counter = 0
  9149. result = await db.execute(
  9150. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  9151. )
  9152. setting = result.scalar_one_or_none()
  9153. retention_days = _retention_days(
  9154. setting.value if setting else None, PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  9155. )
  9156. cutoff = utcnow_naive() - timedelta(days=retention_days)
  9157. cleanup = await db.execute(
  9158. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  9159. )
  9160. await db.commit()
  9161. if cleanup.rowcount > 0:
  9162. logger.info(
  9163. "Cleaned up %s old printer sensor history entries (older than %s days)",
  9164. cleanup.rowcount,
  9165. retention_days,
  9166. )
  9167. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  9168. except asyncio.CancelledError:
  9169. break
  9170. except Exception as e:
  9171. logger.warning("Printer sensor history recording failed: %s", e)
  9172. await asyncio.sleep(60)
  9173. def start_printer_sensor_history_recording():
  9174. global _printer_sensor_history_task
  9175. if _printer_sensor_history_task is None:
  9176. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  9177. logging.getLogger(__name__).info("Printer sensor history recording started")
  9178. def stop_printer_sensor_history_recording():
  9179. global _printer_sensor_history_task
  9180. if _printer_sensor_history_task:
  9181. _printer_sensor_history_task.cancel()
  9182. _printer_sensor_history_task = None
  9183. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  9184. # Printer runtime tracking
  9185. _runtime_tracking_task: asyncio.Task | None = None
  9186. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  9187. # Printers the runtime tracker has seen connected since startup. One of them
  9188. # going offline clears its timestamp, so the time it was away is not counted
  9189. # when it comes back printing (DB-C5). A printer not yet seen -- still
  9190. # connecting after a restart -- keeps it for a grace period: a print that ran
  9191. # on through a Bambuddy restart is counted from the stored timestamp, as before.
  9192. _runtime_seen_connected: set[int] = set()
  9193. # A printer never seen connected this long after the tracker started is
  9194. # offline, not still connecting: its stored timestamp predates a gap too.
  9195. RUNTIME_STARTUP_GRACE_SECONDS = 120
  9196. async def track_printer_runtime():
  9197. """Background task to track printer active runtime (RUNNING state only).
  9198. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  9199. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  9200. which track mechanical wear. Pause time has no motion and no wear, so
  9201. counting it inflates maintenance warnings (#1521).
  9202. """
  9203. logger = logging.getLogger(__name__)
  9204. # Wait for MQTT connections to establish on startup
  9205. await asyncio.sleep(15)
  9206. started = time.monotonic()
  9207. while True:
  9208. try:
  9209. from backend.app.models.printer import Printer
  9210. # Fetch printer IDs in a short-lived read-only session
  9211. async with async_session() as db:
  9212. result = await db.execute(
  9213. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  9214. Printer.is_active.is_(True)
  9215. )
  9216. )
  9217. printer_rows = result.all()
  9218. now = datetime.now(timezone.utc)
  9219. updated_count = 0
  9220. # Update each printer in its own short session to minimise write-lock
  9221. # hold time and avoid blocking critical commits like queue status
  9222. # updates (#897).
  9223. for pid, pname, runtime_secs, last_update in printer_rows:
  9224. state = printer_manager.get_status(pid)
  9225. if not state:
  9226. logger.debug("[%s] Runtime tracking: no state available", pname)
  9227. continue
  9228. if not state.connected:
  9229. logger.debug("[%s] Runtime tracking: not connected", pname)
  9230. offline = pid in _runtime_seen_connected or (
  9231. time.monotonic() - started > RUNTIME_STARTUP_GRACE_SECONDS
  9232. )
  9233. if offline and last_update is not None:
  9234. try:
  9235. async with async_session() as db:
  9236. printer = await db.get(Printer, pid)
  9237. if printer:
  9238. printer.last_runtime_update = None
  9239. await db.commit()
  9240. except Exception as e:
  9241. # Still marked: the next offline tick tries again.
  9242. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  9243. continue
  9244. _runtime_seen_connected.discard(pid)
  9245. continue
  9246. _runtime_seen_connected.add(pid)
  9247. needs_commit = False
  9248. new_runtime = runtime_secs
  9249. new_last_update = last_update
  9250. if state.state == "RUNNING":
  9251. if last_update:
  9252. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  9253. elapsed = (now - lu).total_seconds()
  9254. if elapsed > 0:
  9255. new_runtime = runtime_secs + int(elapsed)
  9256. updated_count += 1
  9257. needs_commit = True
  9258. logger.debug(
  9259. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  9260. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  9261. )
  9262. else:
  9263. needs_commit = True
  9264. logger.debug("[%s] Runtime tracking: first active detection", pname)
  9265. new_last_update = now
  9266. else:
  9267. if last_update is not None:
  9268. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  9269. new_last_update = None
  9270. needs_commit = True
  9271. if needs_commit:
  9272. try:
  9273. async with async_session() as db:
  9274. result = await db.execute(select(Printer).where(Printer.id == pid))
  9275. printer = result.scalar_one_or_none()
  9276. if printer:
  9277. printer.runtime_seconds = new_runtime
  9278. printer.last_runtime_update = new_last_update
  9279. await db.commit()
  9280. except Exception as e:
  9281. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  9282. if updated_count > 0:
  9283. logger.debug("Updated runtime for %s printer(s)", updated_count)
  9284. except asyncio.CancelledError:
  9285. logger.info("Runtime tracking cancelled")
  9286. break
  9287. except Exception as e:
  9288. logger.warning("Runtime tracking failed: %s", e)
  9289. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  9290. def start_runtime_tracking():
  9291. """Start the printer runtime tracking background task."""
  9292. global _runtime_tracking_task
  9293. if _runtime_tracking_task is None:
  9294. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  9295. logging.getLogger(__name__).info("Printer runtime tracking started")
  9296. def stop_runtime_tracking():
  9297. """Stop the printer runtime tracking background task."""
  9298. global _runtime_tracking_task
  9299. if _runtime_tracking_task:
  9300. _runtime_tracking_task.cancel()
  9301. _runtime_tracking_task = None
  9302. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  9303. # SpoolBuddy device watchdog
  9304. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  9305. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  9306. async def _spoolbuddy_watchdog_loop():
  9307. """Periodic check for SpoolBuddy devices that have gone offline."""
  9308. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  9309. while True:
  9310. try:
  9311. await spoolbuddy_watchdog()
  9312. except asyncio.CancelledError:
  9313. break
  9314. except Exception as e:
  9315. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  9316. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  9317. def start_spoolbuddy_watchdog():
  9318. global _spoolbuddy_watchdog_task
  9319. if _spoolbuddy_watchdog_task is None:
  9320. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  9321. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  9322. def stop_spoolbuddy_watchdog():
  9323. global _spoolbuddy_watchdog_task
  9324. if _spoolbuddy_watchdog_task:
  9325. _spoolbuddy_watchdog_task.cancel()
  9326. _spoolbuddy_watchdog_task = None
  9327. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  9328. # Dead-MQTT-session recovery
  9329. #
  9330. # check_staleness() covers the "connected but silent" half-broken session. It
  9331. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  9332. # is the only thing left watching at that point. When paho stops making
  9333. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  9334. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  9335. # offline with the UI open the whole time, recovered only when something
  9336. # happened to nudge it.
  9337. #
  9338. # This loop is that backstop. It only touches printers that had a working
  9339. # session and lost it, and only when the MQTT port still answers — a printer
  9340. # that is simply switched off is left to paho, since rebuilding a client
  9341. # against an unreachable host achieves nothing and would fill the log every
  9342. # night.
  9343. _connection_watchdog_task: asyncio.Task | None = None
  9344. CONNECTION_WATCHDOG_INTERVAL = 60
  9345. # How long a printer must have been silent before we stop trusting paho.
  9346. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  9347. # so a session that is recovering on its own is never interrupted.
  9348. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  9349. # Per-printer floor between rebuild attempts.
  9350. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  9351. _connection_watchdog_last_attempt: dict[int, float] = {}
  9352. async def _recover_dead_printer_sessions() -> int:
  9353. """Rebuild MQTT clients that have been offline too long to still be trying.
  9354. Returns the number of printers a rebuild was attempted for (for tests and
  9355. for the caller's logging). Never raises: one unreachable printer must not
  9356. stop the sweep for the rest of the farm.
  9357. """
  9358. logger = logging.getLogger(__name__)
  9359. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  9360. now = time.monotonic()
  9361. recovered = 0
  9362. for printer_id, client in list(printer_manager._clients.items()):
  9363. try:
  9364. if client.state.connected:
  9365. _connection_watchdog_last_attempt.pop(printer_id, None)
  9366. continue
  9367. # Time since the last inbound message is the age of the last known
  9368. # good session — no extra bookkeeping needed, and it is the same
  9369. # clock is_stale() reads. 0 means this client has never had one:
  9370. # that is the initial-connect path, where paho retrying is the
  9371. # correct and only behaviour, so leave it be.
  9372. last_msg = client._last_message_time
  9373. if not last_msg:
  9374. continue
  9375. offline_for = time.time() - last_msg
  9376. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  9377. continue
  9378. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  9379. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  9380. continue
  9381. if not await check_port(client.ip_address, PORT_MQTT):
  9382. # Switched off, unplugged, or off the network. Paho's retry is
  9383. # the right handler; say so at debug level and move on.
  9384. logger.debug(
  9385. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  9386. "— leaving the reconnect to paho",
  9387. printer_id,
  9388. offline_for,
  9389. )
  9390. _connection_watchdog_last_attempt[printer_id] = now
  9391. continue
  9392. _connection_watchdog_last_attempt[printer_id] = now
  9393. recovered += 1
  9394. logger.warning(
  9395. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  9396. "rebuilding the client with a fresh session (last connect error: %s)",
  9397. printer_id,
  9398. offline_for,
  9399. PORT_MQTT,
  9400. client.last_connect_error or "none recorded",
  9401. )
  9402. # Async context, so this takes the hard-reset path: fresh client_id,
  9403. # paho's QoS 1 queue dropped. That matters — a project_file left
  9404. # unacked on the dead session would otherwise replay into the new
  9405. # one and trip 0500_4003 on the printer (#1136).
  9406. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  9407. except Exception as e:
  9408. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  9409. return recovered
  9410. async def _connection_watchdog_loop():
  9411. logger = logging.getLogger(__name__)
  9412. # Let the initial connects settle before judging anyone offline.
  9413. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  9414. while True:
  9415. try:
  9416. await _recover_dead_printer_sessions()
  9417. except asyncio.CancelledError:
  9418. break
  9419. except Exception as e:
  9420. logger.warning("Connection watchdog sweep failed: %s", e)
  9421. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  9422. def start_connection_watchdog():
  9423. global _connection_watchdog_task
  9424. if _connection_watchdog_task is None:
  9425. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  9426. logging.getLogger(__name__).info("Printer connection watchdog started")
  9427. def stop_connection_watchdog():
  9428. global _connection_watchdog_task
  9429. if _connection_watchdog_task:
  9430. _connection_watchdog_task.cancel()
  9431. _connection_watchdog_task = None
  9432. _connection_watchdog_last_attempt.clear()
  9433. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  9434. # Camera stream orphan cleanup
  9435. _camera_cleanup_task: asyncio.Task | None = None
  9436. CAMERA_CLEANUP_INTERVAL = 60
  9437. # Every this many camera cleanups (about an hour), the timelapse janitor too:
  9438. # kept frames of a failed stitch go after a day, not at the next restart.
  9439. TIMELAPSE_CLEANUP_EVERY = 60
  9440. async def _camera_cleanup_loop():
  9441. """Periodically clean up orphaned ffmpeg processes and timelapse leftovers."""
  9442. from backend.app.api.routes.camera import cleanup_orphaned_streams
  9443. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9444. rounds = 0
  9445. while True:
  9446. try:
  9447. rounds += 1
  9448. await cleanup_orphaned_streams()
  9449. except asyncio.CancelledError:
  9450. break
  9451. except Exception as e:
  9452. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  9453. try:
  9454. if rounds % TIMELAPSE_CLEANUP_EVERY == 0:
  9455. await asyncio.to_thread(cleanup_orphaned_timelapse_sessions)
  9456. except asyncio.CancelledError:
  9457. break
  9458. except Exception as e:
  9459. logging.getLogger(__name__).warning("Timelapse frames cleanup failed: %s", e)
  9460. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  9461. def start_camera_cleanup():
  9462. global _camera_cleanup_task
  9463. if _camera_cleanup_task is None:
  9464. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  9465. logging.getLogger(__name__).info("Camera stream cleanup started")
  9466. def stop_camera_cleanup():
  9467. global _camera_cleanup_task
  9468. if _camera_cleanup_task:
  9469. _camera_cleanup_task.cancel()
  9470. _camera_cleanup_task = None
  9471. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  9472. # ---------------------------------------------------------------------------
  9473. # Expected-print TTL eviction
  9474. # ---------------------------------------------------------------------------
  9475. def _evict_stale_expected_prints() -> None:
  9476. """Remove entries from _expected_prints / _expected_print_creators that are
  9477. older than _EXPECTED_PRINT_TTL_SECONDS.
  9478. This prevents unbounded growth when a print is registered (via
  9479. register_expected_print) but on_print_start never fires — e.g. because the
  9480. printer disconnects, the app restarts, or the print is started directly from
  9481. the printer panel without going through the queue.
  9482. """
  9483. # Use monotonic time so the TTL is unaffected by system clock adjustments
  9484. # (e.g. NTP sync, DST changes).
  9485. # A print that ended without its archive being found at completion leaves
  9486. # its id here; only running prints are owned.
  9487. _owned_print_archive_ids.intersection_update(_active_prints.values())
  9488. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  9489. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  9490. if not stale_keys:
  9491. return
  9492. evicted_archive_ids: set[int] = set()
  9493. for key in stale_keys:
  9494. archive_id = _expected_prints.pop(key, None)
  9495. if archive_id is not None:
  9496. evicted_archive_ids.add(archive_id)
  9497. _expected_print_creators.pop(key, None)
  9498. _expected_print_registered_at.pop(key, None)
  9499. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  9500. # that have no remaining live keys in _expected_prints (all variants
  9501. # were just evicted) and are not printing right now. Print start pops
  9502. # only the names the printer reported, so the "<base>.gcode" variant
  9503. # outlives it; without the printing check its eviction two hours after
  9504. # dispatch threw away a running print's plate, AMS mapping and cost
  9505. # centre, which completion still reads (#3275).
  9506. live_archive_ids = set(_expected_prints.values()) | set(_active_prints.values())
  9507. for archive_id in evicted_archive_ids:
  9508. if archive_id not in live_archive_ids:
  9509. _print_ams_mappings.pop(archive_id, None)
  9510. _print_cost_center_ids.pop(archive_id, None)
  9511. _print_plate_ids.pop(archive_id, None)
  9512. logging.getLogger(__name__).info(
  9513. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  9514. )
  9515. async def _expected_prints_cleanup_loop() -> None:
  9516. """Background task: periodically evict stale expected-print entries."""
  9517. while True:
  9518. try:
  9519. _evict_stale_expected_prints()
  9520. except asyncio.CancelledError:
  9521. raise
  9522. except Exception as e:
  9523. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  9524. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  9525. def start_expected_prints_cleanup() -> None:
  9526. global _expected_prints_cleanup_task
  9527. if _expected_prints_cleanup_task is None:
  9528. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  9529. logging.getLogger(__name__).info("Expected prints cleanup started")
  9530. def stop_expected_prints_cleanup() -> None:
  9531. global _expected_prints_cleanup_task
  9532. if _expected_prints_cleanup_task:
  9533. _expected_prints_cleanup_task.cancel()
  9534. _expected_prints_cleanup_task = None
  9535. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  9536. # ---------------------------------------------------------------------------
  9537. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  9538. # ---------------------------------------------------------------------------
  9539. _auth_cleanup_task: asyncio.Task | None = None
  9540. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  9541. async def _run_auth_cleanup() -> None:
  9542. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  9543. from backend.app.core.database import async_session
  9544. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  9545. from backend.app.models.user_totp import UserTOTP
  9546. now = datetime.now(timezone.utc)
  9547. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  9548. try:
  9549. async with async_session() as db:
  9550. stale_cutoff = now - timedelta(hours=1)
  9551. result = await db.execute(
  9552. select(UserTOTP).where(
  9553. UserTOTP.is_enabled.is_(False),
  9554. UserTOTP.created_at < stale_cutoff,
  9555. )
  9556. )
  9557. stale_records = result.scalars().all()
  9558. if stale_records:
  9559. for rec in stale_records:
  9560. await db.delete(rec)
  9561. await db.commit()
  9562. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  9563. except Exception as e:
  9564. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  9565. # Remove expired revoked-JTI entries (they are no longer needed once the
  9566. # original token's exp has passed — the token would be rejected by JWT
  9567. # signature verification regardless).
  9568. try:
  9569. async with async_session() as db:
  9570. await db.execute(
  9571. delete(AuthEphemeralToken).where(
  9572. AuthEphemeralToken.token_type == "revoked_jti",
  9573. AuthEphemeralToken.expires_at < now,
  9574. )
  9575. )
  9576. await db.commit()
  9577. except Exception as e:
  9578. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  9579. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  9580. # Events outside this window can never affect rate-limit decisions — they only
  9581. # consume DB space. Use the same window constant as the rate limiter so the
  9582. # two are always in sync.
  9583. try:
  9584. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  9585. async with async_session() as db:
  9586. await db.execute(
  9587. delete(AuthRateLimitEvent).where(
  9588. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  9589. )
  9590. )
  9591. await db.commit()
  9592. except Exception as e:
  9593. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  9594. async def _auth_cleanup_loop() -> None:
  9595. """Periodic background task: run auth cleanup every hour."""
  9596. while True:
  9597. try:
  9598. await _run_auth_cleanup()
  9599. except asyncio.CancelledError:
  9600. break
  9601. except Exception as e:
  9602. logging.warning("Auth cleanup loop error: %s", e)
  9603. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  9604. def start_auth_cleanup() -> None:
  9605. global _auth_cleanup_task
  9606. if _auth_cleanup_task is None:
  9607. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  9608. logging.getLogger(__name__).info("Auth periodic cleanup started")
  9609. def stop_auth_cleanup() -> None:
  9610. global _auth_cleanup_task
  9611. if _auth_cleanup_task:
  9612. _auth_cleanup_task.cancel()
  9613. _auth_cleanup_task = None
  9614. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  9615. @asynccontextmanager
  9616. async def lifespan(app: FastAPI):
  9617. # Startup
  9618. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  9619. # anything else can spawn tasks that might trip it.
  9620. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  9621. install_proactor_reset_filter()
  9622. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  9623. # what turned descriptor exhaustion into a corrupted database (#2883).
  9624. from backend.app.core.fd_limit import raise_open_file_limit
  9625. raise_open_file_limit()
  9626. # Before init_db, so the warning is near the top of the log rather than
  9627. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  9628. warn_if_running_on_uvloop()
  9629. await init_db()
  9630. # Browser download tokens expire after five minutes. Remove abandoned
  9631. # prepared ZIPs at startup as well as before each new preparation so a
  9632. # quiet appliance cannot retain an unusable bundle indefinitely.
  9633. try:
  9634. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  9635. await prune_stale_printer_file_bundles()
  9636. except Exception as exc:
  9637. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  9638. # After migrations, so the is_env_managed column exists. Never raises --
  9639. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  9640. # startup (see apply_env_oidc_provider).
  9641. from backend.app.core.oidc_env import apply_env_oidc_provider
  9642. async with async_session() as oidc_db:
  9643. await apply_env_oidc_provider(oidc_db)
  9644. # Close out batches that finished before `completed` was a reachable status
  9645. # (#342). Without this the Batches tab opens on every batch created since
  9646. # the feature shipped, all still marked active. Never blocks startup.
  9647. try:
  9648. from backend.app.services.print_batch import backfill_batch_statuses
  9649. async with async_session() as batch_db:
  9650. await backfill_batch_statuses(batch_db)
  9651. except Exception as exc:
  9652. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  9653. # Register an app-scoped httpx client for Bambu Cloud services so
  9654. # per-request BambuCloudService instances reuse the same connection pool
  9655. # (important for routes like /cloud/filament-info that chain many
  9656. # get_setting_detail calls). The shared client stores no region/token
  9657. # state, so the per-request ownership pattern that fixed the region-bleed
  9658. # bug is preserved.
  9659. import httpx as _httpx
  9660. from backend.app.services.bambu_cloud import set_shared_http_client
  9661. from backend.app.services.model_providers.makerworld.service import (
  9662. set_shared_http_client as set_shared_makerworld_http_client,
  9663. )
  9664. from backend.app.services.orca_cloud import (
  9665. set_shared_http_client as set_shared_orca_http_client,
  9666. )
  9667. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  9668. set_shared_http_client(_shared_cloud_http_client)
  9669. # Reuse the same connection pool for MakerWorld — different host, same
  9670. # keep-alive pool saves a TLS handshake per request.
  9671. set_shared_makerworld_http_client(_shared_cloud_http_client)
  9672. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  9673. # each spun up (and never closed) its own client, leaking sockets.
  9674. set_shared_orca_http_client(_shared_cloud_http_client)
  9675. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  9676. # This can happen when a print was cancelled mid-print on versions before this fix.
  9677. try:
  9678. async with async_session() as db:
  9679. from backend.app.models.print_queue import PrintQueueItem
  9680. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  9681. aborted_items = result.scalars().all()
  9682. if aborted_items:
  9683. for item in aborted_items:
  9684. item.status = "cancelled"
  9685. await db.commit()
  9686. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  9687. except Exception as e:
  9688. logging.warning("Failed to fix aborted queue items: %s", e)
  9689. # Restore debug logging state from previous session
  9690. await init_debug_logging()
  9691. # Set up printer manager callbacks
  9692. loop = asyncio.get_event_loop()
  9693. printer_manager.set_event_loop(loop)
  9694. printer_manager.set_status_change_callback(on_printer_status_change)
  9695. printer_manager.set_print_start_callback(on_print_start)
  9696. printer_manager.set_print_complete_callback(on_print_complete)
  9697. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  9698. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  9699. printer_manager.set_ams_change_callback(on_ams_change)
  9700. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  9701. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  9702. await printer_manager.load_awaiting_plate_clear_from_db()
  9703. # Layer change callback for external camera timelapse
  9704. async def on_layer_change(printer_id: int, layer_num: int):
  9705. """Capture timelapse frame on layer change + first layer notification."""
  9706. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  9707. await tl_layer_change(printer_id, layer_num)
  9708. # #1867: bank a recent in-print frame so the finish-photo path has a
  9709. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  9710. # #2547 added `on_print_progress` as a second driver — this one alone
  9711. # stops firing once the final layer begins.
  9712. await _maybe_bank_inprint_frame(printer_id, layer_num)
  9713. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  9714. # Gate on actual printing state — Bambu firmware ticks layer_num during
  9715. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  9716. # nozzle clean), so a bare layer_num check can fire minutes before the
  9717. # first real extrusion. We require gcode_state == RUNNING and
  9718. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  9719. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  9720. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  9721. # edge fires later; _first_layer_notified stays clear until we actually send
  9722. # so a deferred re-evaluation can win. See issue #1837.
  9723. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  9724. client = printer_manager.get_client(printer_id)
  9725. state = client.state if client else None
  9726. if not state or state.state != "RUNNING":
  9727. return
  9728. if state.mc_print_sub_stage not in (None, 0):
  9729. return
  9730. _first_layer_notified[printer_id] = True
  9731. try:
  9732. async with async_session() as db:
  9733. from backend.app.models.printer import Printer
  9734. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9735. printer = result.scalar_one_or_none()
  9736. if not printer:
  9737. return
  9738. printer_name = printer.name
  9739. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  9740. total_layers = state.total_layers if state else 0
  9741. image_data = await _capture_snapshot_for_notification(
  9742. printer_id, printer, logging.getLogger(__name__)
  9743. )
  9744. await notification_service.on_first_layer_complete(
  9745. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  9746. )
  9747. except Exception as e:
  9748. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  9749. printer_manager.set_layer_change_callback(on_layer_change)
  9750. async def on_print_progress(printer_id: int, percent: int):
  9751. """#2547: keep the in-print frame bank fresh through the final layer.
  9752. `on_layer_change` stops the moment the last layer starts, which on the
  9753. H2C capture that closed #2547 left the bank stale for the three minutes
  9754. that layer took. Progress is the only field that keeps advancing there,
  9755. and it freezes before the End G-code runs — so banking on it stays
  9756. inside the print and never sees a swapped plate.
  9757. """
  9758. client = printer_manager.get_client(printer_id)
  9759. state = client.state if client else None
  9760. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  9761. printer_manager.set_print_progress_callback(on_print_progress)
  9762. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  9763. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  9764. waiter = _bed_cool_waiters.get(printer_id)
  9765. if not waiter:
  9766. return
  9767. threshold = waiter["threshold"]
  9768. if bed_temp > threshold:
  9769. return
  9770. # Bed is at or below threshold — fire notification and remove waiter
  9771. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  9772. if not waiter_info:
  9773. return # Another callback already handled it
  9774. bed_cool_logger = logging.getLogger(__name__)
  9775. bed_cool_logger.info(
  9776. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  9777. bed_temp,
  9778. printer_id,
  9779. threshold,
  9780. )
  9781. try:
  9782. printer_info = printer_manager.get_printer(printer_id)
  9783. p_name = printer_info.name if printer_info else "Unknown"
  9784. async with async_session() as db:
  9785. await notification_service.on_bed_cooled(
  9786. printer_id=printer_id,
  9787. printer_name=p_name,
  9788. bed_temp=bed_temp,
  9789. threshold=threshold,
  9790. filename=waiter_info["filename"],
  9791. db=db,
  9792. )
  9793. except Exception as e:
  9794. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  9795. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  9796. async def on_drying_complete(printer_id: int, ams_id: int):
  9797. """Smart-plug auto-off-after-drying trigger (#1349).
  9798. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  9799. manager walks all plugs linked to this printer and turns off only
  9800. the ones with ``auto_off_after_drying`` enabled, after their
  9801. per-plug delay. Multiple AMS units finishing close together (e.g. a
  9802. dual-AMS dry that ends within the same MQTT push) call this once
  9803. per unit — the manager's ``_cancel_pending_off`` collapses
  9804. repeated scheduling on the same plug to one timer, so duplicate
  9805. fires are safe.
  9806. """
  9807. try:
  9808. async with async_session() as db:
  9809. await smart_plug_manager.on_drying_complete(printer_id, db)
  9810. except Exception as e:
  9811. logging.getLogger(__name__).warning(
  9812. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  9813. printer_id,
  9814. ams_id,
  9815. e,
  9816. )
  9817. printer_manager.set_drying_complete_callback(on_drying_complete)
  9818. async def on_drying_cycle_end(printer_id: int, cycle):
  9819. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  9820. from backend.app.services.spool_drying import record_drying_cycle
  9821. try:
  9822. async with async_session() as db:
  9823. await record_drying_cycle(db, printer_id, cycle)
  9824. except Exception as e:
  9825. logging.getLogger(__name__).warning(
  9826. "Failed to record drying for printer %d (AMS %d): %s",
  9827. printer_id,
  9828. cycle.ams_id,
  9829. e,
  9830. )
  9831. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  9832. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  9833. """Surface the read-back result of a spool assignment to the UI (#2582).
  9834. The MQTT client confirms (or fails to confirm) that the tray telemetry
  9835. echoed back the filament id we pushed. We relay that as a websocket
  9836. event so the frontend can toast "loaded" / "assignment didn't take"
  9837. instead of the historic silent fire-and-forget, which made the
  9838. AMS→Studio hand-off feel random to users.
  9839. """
  9840. try:
  9841. from backend.app.services.spool_assignment_notifications import (
  9842. _slot_label_from_global_tray,
  9843. )
  9844. if ams_id == 255:
  9845. global_id = 254 + tray_id
  9846. elif ams_id >= 128:
  9847. global_id = ams_id
  9848. else:
  9849. global_id = ams_id * 4 + tray_id
  9850. slot_label = _slot_label_from_global_tray(global_id)
  9851. printer_info = printer_manager.get_printer(printer_id)
  9852. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  9853. await ws_manager.broadcast(
  9854. {
  9855. "type": "spool_assignment_verified",
  9856. "printer_id": printer_id,
  9857. "printer_name": printer_name,
  9858. "ams_id": ams_id,
  9859. "tray_id": tray_id,
  9860. "slot": slot_label,
  9861. "verified": verified,
  9862. # Present on success: False means the filament setting landed
  9863. # but the K-profile (cali_idx) did not — the reporter's exact
  9864. # "loaded but no flow profile" symptom.
  9865. "kprofile_applied": detail.get("kprofile_applied", True),
  9866. }
  9867. )
  9868. except Exception as e:
  9869. logging.getLogger(__name__).warning(
  9870. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  9871. printer_id,
  9872. ams_id,
  9873. tray_id,
  9874. e,
  9875. )
  9876. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  9877. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  9878. """Persist a mid-print tray change for completion-time attribution.
  9879. AMS filament backup switches trays without telling the slicer, so the
  9880. tray-change log is the only record of which spool fed which layers.
  9881. Keeping it only in memory meant a restart mid-print charged everything
  9882. to the tray that finished the job.
  9883. """
  9884. try:
  9885. from backend.app.services.usage_tracker import record_tray_change
  9886. async with async_session() as db:
  9887. await record_tray_change(db, printer_id, tray_global, layer_num)
  9888. except Exception as e:
  9889. logging.getLogger(__name__).warning(
  9890. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  9891. printer_id,
  9892. tray_global,
  9893. layer_num,
  9894. e,
  9895. )
  9896. printer_manager.set_tray_change_callback(on_tray_change)
  9897. # Initialize MQTT relay from settings
  9898. async with async_session() as db:
  9899. from backend.app.api.routes.settings import get_setting
  9900. mqtt_settings = {
  9901. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  9902. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  9903. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  9904. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  9905. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  9906. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  9907. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  9908. }
  9909. await mqtt_relay.configure(mqtt_settings)
  9910. # Restore MQTT smart plug subscriptions
  9911. if mqtt_settings.get("mqtt_enabled"):
  9912. from backend.app.models.smart_plug import SmartPlug
  9913. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  9914. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  9915. mqtt_plugs = result.scalars().all()
  9916. restored = 0
  9917. for plug in mqtt_plugs:
  9918. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  9919. restored += 1
  9920. if restored:
  9921. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  9922. # Connect to all active printers
  9923. async with async_session() as db:
  9924. await init_printer_connections(db)
  9925. # Auto-connect to Spoolman if enabled
  9926. async with async_session() as db:
  9927. from backend.app.api.routes.settings import get_setting
  9928. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  9929. spoolman_url = await get_setting(db, "spoolman_url")
  9930. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  9931. try:
  9932. client = await init_spoolman_client(spoolman_url)
  9933. if await client.health_check():
  9934. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  9935. # Ensure the 'tag' extra field exists for RFID/UUID storage
  9936. field_ok = await client.ensure_tag_extra_field()
  9937. if not field_ok:
  9938. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  9939. # Register the BambuStudio slicer-preset fields used by the
  9940. # spool-edit / assign flow. Spoolman rejects PATCHes with
  9941. # unknown extra keys, so these must exist before any update
  9942. # that touches them.
  9943. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  9944. if not await client.ensure_extra_field(field_name):
  9945. logging.warning(
  9946. "Spoolman extra field %r registration failed — "
  9947. "spool slicer-preset edits will return 502",
  9948. field_name,
  9949. )
  9950. else:
  9951. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  9952. except Exception as e:
  9953. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  9954. # Start the print scheduler
  9955. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  9956. # Start the smart plug scheduler for time-based on/off
  9957. smart_plug_manager.start_scheduler()
  9958. # Start the Home Assistant sensor poller (#1148)
  9959. ha_sensor_manager.start()
  9960. location_ha_sensor_manager.start()
  9961. # Resume any pending auto-offs that were interrupted by restart
  9962. await smart_plug_manager.resume_pending_auto_offs()
  9963. # Start the notification digest scheduler
  9964. notification_service.start_digest_scheduler()
  9965. notify_live_activities.start()
  9966. notify_widgets.start()
  9967. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  9968. # provider in reactions/both mode; the notification routes resync them.
  9969. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  9970. # until the next provider save, not the whole startup.
  9971. try:
  9972. await telegram_reaction_poller.start()
  9973. except Exception as e:
  9974. logging.warning("Telegram reaction poller did not start: %s", e)
  9975. # Start the GitHub backup scheduler
  9976. await github_backup_service.start_scheduler()
  9977. # Start the local backup scheduler
  9978. await local_backup_service.start_scheduler()
  9979. await obico_detection_service.start()
  9980. # Start the library trash sweeper (#1008)
  9981. await library_trash_service.start_scheduler()
  9982. # Start the archive auto-purge sweeper (#1008 follow-up)
  9983. await archive_purge_service.start_scheduler()
  9984. # Start AMS history recording
  9985. start_ams_history_recording()
  9986. # Start printer sensor (nozzle / bed / chamber) history recording
  9987. start_printer_sensor_history_recording()
  9988. # Start printer runtime tracking
  9989. start_runtime_tracking()
  9990. # Start SpoolBuddy device watchdog
  9991. start_spoolbuddy_watchdog()
  9992. # Start camera stream orphan cleanup
  9993. start_camera_cleanup()
  9994. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  9995. start_connection_watchdog()
  9996. # One-shot sweep for timelapse session directories orphaned by a crash
  9997. # or restart that happened mid-print (in-memory session tracking can't
  9998. # survive that, and nothing else reaps the leftover frames/output file)
  9999. try:
  10000. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  10001. removed = cleanup_orphaned_timelapse_sessions()
  10002. if removed:
  10003. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  10004. except Exception as e:
  10005. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  10006. # Start expected-print TTL eviction (prevents memory leak when prints are
  10007. # registered but on_print_start never fires)
  10008. start_expected_prints_cleanup()
  10009. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  10010. start_auth_cleanup()
  10011. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  10012. from backend.app.services import announcements as announcements_service
  10013. announcements_service.start()
  10014. from backend.app.services.printer_media import start_printer_download_cleanup
  10015. start_printer_download_cleanup()
  10016. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  10017. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  10018. from backend.app.services.loop_watchdog import start_loop_watchdog
  10019. start_loop_watchdog()
  10020. # Initialize virtual printer manager and sync from DB
  10021. from backend.app.services.virtual_printer import virtual_printer_manager
  10022. virtual_printer_manager.set_session_factory(async_session)
  10023. virtual_printer_manager.set_printer_manager(printer_manager)
  10024. try:
  10025. await virtual_printer_manager.sync_from_db()
  10026. logging.info("Virtual printer manager synced from database")
  10027. except Exception as e:
  10028. logging.warning("Failed to sync virtual printers: %s", e)
  10029. yield
  10030. # Shutdown
  10031. print_scheduler.stop()
  10032. smart_plug_manager.stop_scheduler()
  10033. ha_sensor_manager.stop()
  10034. location_ha_sensor_manager.stop()
  10035. notification_service.stop_digest_scheduler()
  10036. await notify_live_activities.close()
  10037. await notify_widgets.close()
  10038. await telegram_reaction_poller.aclose()
  10039. github_backup_service.stop_scheduler()
  10040. local_backup_service.stop_scheduler()
  10041. library_trash_service.stop_scheduler()
  10042. archive_purge_service.stop_scheduler()
  10043. obico_detection_service.stop()
  10044. stop_ams_history_recording()
  10045. stop_printer_sensor_history_recording()
  10046. stop_runtime_tracking()
  10047. stop_spoolbuddy_watchdog()
  10048. stop_camera_cleanup()
  10049. stop_connection_watchdog()
  10050. from backend.app.services.loop_watchdog import stop_loop_watchdog
  10051. stop_loop_watchdog()
  10052. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  10053. # cleanly rather than waiting on a queue that nothing will ever fill.
  10054. try:
  10055. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  10056. await shutdown_all_broadcasters()
  10057. except Exception as e:
  10058. logging.warning("Failed to shut down camera broadcasters: %s", e)
  10059. stop_expected_prints_cleanup()
  10060. stop_auth_cleanup()
  10061. from backend.app.services import announcements as announcements_service
  10062. announcements_service.stop()
  10063. from backend.app.services.printer_media import stop_printer_download_cleanup
  10064. await stop_printer_download_cleanup()
  10065. # Stops a timelapse editor's ffmpeg rather than leaving it to the OS.
  10066. from backend.app.services import timelapse_jobs
  10067. await timelapse_jobs.cancel_all()
  10068. printer_manager.disconnect_all()
  10069. slot_unlink_grace.reset()
  10070. await close_spoolman_client()
  10071. # Stop all virtual printer services
  10072. await virtual_printer_manager.stop_all()
  10073. await mqtt_smart_plug_service.disconnect(timeout=2)
  10074. await mqtt_relay.disconnect(timeout=2)
  10075. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  10076. set_shared_http_client(None)
  10077. set_shared_makerworld_http_client(None)
  10078. set_shared_orca_http_client(None)
  10079. await _shared_cloud_http_client.aclose()
  10080. # Checkpoint WAL (SQLite only) and close all database connections
  10081. from backend.app.core.db_dialect import is_sqlite
  10082. if is_sqlite():
  10083. try:
  10084. async with engine.begin() as conn:
  10085. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  10086. logging.info("WAL checkpoint completed")
  10087. except Exception as e:
  10088. logging.warning("WAL checkpoint failed: %s", e)
  10089. await engine.dispose()
  10090. app = FastAPI(
  10091. title=app_settings.app_name,
  10092. description="Archive and manage Bambu Lab 3MF files",
  10093. version=APP_VERSION,
  10094. lifespan=lifespan,
  10095. )
  10096. # Added first so it sits innermost, next to the routes: a refused header's value
  10097. # (often a stored token) masked in every JSON body. See core.response_redaction.
  10098. app.add_middleware(RefusedHeaderResponseMask)
  10099. def _json_safe(value):
  10100. """The validation errors with every non-finite number written as text."""
  10101. if isinstance(value, float) and not math.isfinite(value):
  10102. return str(value)
  10103. if isinstance(value, dict):
  10104. return {key: _json_safe(item) for key, item in value.items()}
  10105. if isinstance(value, list | tuple):
  10106. return [_json_safe(item) for item in value]
  10107. return value
  10108. @app.exception_handler(RequestValidationError)
  10109. async def _validation_error(_request, exc: RequestValidationError) -> JSONResponse:
  10110. """FastAPI's own 422, except that it survives a non-finite number.
  10111. A body may carry ``Infinity`` or ``NaN`` (Python's JSON reader accepts
  10112. them), and the default handler echoes the input back in its errors,
  10113. which JSON cannot hold: the request ended in an error instead of a 422.
  10114. """
  10115. return JSONResponse(status_code=422, content={"detail": _json_safe(jsonable_encoder(exc.errors()))})
  10116. # =============================================================================
  10117. # Authentication Middleware - Secures ALL API routes by default
  10118. # =============================================================================
  10119. # Public routes that don't require authentication even when auth is enabled
  10120. PUBLIC_API_ROUTES = {
  10121. # Auth routes needed before/during login
  10122. "/api/v1/auth/status",
  10123. "/api/v1/auth/login",
  10124. "/api/v1/auth/setup", # Needed for initial setup and recovery
  10125. # Advanced auth status needed for login page
  10126. "/api/v1/auth/advanced-auth/status",
  10127. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  10128. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  10129. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  10130. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  10131. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  10132. # OIDC routes that must be reachable without a JWT
  10133. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  10134. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  10135. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  10136. # Connected apps: the app's server swaps a code for the user's identity,
  10137. # authenticated by its client secret rather than a login token.
  10138. "/api/v1/connect/token",
  10139. # Version check for updates (no sensitive data)
  10140. "/api/v1/updates/version",
  10141. # Metrics endpoint handles its own prometheus_token authentication
  10142. "/api/v1/metrics",
  10143. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  10144. # this BEFORE a JWT is available to pick up the firstboot wizard's
  10145. # hostname / timezone / locale and the chrony NTP-gate state. The
  10146. # response contains user-set defaults and a public sync flag — no
  10147. # secrets. Without this entry the global auth middleware returns 401
  10148. # before the route handler runs, regardless of the route's own
  10149. # "no auth required" intent.
  10150. "/api/v1/system/appliance",
  10151. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  10152. # authenticates with a long-lived ``camwall``-scoped token in the query
  10153. # string — exactly like the camera streams two lists below, and for the same
  10154. # reason (no header to put a JWT in). "Public" here only means the middleware
  10155. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  10156. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  10157. # plain ``camera_stream`` token does NOT open this door.
  10158. "/api/v1/camwall/printers",
  10159. # Overlay branding: the route enforces overlay-scoped token authentication.
  10160. "/api/v1/overlay-branding/logo",
  10161. }
  10162. # Route prefixes that are public (for routes with dynamic segments)
  10163. PUBLIC_API_PREFIXES = [
  10164. # WebSocket connections handle their own auth
  10165. "/api/v1/ws",
  10166. # OIDC authorize redirects — include provider_id in path
  10167. "/api/v1/auth/oidc/authorize/",
  10168. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  10169. # a phone with no session, so no header can carry a JWT — the single-use
  10170. # capability token in the path IS the credential (same reasoning as the
  10171. # /dl/ slicer downloads below). The route grants nothing beyond writing
  10172. # good/reject on the one archive the token was minted for.
  10173. "/api/v1/archives/confirm/",
  10174. ]
  10175. # Route patterns that are public (read-only display data)
  10176. # These are checked with "in path" - needed because browsers load images/videos
  10177. # via <img src> and <video src> which don't include Authorization headers
  10178. PUBLIC_API_PATTERNS = [
  10179. # Thumbnails
  10180. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  10181. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  10182. # Images and media
  10183. "/photos/", # /archives/{id}/photos/{filename}
  10184. "/project-image/", # /archives/{id}/project-image/{path}
  10185. "/qrcode", # /archives/{id}/qrcode
  10186. "/timelapse", # /archives/{id}/timelapse (video)
  10187. "/cover", # /printers/{id}/cover
  10188. "/icon", # /external-links/{id}/icon
  10189. # Camera (streams loaded via <img> tag)
  10190. "/camera/stream", # /printers/{id}/camera/stream
  10191. "/camera/snapshot", # /printers/{id}/camera/snapshot
  10192. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  10193. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  10194. # string (same reasoning as the camera streams above — no header to carry a
  10195. # JWT). "Public" only means the middleware steps aside; the route still runs
  10196. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  10197. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  10198. "/overlay-status", # /printers/{id}/overlay-status
  10199. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  10200. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  10201. # download token in the URL path instead.
  10202. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  10203. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  10204. # and these patterns match by substring. Without its own entry the middleware
  10205. # 401s the slicer's header-less request before the route's token check runs,
  10206. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  10207. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  10208. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  10209. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  10210. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  10211. ]
  10212. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  10213. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  10214. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  10215. Format: comma-separated list of ``scheme://host[:port]`` origins.
  10216. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  10217. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  10218. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  10219. Invalid entries are dropped with a warning rather than failing startup, so
  10220. a typo in one origin doesn't take the whole deployment down.
  10221. """
  10222. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  10223. if not raw:
  10224. return ()
  10225. valid: list[str] = []
  10226. for item in raw.split(","):
  10227. candidate = item.strip()
  10228. if not candidate:
  10229. continue
  10230. try:
  10231. parsed = urlparse(candidate)
  10232. except ValueError as e:
  10233. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  10234. continue
  10235. if parsed.scheme not in ("http", "https"):
  10236. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  10237. continue
  10238. if not parsed.netloc:
  10239. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  10240. continue
  10241. if parsed.path and parsed.path != "/":
  10242. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  10243. continue
  10244. if parsed.query or parsed.fragment:
  10245. _security_headers_logger.warning(
  10246. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  10247. )
  10248. continue
  10249. if "*" in parsed.netloc:
  10250. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  10251. continue
  10252. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  10253. if valid:
  10254. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  10255. return tuple(valid)
  10256. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  10257. def _frame_ancestors(default_value: str) -> str:
  10258. """Compose the ``frame-ancestors`` CSP directive (#1191).
  10259. ``default_value`` is the strict directive used when the operator has not
  10260. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  10261. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  10262. Settings URL builder's preview). When trusted origins
  10263. are configured, ``'self'`` is always included so same-origin embedding never
  10264. breaks even if an operator forgets to add their own origin to the list.
  10265. """
  10266. if _TRUSTED_FRAME_ORIGINS:
  10267. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  10268. return f"frame-ancestors {default_value};"
  10269. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  10270. # patterns are anchored on the exact emitted name so the relaxed policies
  10271. # below can never apply to any other asset.
  10272. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  10273. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  10274. # -> /assets/pdf.worker.min-<hash>.js
  10275. # Vite also emits a one-line chunk under the second name that only exports the
  10276. # worker's URL. The page imports it as a module, and a module script is run
  10277. # under the importing document's policy, never its own response's, so it
  10278. # matching as well changes nothing.
  10279. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  10280. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  10281. @app.middleware("http")
  10282. async def security_headers_middleware(request, call_next):
  10283. """Add standard HTTP security headers to every response."""
  10284. # Per-request nonce stamped into `script-src` (#1460). On its own this
  10285. # changes nothing for Bambuddy's own pages — index.html has no inline
  10286. # scripts since the SW registration moved to /sw-register.js. The reason
  10287. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  10288. # script injected into the HTML on the edge, with a fresh hash on every
  10289. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  10290. # it clones the same nonce onto its injected <script>, and the inline
  10291. # script passes the policy without us needing 'unsafe-inline'. See
  10292. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  10293. csp_nonce = secrets.token_urlsafe(16)
  10294. # Routes that render their own HTML need it too, or their inline script is
  10295. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  10296. # one that does: it submits its own form so a verdict still costs one tap.
  10297. request.state.csp_nonce = csp_nonce
  10298. response = await call_next(request)
  10299. response.headers["X-Content-Type-Options"] = "nosniff"
  10300. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  10301. # browsers honour CSP frame-ancestors instead, and the legacy
  10302. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  10303. # When operators have explicitly allowlisted trusted frame origins (#1191
  10304. # — typically Home Assistant on a different port), drop X-Frame-Options
  10305. # and let the CSP-side frame-ancestors directive govern embedding.
  10306. if not _TRUSTED_FRAME_ORIGINS:
  10307. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  10308. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  10309. # Content-Security-Policy for the React SPA.
  10310. # Notes:
  10311. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  10312. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  10313. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  10314. # - media-src blob:: timelapse video player uses Blob URLs.
  10315. # - font-src data:: some icon fonts are embedded as data URIs.
  10316. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  10317. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  10318. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  10319. # default CSP would render a blank page.
  10320. response.headers["Content-Security-Policy"] = (
  10321. "default-src 'self'; "
  10322. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  10323. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  10324. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  10325. "connect-src 'self'; "
  10326. "font-src 'self' data: https://fonts.gstatic.com; "
  10327. "worker-src 'self' blob:; "
  10328. "object-src 'none'; "
  10329. "base-uri 'self'; " + _frame_ancestors("'none'")
  10330. )
  10331. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  10332. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  10333. # its emscripten/embind glue generates invoker functions with `new
  10334. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  10335. # worker is governed by the policy delivered with the WORKER SCRIPT's
  10336. # own response — not the document's — so relaxing it here confines
  10337. # eval to that DOM-less worker context. The document policy below
  10338. # stays nonce-strict, and this response header has no effect when the
  10339. # file is merely fetched (a fetch's CSP is enforced against the
  10340. # requesting document, not the resource's own headers).
  10341. response.headers["Content-Security-Policy"] = (
  10342. "default-src 'self'; "
  10343. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  10344. "connect-src 'self'; "
  10345. "object-src 'none'; "
  10346. "base-uri 'self'; " + _frame_ancestors("'none'")
  10347. )
  10348. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  10349. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  10350. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  10351. # rule as the STEP worker above: the policy that governs a dedicated
  10352. # worker is the one delivered with its own script, so the wasm compile
  10353. # has to be permitted here rather than on the document. Unlike the STEP
  10354. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  10355. response.headers["Content-Security-Policy"] = (
  10356. "default-src 'self'; "
  10357. "script-src 'self' 'wasm-unsafe-eval'; "
  10358. "connect-src 'self'; "
  10359. "object-src 'none'; "
  10360. "base-uri 'self'; " + _frame_ancestors("'none'")
  10361. )
  10362. else:
  10363. # The streaming overlay is embedded same-origin by the URL builder's
  10364. # preview in Settings (#1422), so this branch allows 'self'.
  10365. # Embedding from anywhere else is still refused: 'self'
  10366. # only permits a framer on this origin, which is Bambuddy's own UI, so
  10367. # a clickjacking page on another host is blocked exactly as before.
  10368. # (The overlay draws status over a camera feed and its only interactive
  10369. # element is the logo link, so there is nothing to bait a click into
  10370. # even from a same-origin framer.) Cross-origin embedding of the
  10371. # overlay — Home Assistant on another port — remains what
  10372. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  10373. # allowlist in.
  10374. #
  10375. # The connected-app consent page (/connect/authorize) gets the same
  10376. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  10377. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  10378. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  10379. # requires every ancestor to be this origin, so a foreign page -- a
  10380. # sidebar link's site included -- still cannot frame the consent
  10381. # screen to bait a click.
  10382. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  10383. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  10384. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  10385. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  10386. # the policy served with their own script, so each gets it in its own
  10387. # branch above and the document policy stays as strict as it was.
  10388. response.headers["Content-Security-Policy"] = (
  10389. "default-src 'self'; "
  10390. f"script-src 'self' 'nonce-{csp_nonce}'; "
  10391. "style-src 'self' 'unsafe-inline'; "
  10392. "img-src 'self' data: blob:; "
  10393. "media-src 'self' blob:; "
  10394. "connect-src 'self' ws: wss:; "
  10395. "font-src 'self' data:; "
  10396. "object-src 'none'; "
  10397. "base-uri 'self'; "
  10398. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  10399. )
  10400. if request.url.scheme == "https":
  10401. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  10402. return response
  10403. @app.middleware("http")
  10404. async def auth_middleware(request, call_next):
  10405. """Enforce authentication on all API routes when auth is enabled.
  10406. This middleware provides defense-in-depth by checking auth at the API gateway level,
  10407. regardless of whether individual routes have auth dependencies.
  10408. """
  10409. from starlette.responses import JSONResponse
  10410. path = request.url.path
  10411. # Only apply to API routes
  10412. if not path.startswith("/api/"):
  10413. return await call_next(request)
  10414. # Allow public routes
  10415. if path in PUBLIC_API_ROUTES:
  10416. return await call_next(request)
  10417. # Allow public prefixes
  10418. for prefix in PUBLIC_API_PREFIXES:
  10419. if path.startswith(prefix):
  10420. return await call_next(request)
  10421. # Allow public patterns (read-only display data like thumbnails)
  10422. for pattern in PUBLIC_API_PATTERNS:
  10423. if pattern in path:
  10424. return await call_next(request)
  10425. # Check if auth is enabled. Fail CLOSED on any exception during the
  10426. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  10427. # an attacker who could force a DB exception (e.g. file-descriptor
  10428. # exhaustion via login flood) bypass auth on every protected endpoint.
  10429. # Only the probe is guarded: the request itself runs outside the try, so an
  10430. # error in a route surfaces as the 500 it is rather than as an auth outage.
  10431. try:
  10432. async with async_session() as db:
  10433. from backend.app.core.auth import is_auth_enabled
  10434. auth_enabled = await is_auth_enabled(db)
  10435. except Exception:
  10436. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  10437. return JSONResponse(
  10438. status_code=503,
  10439. content={"detail": "Authentication service temporarily unavailable"},
  10440. )
  10441. if not auth_enabled:
  10442. # Auth disabled, allow all requests
  10443. return await call_next(request)
  10444. # Auth is enabled - require valid token
  10445. auth_header = request.headers.get("Authorization")
  10446. x_api_key = request.headers.get("X-API-Key")
  10447. # Check for API key auth first
  10448. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  10449. # API key authentication - let the request through to be validated by route handler
  10450. # API keys are validated per-route since they have different permission levels
  10451. return await call_next(request)
  10452. # Check for JWT auth
  10453. if not auth_header or not auth_header.startswith("Bearer "):
  10454. return JSONResponse(
  10455. status_code=401,
  10456. content={"detail": "Authentication required"},
  10457. headers={"WWW-Authenticate": "Bearer"},
  10458. )
  10459. # Validate JWT token
  10460. import jwt
  10461. try:
  10462. from backend.app.core.auth import (
  10463. ALGORITHM,
  10464. SECRET_KEY,
  10465. _is_token_fresh,
  10466. get_user_by_username,
  10467. is_jti_revoked,
  10468. )
  10469. token = auth_header.replace("Bearer ", "")
  10470. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  10471. username = payload.get("sub")
  10472. if not username:
  10473. raise ValueError("No username in token")
  10474. jti = payload.get("jti")
  10475. if not jti:
  10476. raise ValueError("No jti in token")
  10477. iat = payload.get("iat")
  10478. # Verify user exists, is active, and token is still fresh (L-R8-A).
  10479. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  10480. # this session so the gateway adds a single pooled checkout, not two (#2572).
  10481. async with async_session() as db:
  10482. if await is_jti_revoked(jti, db):
  10483. return JSONResponse(
  10484. status_code=401,
  10485. content={"detail": "Token has been revoked"},
  10486. headers={"WWW-Authenticate": "Bearer"},
  10487. )
  10488. user = await get_user_by_username(db, username)
  10489. if not user or not user.is_active:
  10490. return JSONResponse(
  10491. status_code=401,
  10492. content={"detail": "User not found or inactive"},
  10493. headers={"WWW-Authenticate": "Bearer"},
  10494. )
  10495. if not _is_token_fresh(iat, user):
  10496. return JSONResponse(
  10497. status_code=401,
  10498. content={"detail": "Token no longer valid"},
  10499. headers={"WWW-Authenticate": "Bearer"},
  10500. )
  10501. except jwt.ExpiredSignatureError:
  10502. return JSONResponse(
  10503. status_code=401,
  10504. content={"detail": "Token has expired"},
  10505. headers={"WWW-Authenticate": "Bearer"},
  10506. )
  10507. except (jwt.InvalidTokenError, ValueError):
  10508. return JSONResponse(
  10509. status_code=401,
  10510. content={"detail": "Invalid token"},
  10511. headers={"WWW-Authenticate": "Bearer"},
  10512. )
  10513. except Exception:
  10514. # Not a bad token but a failure checking it (database, pool): refuse,
  10515. # as for the probe above, rather than answer 401 -- the frontend reads
  10516. # a 401 from /auth/me as final and signs the user out.
  10517. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  10518. return JSONResponse(
  10519. status_code=503,
  10520. content={"detail": "Authentication service temporarily unavailable"},
  10521. )
  10522. return await call_next(request)
  10523. @app.middleware("http")
  10524. async def trace_id_middleware(request, call_next):
  10525. """Stamp every HTTP request with a trace ID and echo it back.
  10526. Decorated AFTER auth_middleware on purpose: Starlette stacks
  10527. @app.middleware decorators LIFO, so the last-decorated runs first
  10528. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  10529. which means auth-middleware log lines (and every line emitted on the
  10530. way down to and back from the route handler) all carry the same
  10531. trace ID. If we put it before auth, auth's logs would be stamped
  10532. with the *previous* request's ID — useless for correlation.
  10533. Honours an inbound ``X-Trace-Id`` header so callers running their
  10534. own tracing can correlate their span IDs with our log lines, but
  10535. only if the value passes the whitelist gate in
  10536. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  10537. rejected (too long, contains control chars, etc.) silently triggers
  10538. a freshly minted server-side ID rather than failing the request.
  10539. The minted (or echoed) ID is set on a ContextVar so that every log
  10540. record emitted during the request — application logs *and* uvicorn's
  10541. access log — carries it via TraceIDFilter, and is also written to
  10542. the ``X-Trace-Id`` response header so clients can pin a server-side
  10543. log search to the exact request they made.
  10544. """
  10545. from backend.app.core.trace import (
  10546. generate_trace_id,
  10547. normalise_inbound_trace_id,
  10548. trace_id_var,
  10549. )
  10550. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  10551. trace_id = inbound if inbound is not None else generate_trace_id()
  10552. token = trace_id_var.set(trace_id)
  10553. try:
  10554. response = await call_next(request)
  10555. finally:
  10556. # Reset the ContextVar so a record emitted in a totally
  10557. # unrelated background task that just happens to inherit this
  10558. # context doesn't keep referencing this request's ID forever.
  10559. # In practice ContextVar.reset is best-effort under asyncio
  10560. # task-spawn semantics, but the cost is one attribute write so
  10561. # we may as well do it.
  10562. trace_id_var.reset(token)
  10563. response.headers["X-Trace-Id"] = trace_id
  10564. return response
  10565. # API routes
  10566. app.include_router(auth.router, prefix=app_settings.api_prefix)
  10567. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  10568. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  10569. app.include_router(users.router, prefix=app_settings.api_prefix)
  10570. app.include_router(groups.router, prefix=app_settings.api_prefix)
  10571. app.include_router(printers.router, prefix=app_settings.api_prefix)
  10572. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  10573. app.include_router(archives.router, prefix=app_settings.api_prefix)
  10574. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  10575. app.include_router(finance.router, prefix=app_settings.api_prefix)
  10576. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  10577. app.include_router(labels.router, prefix=app_settings.api_prefix)
  10578. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  10579. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  10580. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  10581. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  10582. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  10583. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  10584. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  10585. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  10586. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  10587. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  10588. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  10589. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  10590. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  10591. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  10592. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  10593. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  10594. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  10595. app.include_router(updates.router, prefix=app_settings.api_prefix)
  10596. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  10597. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  10598. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  10599. app.include_router(camera.router, prefix=app_settings.api_prefix)
  10600. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  10601. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  10602. app.include_router(projects.router, prefix=app_settings.api_prefix)
  10603. app.include_router(library.router, prefix=app_settings.api_prefix)
  10604. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  10605. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  10606. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  10607. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  10608. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  10609. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  10610. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  10611. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  10612. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  10613. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  10614. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  10615. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  10616. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  10617. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  10618. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  10619. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  10620. app.include_router(system.router, prefix=app_settings.api_prefix)
  10621. app.include_router(support.router, prefix=app_settings.api_prefix)
  10622. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  10623. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  10624. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  10625. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  10626. app.include_router(bulk.router, prefix=app_settings.api_prefix)
  10627. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  10628. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  10629. app.include_router(obico.router, prefix=app_settings.api_prefix)
  10630. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  10631. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  10632. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  10633. # Serve static files (React build)
  10634. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  10635. # Compressed, and cached for good where Vite hashed the name (#3175).
  10636. app.mount(
  10637. "/assets",
  10638. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  10639. name="assets",
  10640. )
  10641. if (app_settings.static_dir / "img").exists():
  10642. app.mount(
  10643. "/img",
  10644. StaticFiles(directory=app_settings.static_dir / "img"),
  10645. name="img",
  10646. )
  10647. if (app_settings.static_dir / "icons").exists():
  10648. app.mount(
  10649. "/icons",
  10650. StaticFiles(directory=app_settings.static_dir / "icons"),
  10651. name="icons",
  10652. )
  10653. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  10654. # falls through to the SPA catch-all and returns index.html, which the
  10655. # browser's font sanitizer rejects ("downloadable font: rejected by
  10656. # sanitizer").
  10657. if (app_settings.static_dir / "fonts").exists():
  10658. app.mount(
  10659. "/fonts",
  10660. StaticFiles(directory=app_settings.static_dir / "fonts"),
  10661. name="fonts",
  10662. )
  10663. @app.get("/")
  10664. async def serve_frontend():
  10665. """Serve the React frontend."""
  10666. index_file = app_settings.static_dir / "index.html"
  10667. if index_file.exists():
  10668. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10669. return {
  10670. "message": "Bambuddy API",
  10671. "docs": "/docs",
  10672. "frontend": "Build and place React app in /static directory",
  10673. }
  10674. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  10675. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  10676. # forever, but the HTML wrapping it is the only file that knows which hash
  10677. # is current. Without explicit cache-control headers Chromium decides
  10678. # heuristically (typically 10% of the time since Last-Modified) and on
  10679. # long-running kiosks happily serves stale HTML across browser restarts.
  10680. # That stale HTML references an old bundle hash, the old bundle is also
  10681. # in the disk cache, and the user ends up running pre-update JS forever
  10682. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  10683. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  10684. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  10685. @app.get("/health")
  10686. async def health_check():
  10687. """Health check endpoint."""
  10688. return {"status": "healthy"}
  10689. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  10690. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  10691. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  10692. # in deployment debugging.
  10693. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  10694. async def serve_manifest():
  10695. """Serve PWA manifest."""
  10696. manifest_file = app_settings.static_dir / "manifest.json"
  10697. if manifest_file.exists():
  10698. return FileResponse(manifest_file, media_type="application/manifest+json")
  10699. return {"error": "Manifest not found"}
  10700. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  10701. async def serve_service_worker():
  10702. """Serve service worker."""
  10703. sw_file = app_settings.static_dir / "sw.js"
  10704. if sw_file.exists():
  10705. return FileResponse(
  10706. sw_file,
  10707. media_type="application/javascript",
  10708. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  10709. )
  10710. return {"error": "Service worker not found"}
  10711. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  10712. async def serve_sw_register():
  10713. """Serve the service-worker registration bootstrap script.
  10714. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  10715. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  10716. """
  10717. reg_file = app_settings.static_dir / "sw-register.js"
  10718. if reg_file.exists():
  10719. return FileResponse(reg_file, media_type="application/javascript")
  10720. return {"error": "sw-register.js not found"}
  10721. # ── GCode viewer static files ────────────────────────────────────────────────
  10722. # Catch-all route for React Router (must be last)
  10723. @app.get("/{full_path:path}")
  10724. async def serve_spa(full_path: str):
  10725. """Serve React app for client-side routing."""
  10726. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  10727. if full_path.startswith("api/"):
  10728. from fastapi import HTTPException
  10729. raise HTTPException(status_code=404, detail="Not found")
  10730. index_file = app_settings.static_dir / "index.html"
  10731. if index_file.exists():
  10732. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10733. return {"error": "Frontend not built"}