main.py 560 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570
  1. import asyncio
  2. import json
  3. import logging
  4. import math
  5. import os
  6. import posixpath
  7. import re
  8. import secrets
  9. import time
  10. from contextlib import asynccontextmanager
  11. from datetime import datetime, timedelta, timezone
  12. from logging.handlers import RotatingFileHandler
  13. from pathlib import Path, PurePosixPath
  14. from urllib.parse import urlparse
  15. from fastapi import FastAPI
  16. from fastapi.responses import FileResponse
  17. from fastapi.staticfiles import StaticFiles
  18. from sqlalchemy import delete, inspect as sa_inspect, or_, select, text, update
  19. from sqlalchemy.exc import IntegrityError
  20. from sqlalchemy.orm.exc import StaleDataError
  21. from backend.app.api.routes import (
  22. ams_history,
  23. announcements,
  24. api_keys,
  25. archive_purge,
  26. archives,
  27. auth,
  28. bug_report,
  29. camera,
  30. camwall,
  31. cloud,
  32. connected_apps,
  33. discovery,
  34. external_links,
  35. filaments,
  36. finance,
  37. firmware,
  38. github_backup,
  39. groups,
  40. ha_sensors,
  41. inventory,
  42. kprofiles,
  43. labels,
  44. library,
  45. library_tags,
  46. library_trash,
  47. library_variants,
  48. local_backup,
  49. local_presets,
  50. location_ha_sensors,
  51. maintenance,
  52. makerworld,
  53. manyfold,
  54. metrics,
  55. mfa,
  56. notification_templates,
  57. notifications,
  58. obico,
  59. orca_cloud,
  60. overlay_branding,
  61. pending_uploads,
  62. pipeline_runs,
  63. print_log,
  64. print_queue,
  65. printer_locations,
  66. printer_sensor_history,
  67. printers,
  68. projects,
  69. scheduled_dryings,
  70. settings as settings_routes,
  71. slice_jobs,
  72. slicer_pipelines,
  73. slicer_presets,
  74. smart_plugs,
  75. sponsor_prompt,
  76. spoolbuddy,
  77. spoolman,
  78. spoolman_inventory,
  79. support,
  80. system,
  81. updates,
  82. user_notifications,
  83. users,
  84. virtual_printers,
  85. webhook,
  86. websocket,
  87. )
  88. from backend.app.api.routes.maintenance import (
  89. _get_printer_maintenance_internal,
  90. ensure_default_types,
  91. maintenance_alert_values,
  92. )
  93. from backend.app.api.routes.support import init_debug_logging
  94. from backend.app.core.config import APP_VERSION, settings as app_settings
  95. from backend.app.core.database import async_session, engine, init_db
  96. from backend.app.core.static_assets import AssetStaticFiles
  97. from backend.app.core.tasks import spawn_background_task
  98. from backend.app.core.websocket import ws_manager
  99. from backend.app.services import kprofile_drift, print_dispatch_context, slot_unlink_grace
  100. from backend.app.services.archive import ArchiveService, peek_plate_index_in_3mf, swap_plate_suffix
  101. from backend.app.services.archive_cost_estimate import (
  102. schedule_archive_cost_estimate as _schedule_archive_cost_estimate,
  103. )
  104. from backend.app.services.archive_purge import archive_purge_service
  105. from backend.app.services.bambu_ftp import (
  106. FileNotOnPrinterError,
  107. cache_3mf_download,
  108. clear_3mf_cache,
  109. download_file_async,
  110. download_file_try_paths_async,
  111. ftps_handshake_blocked,
  112. get_cached_3mf,
  113. get_ftp_retry_settings,
  114. normalize_3mf_name,
  115. with_ftp_retry,
  116. )
  117. from backend.app.services.bambu_mqtt import PrinterState
  118. from backend.app.services.camera_light import camera_light
  119. from backend.app.services.energy_plug import energy_plug_candidates, select_energy_reading
  120. from backend.app.services.github_backup import github_backup_service
  121. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  122. from backend.app.services.library_trash import library_trash_service
  123. from backend.app.services.local_backup import local_backup_service
  124. from backend.app.services.location_ha_sensor_manager import location_ha_sensor_manager
  125. from backend.app.services.mqtt_relay import mqtt_relay
  126. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  127. from backend.app.services.notification_service import notification_service
  128. from backend.app.services.notify_live_activities import notify_live_activities
  129. from backend.app.services.notify_widgets import notify_widgets
  130. from backend.app.services.obico_detection import obico_detection_service
  131. from backend.app.services.plug_energy import get_plug_energy as _get_plug_energy
  132. from backend.app.services.print_cost_estimate import plate_scoped_run_estimate as _plate_scoped_run_estimate
  133. from backend.app.services.print_scheduler import scheduler as print_scheduler
  134. from backend.app.services.print_storage import (
  135. REASON_FTP_TRANSFER_FAILED,
  136. REASON_FTPS_COOLOFF,
  137. external_storage_present,
  138. ftp_probe_paths,
  139. print_file_reachable_over_ftp,
  140. )
  141. from backend.app.services.printer_manager import (
  142. init_printer_connections,
  143. parse_plate_id,
  144. printer_manager,
  145. printer_state_to_dict,
  146. resolve_plate_id,
  147. )
  148. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  149. from backend.app.services.slot_nozzle import (
  150. nozzle_diameter_for_extruder,
  151. nozzle_flow_for_extruder,
  152. resolve_slot_nozzle,
  153. )
  154. from backend.app.services.smart_plug_manager import smart_plug_manager
  155. from backend.app.services.spool_assignment_notifications import (
  156. notify_missing_spool_assignments_on_print_start,
  157. )
  158. from backend.app.services.spool_filament_preset import printer_safe_filament_id
  159. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  160. from backend.app.services.spoolman_tracking import (
  161. cleanup_tracking as _cleanup_spoolman_tracking,
  162. release_archived_slot_rows as _release_archived_spoolman_slots,
  163. report_usage as _report_spoolman_usage,
  164. store_print_data as _store_spoolman_print_data,
  165. )
  166. from backend.app.services.telegram_reactions import telegram_reaction_poller
  167. from backend.app.utils.ams_drying import is_drying_active, temperature_alarm_suppressed
  168. from backend.app.utils.ams_humidity import ams_humidity_percent
  169. from backend.app.utils.filament_types import printer_filament_type
  170. from backend.app.utils.fts_routing import extruder_for_inlet
  171. from backend.app.utils.local_time import to_naive_utc, utcnow_naive
  172. from backend.app.utils.print_jobs import is_internal_printer_job
  173. # =============================================================================
  174. # Dependency Check - runs before other imports to give helpful error messages
  175. # =============================================================================
  176. def _start_error_server(missing_packages: list):
  177. """Start a minimal HTTP server to display dependency errors in browser."""
  178. import os
  179. import signal
  180. from http.server import BaseHTTPRequestHandler, HTTPServer
  181. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  182. html = f"""<!DOCTYPE html>
  183. <html>
  184. <head>
  185. <title>Bambuddy - Setup Required</title>
  186. <style>
  187. body {{
  188. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  189. background: #0f172a; color: #e2e8f0;
  190. display: flex; justify-content: center; align-items: center;
  191. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  192. }}
  193. .container {{
  194. background: #1e293b; border-radius: 12px; padding: 40px;
  195. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  196. }}
  197. h1 {{ color: #f87171; margin-bottom: 10px; }}
  198. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  199. .packages {{
  200. background: #0f172a; border-radius: 8px; padding: 20px;
  201. margin: 20px 0; text-align: left;
  202. }}
  203. .packages ul {{ margin: 0; padding-left: 20px; }}
  204. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  205. .command {{
  206. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  207. margin: 15px 0; font-family: monospace; color: #4ade80;
  208. text-align: left; overflow-x: auto;
  209. }}
  210. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  211. </style>
  212. </head>
  213. <body>
  214. <div class="container">
  215. <h1>Setup Required</h1>
  216. <h2>Missing Python packages</h2>
  217. <div class="packages"><ul>{packages_html}</ul></div>
  218. <p>To fix, run this command on your server:</p>
  219. <div class="command">pip install -r requirements.lock</div>
  220. <p>Or if using a virtual environment:</p>
  221. <div class="command">./venv/bin/pip install -r requirements.lock</div>
  222. <p class="note">After installing, restart Bambuddy:<br>
  223. <code>sudo systemctl restart bambuddy</code></p>
  224. </div>
  225. </body>
  226. </html>"""
  227. class ErrorHandler(BaseHTTPRequestHandler):
  228. def do_GET(self):
  229. self.send_response(503)
  230. self.send_header("Content-type", "text/html")
  231. self.end_headers()
  232. self.wfile.write(html.encode())
  233. def log_message(self, format, *args):
  234. print(f"[Error Server] {args[0]}")
  235. port = int(os.environ.get("PORT", 8000))
  236. print(f"\nStarting error server on http://0.0.0.0:{port}")
  237. print("Visit this URL in your browser to see the error details.\n")
  238. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  239. def shutdown(signum, frame):
  240. print("\nShutting down error server...")
  241. raise SystemExit(0)
  242. signal.signal(signal.SIGTERM, shutdown)
  243. signal.signal(signal.SIGINT, shutdown)
  244. server.serve_forever()
  245. def check_dependencies():
  246. """Check that all required packages are installed."""
  247. missing = []
  248. # Map of import name -> package name (for pip install)
  249. required = {
  250. "jwt": "PyJWT",
  251. "fastapi": "fastapi",
  252. "uvicorn": "uvicorn",
  253. "sqlalchemy": "sqlalchemy",
  254. "aiosqlite": "aiosqlite",
  255. "pydantic": "pydantic",
  256. "paho.mqtt": "paho-mqtt",
  257. }
  258. for module, package in required.items():
  259. try:
  260. __import__(module)
  261. except ImportError:
  262. missing.append(package)
  263. if missing:
  264. print("\n" + "=" * 60)
  265. print("ERROR: Missing required Python packages!")
  266. print("=" * 60)
  267. print(f"\nMissing packages: {', '.join(missing)}")
  268. print("\nTo fix, run:")
  269. print(" pip install -r requirements.lock")
  270. print("\nOr if using a virtual environment:")
  271. print(" ./venv/bin/pip install -r requirements.lock")
  272. print("=" * 60 + "\n")
  273. _start_error_server(missing)
  274. check_dependencies()
  275. # =============================================================================
  276. # Import settings first for logging configuration
  277. # Configure logging based on settings
  278. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  279. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  280. log_level = getattr(logging, log_level_str, logging.INFO)
  281. # Trace ID column ([-] when no request scope is active — startup, MQTT
  282. # callbacks, scheduled tasks not chained from a request — so the column
  283. # stays visually aligned and missing values are obvious in grep). See
  284. # backend/app/core/trace.py for the ContextVar that feeds this slot.
  285. log_format = "%(asctime)s %(levelname)s [%(name)s] [%(trace_id)s] %(message)s"
  286. # Create root logger
  287. root_logger = logging.getLogger()
  288. root_logger.setLevel(log_level)
  289. # Trace-ID injection: this filter populates record.trace_id from the
  290. # per-request ContextVar so the format string above can reference it.
  291. # Attached to each HANDLER (not the root logger) because Python's
  292. # logging semantics only invoke a logger's filters on records that
  293. # *originated* at that logger — records propagated up from child
  294. # loggers (every named logger in the app) never trigger root's filter.
  295. # Putting it on the handlers means every record any handler emits gets
  296. # trace_id injected just before the formatter runs, regardless of which
  297. # logger created the record. Without this, the formatter raises
  298. # KeyError on every child-logger record and the record is silently
  299. # dropped — which is exactly the "logs/bambuddy.log only shows logs
  300. # partially" bug we hit. See backend/app/core/trace.py for the
  301. # ContextVar the filter reads.
  302. from backend.app.core.logging_filters import RefusedHeaderRedactFilter
  303. from backend.app.core.response_redaction import RefusedHeaderResponseMask
  304. from backend.app.core.trace import TraceIDFilter
  305. _trace_id_filter = TraceIDFilter()
  306. # Console handler - always enabled
  307. console_handler = logging.StreamHandler()
  308. console_handler.setLevel(log_level)
  309. console_handler.setFormatter(logging.Formatter(log_format))
  310. console_handler.addFilter(_trace_id_filter)
  311. # A refused header's value (often a token) masked before the line is written.
  312. _refused_header_filter = RefusedHeaderRedactFilter()
  313. console_handler.addFilter(_refused_header_filter)
  314. root_logger.addHandler(console_handler)
  315. def _attach_file_handler_to_uvicorn(handler: logging.Handler) -> None:
  316. """Send uvicorn's own loggers to bambuddy.log as well.
  317. Both ship with propagate=False, so the root handler never sees them.
  318. uvicorn.access is the record of which endpoint changed server state;
  319. uvicorn.error is where an unhandled route error is logged with its
  320. traceback ("Exception in ASGI application").
  321. """
  322. for name in ("uvicorn.access", "uvicorn.error"):
  323. logging.getLogger(name).addHandler(handler)
  324. # File handler - only in production or if explicitly enabled
  325. if app_settings.log_to_file:
  326. log_file = app_settings.log_dir / "bambuddy.log"
  327. file_handler = RotatingFileHandler(
  328. log_file,
  329. maxBytes=app_settings.log_max_bytes,
  330. backupCount=app_settings.log_backup_count,
  331. encoding="utf-8",
  332. )
  333. file_handler.setLevel(log_level)
  334. file_handler.setFormatter(logging.Formatter(log_format))
  335. file_handler.addFilter(_trace_id_filter)
  336. file_handler.addFilter(_refused_header_filter)
  337. root_logger.addHandler(file_handler)
  338. logging.info("Logging to file: %s", log_file)
  339. # Pipe uvicorn's HTTP access log to bambuddy.log too. Uvicorn ships its
  340. # access logger with propagate=False by default, so without this attach
  341. # there is no on-disk record of which endpoint triggered a server-state
  342. # change — the rogue stop_print mystery on 2026-04-26 was untraceable
  343. # for exactly this reason. Filtered to write methods only
  344. # (POST/PUT/PATCH/DELETE) so the high-volume status-poll GETs from the
  345. # frontend don't churn the rotation window faster than it's useful.
  346. from backend.app.core.logging_filters import (
  347. CancelledPoolNoiseFilter,
  348. WriteRequestsOnlyFilter,
  349. )
  350. _attach_file_handler_to_uvicorn(file_handler)
  351. uvicorn_access_logger = logging.getLogger("uvicorn.access")
  352. uvicorn_access_logger.addFilter(WriteRequestsOnlyFilter())
  353. # Uvicorn's access logger has propagate=False (its own default), so the
  354. # root-attached TraceIDFilter never sees these records. Attach a
  355. # second instance directly so HTTP access lines carry the same trace
  356. # ID column as the application logs they correlate with.
  357. uvicorn_access_logger.addFilter(TraceIDFilter())
  358. # Drop SQLAlchemy connection-pool log noise that's caused by Starlette's
  359. # BaseHTTPMiddleware cancelling the inner task scope on client
  360. # disconnect (#1112). The cancel-safe `get_db` already prevents the
  361. # underlying transaction leak; this filter only suppresses the residual
  362. # log records that pre-existing pools still emit during their cleanup.
  363. logging.getLogger("sqlalchemy.pool").addFilter(CancelledPoolNoiseFilter())
  364. # Query-string tokens out of uvicorn's request and WebSocket lines, on every
  365. # handler (console included), whether or not file logging is on.
  366. from backend.app.core.logging_filters import QueryTokenRedactFilter # noqa: E402
  367. for _uvicorn_logger in ("uvicorn.access", "uvicorn.error"):
  368. logging.getLogger(_uvicorn_logger).addFilter(QueryTokenRedactFilter())
  369. logging.getLogger(_uvicorn_logger).addFilter(_refused_header_filter)
  370. # These stay at WARNING even in debug mode: at INFO/DEBUG httpx/httpcore log
  371. # full request URLs, and some carry credentials (bot tokens, webhook URLs, API
  372. # keys in the query). Same as the runtime log-level toggle in support.py.
  373. logging.getLogger("httpcore").setLevel(logging.WARNING)
  374. logging.getLogger("httpx").setLevel(logging.WARNING)
  375. # aiosqlite logs every statement with its parameters at DEBUG.
  376. logging.getLogger("aiosqlite").setLevel(logging.WARNING)
  377. # Reduce noise from third-party libraries in production
  378. if not app_settings.debug:
  379. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  380. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  381. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  382. # Track active prints: {(printer_id, filename): archive_id}
  383. _active_prints: dict[tuple[int, str], int] = {}
  384. # #1721: stage-22 pre-captured finish photo bytes per printer. on_finish_photo_moment
  385. # fires when stg_cur enters 22 ("Filament unloading") at end-of-print — toolhead
  386. # parked, bed not yet dropped — and grabs a single camera frame into this cache.
  387. # `_background_finish_photo` (inside on_print_complete) consumes the cached bytes
  388. # instead of running its own grab-now chain when present, so the finish photo
  389. # captures the better-framed pre-bed-drop moment without us having to force
  390. # timelapse on at dispatch (the #1397 mechanism that caused #1721's per-layer
  391. # nozzle parking on slicer profiles with Timelapse Type = Smooth).
  392. #
  393. # #2708: the bytes in here are ALWAYS already rotated by the printer's
  394. # camera_rotation. `on_finish_photo_moment` owns that, because one of its
  395. # sources (the #1867 in-print bank) is rotated before it ever reaches the
  396. # bank and the others are not — so the consumer can't tell them apart and
  397. # must not rotate again.
  398. _stage22_finish_frames: dict[int, bytes] = {}
  399. # #1790: per-printer producer-done event. Set by `on_finish_photo_moment` in its
  400. # `finally` block (whether it captured a frame or not). The consumer in
  401. # `_background_finish_photo` waits on it before reading `_stage22_finish_frames`
  402. # so the FINISH-state fallback path — where moment and completion are dispatched
  403. # back-to-back — doesn't race past the producer with an empty pop, and the
  404. # consumer's RTSP fallback can't collide with the producer's still-in-flight RTSP
  405. # grab (Bambu printers allow only one RTSP client at a time).
  406. _stage22_finish_in_flight: dict[int, asyncio.Event] = {}
  407. # #1867: rolling "last in-print camera frame" per printer. Refreshed on
  408. # layer-change and on print-progress advances (#2547) while the model is still
  409. # printing, then consumed by the FINISH-state finish-photo path when the
  410. # dispatcher recorded that it injected End G-code into this print. Bambu
  411. # reports gcode_state=FINISH AFTER the user End G-code (e.g. SwapMod
  412. # plate-swap) has run, so a live grab there would capture the swapped/empty
  413. # plate.
  414. #
  415. # The load-bearing property: both drivers are print telemetry that stops before
  416. # the End G-code executes — no further layer_num increases, and mc_percent
  417. # freezes — so the last banked frame is always the finished print before the
  418. # swap. Anything added as a third driver must hold that same property.
  419. _inprint_frame_bank: dict[int, bytes] = {}
  420. # Monotonic timestamp of the last banked frame per printer — throttles banking
  421. # so tall prints don't add a camera grab on every layer.
  422. _inprint_frame_bank_ts: dict[int, float] = {}
  423. # Minimum seconds between banked frames, except the final object layer which
  424. # always refreshes for the best framing.
  425. _INPRINT_BANK_MIN_INTERVAL = 25.0
  426. # Per-printer "connected" edge tracker. Used by `on_printer_status_change`
  427. # to fire `reconcile_stale_active_prints` exactly once per (re)connection
  428. # (#1542 follow-up — power-cycle ghost prints). The value is True after
  429. # the first connected status update for that connection; transitions back
  430. # to False whenever we observe `state.connected = False` so the next
  431. # reconnect re-arms reconciliation. Keyed by printer_id.
  432. _printer_reconciled_since_connect: dict[int, bool] = {}
  433. # Same edge, same keying, for priming the printer's calibration table exactly
  434. # once per (re)connection. Nothing else asks for it on connect: state.kprofiles
  435. # is otherwise filled only when someone opens the Profiles page or Configure
  436. # Slot, when a GitHub backup runs, or when the printer happens to answer
  437. # somebody else's query on the report topic. Until then the AMS slot card has
  438. # no K value to show on the printers whose trays carry none of their own
  439. # (#2854 — H2-series report cali_idx and nothing more).
  440. _printer_kprofiles_primed_since_connect: dict[int, bool] = {}
  441. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  442. # {(printer_id, filename): archive_id}
  443. _expected_prints: dict[tuple[int, str], int] = {}
  444. # Track AMS mapping for prints: {archive_id: [global_tray_id_per_slot]}
  445. # Used by usage tracker to map 3MF slots to physical AMS trays
  446. _print_ams_mappings: dict[int, list[int]] = {}
  447. # Track cost center selection for the current print run: {archive_id: cost_center_id}
  448. _print_cost_center_ids: dict[int, int] = {}
  449. # Track plate_id for prints from multi-plate 3MFs: {archive_id: plate_id}
  450. # Used by usage tracker to scope 3MF parsing to the dispatched plate (#1697).
  451. # Populated by direct-Print and queue dispatch paths; queue prints also have a
  452. # redundant queue-item lookup in on_print_start so this dict isn't load-bearing
  453. # for the queue path. Cleared on print completion or TTL eviction.
  454. _print_plate_ids: dict[int, int] = {}
  455. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  456. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  457. _last_progress_milestone: dict[int, int] = {}
  458. # Track whether first layer complete notification has been sent for current print
  459. _first_layer_notified: dict[int, bool] = {}
  460. # Track whether we already sent a kill-switch stop for the current unauthorized print
  461. _unauthorized_print_kill_sent: set[int] = set()
  462. # The MQTT status callback is a hot path. Cache the two-setting kill-switch
  463. # lookup briefly so an unknown active print does not query the database on
  464. # every status frame. A short TTL keeps settings changes responsive.
  465. _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS = 5.0
  466. _kill_switch_setting_cache: tuple[bool, float] | None = None
  467. # Provider notification started when the kill switch stops a print. The later
  468. # MQTT print-complete callback awaits this task and only sends its regular
  469. # provider notification when the immediate attempt failed.
  470. _kill_switch_notification_tasks: dict[int, asyncio.Task[bool]] = {}
  471. # HMS faults already notified, with when each was last seen:
  472. # {printer_id: {fault key: timestamp}}. Tracked per fault, not per printer: a
  473. # fault that flickers beside a held notice was forgotten on every gap and
  474. # notified on every return (#3226). The window is long because the measured
  475. # gaps reach 64 s.
  476. _notified_hms_errors: dict[int, dict[str, float]] = {}
  477. _HMS_CLEAR_GRACE_SECONDS = 600.0
  478. # The print state each printer was last seen in, and the faults recorded before
  479. # it last changed, which are forgotten as soon as they are gone (see
  480. # _take_new_hms_faults).
  481. _hms_print_state: dict[int, str] = {}
  482. _hms_forget_when_gone: dict[int, set[str]] = {}
  483. # Track timelapse file baselines at print start: {printer_id: set of video filenames}
  484. # Used for snapshot-diff detection at print completion
  485. _timelapse_baselines: dict[int, set[str]] = {}
  486. # Track printers waiting for bed to cool after print completion.
  487. # Event-driven: fires when bed_temper arrives via MQTT below threshold.
  488. # {printer_id: {"threshold": float, "filename": str, "registered_at": float}}
  489. _bed_cool_waiters: dict[int, dict] = {}
  490. # Track printers where the user explicitly stopped the print from the queue UI.
  491. # When on_print_complete fires with status "failed" for these printers we treat it
  492. # as "cancelled" (stopped by user) so the correct notification email is sent.
  493. _user_stopped_printers: set[int] = set()
  494. # Offline-notification edge state (#1752): fire `on_printer_offline` exactly
  495. # once when a printer transitions connected → disconnected. `_printer_last_connected`
  496. # holds the previous observation so we only fire on the True → False edge (a
  497. # False → False repeat doesn't notify; an initial False at startup doesn't
  498. # notify either, since there's no prior True). `_printer_offline_notify_tasks`
  499. # holds the per-printer pending asyncio task that fires the notification
  500. # after a debounce window — cancelled if the printer reconnects before the
  501. # window elapses, so transient MQTT blips don't flood the user.
  502. _printer_last_connected: dict[int, bool] = {}
  503. # Printers whose relay offline event went out, so the reconnect publishes the
  504. # matching online event and a blip shorter than the debounce publishes neither.
  505. _printer_offline_published: set[int] = set()
  506. _printer_offline_notify_tasks: dict[int, asyncio.Task] = {}
  507. # Debounce: a printer must stay offline this long before we notify. Sized
  508. # against the staleness path (`bambu_mqtt.py::STALE_RECONNECT_COOLDOWN = 30s`)
  509. # so a single stale-trigger cooldown isn't enough to fire — only a real
  510. # offline that survives one reconnect attempt notifies.
  511. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS = 60.0
  512. # HMS short-code → failure_reason key. Used by _dispatch_archive_update
  513. # when status="failed" to label the print's failure_reason in archives.
  514. #
  515. # Earlier code matched on `module` alone (e.g. "any module 0x0C HMS → Layer shift"),
  516. # which is wrong on two counts:
  517. # 1. Real layer-shift codes live in module 0x03 (see Bambu wiki), not 0x0C.
  518. # 2. Module 0x0C is "Motion Controller" — broad category that also covers cameras
  519. # and visual markers, AND the H2D firmware emits a 0x0C HMS (0C00_001B, not in
  520. # the public wiki) as part of its user-cancel sequence. Matching on the module
  521. # alone caused user-cancellations to be archived as "Layer shift" failures.
  522. # We now match by full short code only — anything not in this map leaves
  523. # failure_reason=None rather than guessing.
  524. # Values are the canonical camelCase failure-reason keys, NOT display labels
  525. # (issue #2974). The vocabulary is enforced on writes by
  526. # ``_FAILURE_REASON_KEYS`` in ``api/routes/print_log.py`` and rendered through
  527. # ``t('editArchive.failureReasons.<key>')`` on both the archive editor and the
  528. # Statistics breakdown. Storing a label here instead put a second spelling of
  529. # the same cause into one column: the Failure Analysis widget groups on the raw
  530. # value, so a print the backend classified and an identical one a user
  531. # classified counted as two different reasons, and the label form could never
  532. # be translated because there was no key for ``t()`` to resolve.
  533. _HMS_FAILURE_REASONS: dict[str, str] = {
  534. # Layer shift / step loss
  535. "0300_4057": "layerShift",
  536. "0300_4068": "layerShift",
  537. "0300_800C": "layerShift",
  538. # Filament runout (printer-side & per-AMS-slot)
  539. "0300_8004": "filamentRunout",
  540. "0700_8011": "filamentRunout",
  541. "0701_8011": "filamentRunout",
  542. "0702_8011": "filamentRunout",
  543. "0703_8011": "filamentRunout",
  544. "0704_8011": "filamentRunout",
  545. "0705_8011": "filamentRunout",
  546. "0706_8011": "filamentRunout",
  547. "0707_8011": "filamentRunout",
  548. "07FF_8011": "filamentRunout",
  549. # Clogged nozzle / extruder
  550. "0300_4006": "cloggedNozzle",
  551. "0300_8016": "cloggedNozzle",
  552. "0300_801C": "cloggedNozzle",
  553. "0700_8003": "cloggedNozzle",
  554. "0700_8007": "cloggedNozzle",
  555. "0700_8013": "cloggedNozzle",
  556. "0701_8003": "cloggedNozzle",
  557. "0701_8007": "cloggedNozzle",
  558. "0701_8013": "cloggedNozzle",
  559. "0702_8003": "cloggedNozzle",
  560. # AI print monitoring — spaghetti / the model coming off the plate.
  561. # `spaghettiDetached` is a key the archive editor already offers for this
  562. # failure mode, not a new one, so a derived reason opens the dropdown on
  563. # that option rather than blank — and survives the next save, which clears
  564. # any value the editor does not recognise.
  565. #
  566. # A module-0x0C row is safe here despite the warning above: that warning is
  567. # about matching on the module alone, and 0C00_8042 is a full short code
  568. # with a documented meaning ("The AI print monitor has detected a spaghetti
  569. # defect", hms_errors.py). The H2D cancel echo is 0C00_001B, so the two
  570. # cannot collide.
  571. #
  572. # 0300_8003's own text ends "before continuing your print", but on an X2D
  573. # it arrives with the print already paused, offering only
  574. # RESUME_PRINTING_DEFECTS / STOP_PRINTING — a halt waiting on the user.
  575. #
  576. # Two neighbours are left out on purpose, so this does not get re-derived:
  577. # * 0C00_C004 "Possible spaghetti failure was detected." — "possible"
  578. # reads as a warning about a print that is still running, not a halt.
  579. # * 0300_800A is AI monitoring too, but it reports a filament pile-up in
  580. # the waste chute. That is not the print failing.
  581. #
  582. # That line is drawn from the text, not from `severity`, because severity
  583. # cannot draw it: 0300_8003 reaches us through `print_error`, a bare
  584. # module/error word with no level in it, and bambu_mqtt.py gives every
  585. # print_error entry a flat severity=3. Matching on the short code alone is
  586. # the right shape for derive_failure_reason, not an omission.
  587. "0300_8003": "spaghettiDetached",
  588. "0C00_8042": "spaghettiDetached",
  589. }
  590. def _hms_short_code(attr: int, code: int | str) -> str:
  591. """Build the canonical "MMMM_CCCC" HMS short code from raw attr/code values."""
  592. if isinstance(code, str):
  593. code_int = int(code.replace("0x", ""), 16) if code else 0
  594. else:
  595. code_int = int(code or 0)
  596. attr_int = int(attr or 0)
  597. return f"{(attr_int >> 16) & 0xFFFF:04X}_{code_int & 0xFFFF:04X}"
  598. def derive_failure_reason(status: str, hms_errors: list[dict] | None) -> str | None:
  599. """Derive the failure_reason key for an archived print.
  600. Returns "userCancelled" for cancelled/aborted prints; for failed prints,
  601. returns the first matching key from _HMS_FAILURE_REASONS, or None when
  602. no HMS code matches (don't guess — null is honest). The keys are the
  603. archive editor's vocabulary (_FAILURE_REASON_KEYS in print_log.py) and are
  604. translated at render time.
  605. """
  606. if status in ("aborted", "cancelled"):
  607. return "userCancelled"
  608. if status != "failed":
  609. return None
  610. for err in hms_errors or []:
  611. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  612. if short_code in _HMS_FAILURE_REASONS:
  613. return _HMS_FAILURE_REASONS[short_code]
  614. return None
  615. # Track created_by_id for expected prints so the user email can be sent even when
  616. # the archive itself doesn't have created_by_id set (e.g. library-file-based prints).
  617. # {(printer_id, filename): created_by_id}
  618. _expected_print_creators: dict[tuple[int, str], int] = {}
  619. # Per-printer lock that serialises the spool-assignment side of on_ams_change
  620. # (auto-unlink stale + auto-assign new) when MQTT bursts deliver multiple AMS
  621. # updates for the same printer in quick succession (~30 ms apart, observed in
  622. # the wild on H2D + dual AMS).
  623. #
  624. # Without this serialisation, two concurrent on_ams_change callbacks each read
  625. # "no assignment for (printer, ams, tray)", each call auto_assign_spool, and
  626. # the second commit hits
  627. # IntegrityError: duplicate key value violates unique constraint
  628. # "spool_assignment_printer_id_ams_id_tray_id_key"
  629. # SQLite's WAL serial-write semantics had been silently swallowing the race
  630. # until optional Postgres support landed (asyncpg allows true concurrent
  631. # transactions and surfaces the constraint violation).
  632. #
  633. # Scope is intentionally narrow: only the two DB-mutating blocks (unlink +
  634. # assign) are inside the lock. The Spoolman sync block further down stays
  635. # concurrent because it's network-bound and idempotent.
  636. _ams_assignment_locks: dict[int, asyncio.Lock] = {}
  637. def _get_ams_assignment_lock(printer_id: int) -> asyncio.Lock:
  638. """Return the per-printer assignment lock, creating it on first use."""
  639. lock = _ams_assignment_locks.get(printer_id)
  640. if lock is None:
  641. lock = asyncio.Lock()
  642. _ams_assignment_locks[printer_id] = lock
  643. return lock
  644. # Per-printer dedup for unknown_tag WS broadcasts. Keyed by
  645. # (ams_id, tray_id) -> (tag_uid, tray_uuid); we only re-broadcast when the
  646. # tag tuple changes for the slot. Cleared when the slot is reported empty
  647. # so remove + reinsert reliably re-prompts the UI.
  648. _unknown_tag_last_broadcast: dict[int, dict[tuple[int, int], tuple[str, str]]] = {}
  649. async def _broadcast_unknown_tag(
  650. *,
  651. printer_id: int,
  652. ams_id: int,
  653. tray_id: int,
  654. tag_uid: str,
  655. tray_uuid: str,
  656. tray_type: str | None = None,
  657. tray_color: str | None = None,
  658. tray_sub_brands: str | None = None,
  659. tray_count: int | None = None,
  660. ) -> None:
  661. """Broadcast unknown_tag, deduped so repeated MQTT pushes for the same slot+tag don't spam the UI."""
  662. _logger = logging.getLogger(__name__)
  663. slot_key = (ams_id, tray_id)
  664. tag_key = (tag_uid or "", tray_uuid or "")
  665. per_printer = _unknown_tag_last_broadcast.setdefault(printer_id, {})
  666. if per_printer.get(slot_key) == tag_key:
  667. _logger.debug(
  668. "unknown_tag deduped for printer=%d AMS=%d slot=%d tag=%s",
  669. printer_id,
  670. ams_id,
  671. tray_id,
  672. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  673. )
  674. return
  675. _logger.info(
  676. "unknown_tag broadcast: printer=%d AMS=%d slot=%d type=%r color=%r tag=%s",
  677. printer_id,
  678. ams_id,
  679. tray_id,
  680. tray_type,
  681. tray_color,
  682. tag_key[0][:8] or tag_key[1][:8] or "(none)",
  683. )
  684. # Broadcast first; only commit the dedup if the WS write succeeds.
  685. # If broadcast raises, the next MQTT push retries instead of being
  686. # permanently silenced by a poisoned dedup entry.
  687. await ws_manager.broadcast(
  688. {
  689. "type": "unknown_tag",
  690. "printer_id": printer_id,
  691. "ams_id": ams_id,
  692. "tray_id": tray_id,
  693. "tag_uid": tag_uid,
  694. "tray_uuid": tray_uuid,
  695. "tray_type": tray_type,
  696. "tray_color": tray_color,
  697. "tray_sub_brands": tray_sub_brands,
  698. "tray_count": tray_count,
  699. }
  700. )
  701. per_printer[slot_key] = tag_key
  702. def _clear_unknown_tag_dedup(printer_id: int, ams_id: int, tray_id: int) -> None:
  703. """Drop the cached last-broadcast tag for a slot (called when slot reports empty or gets matched)."""
  704. per_printer = _unknown_tag_last_broadcast.get(printer_id)
  705. if per_printer is None:
  706. return
  707. per_printer.pop((ams_id, tray_id), None)
  708. # TTL for expected-print entries: evict registrations older than this to prevent
  709. # unbounded growth when a print is registered but never starts (e.g. printer
  710. # disconnect, app restart, print started from the printer panel).
  711. _EXPECTED_PRINT_TTL_SECONDS: int = 2 * 60 * 60 # 2 hours
  712. # Registration timestamps used for TTL eviction: {(printer_id, filename): monotonic_time}
  713. _expected_print_registered_at: dict[tuple[int, str], float] = {}
  714. # Cleanup loop interval
  715. _EXPECTED_PRINT_CLEANUP_INTERVAL: int = 15 * 60 # 15 minutes
  716. _expected_prints_cleanup_task: asyncio.Task | None = None
  717. _ACTIVE_PRINT_STATES: set[str] = {"RUNNING", "PRINTING", "PAUSE"}
  718. def _build_status_print_keys(printer_id: int, state: PrinterState) -> list[tuple[int, str]]:
  719. """Build filename keys for matching a printer status update to Bambuddy-owned jobs."""
  720. possible_keys: list[tuple[int, str]] = []
  721. filename = (state.gcode_file or state.current_print or "").strip()
  722. subtask_name = (state.subtask_name or "").strip()
  723. if subtask_name:
  724. possible_keys.append((printer_id, subtask_name))
  725. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  726. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  727. if filename:
  728. base_name = filename.rsplit("/", 1)[-1]
  729. if base_name.endswith(".gcode.3mf"):
  730. root_name = base_name[: -len(".gcode.3mf")]
  731. possible_keys.append((printer_id, root_name))
  732. possible_keys.append((printer_id, base_name))
  733. possible_keys.append((printer_id, f"{root_name}.gcode"))
  734. possible_keys.append((printer_id, f"{root_name}.3mf"))
  735. elif base_name.endswith(".3mf"):
  736. root_name = base_name[: -len(".3mf")]
  737. possible_keys.append((printer_id, root_name))
  738. possible_keys.append((printer_id, base_name))
  739. elif base_name.endswith(".gcode"):
  740. root_name = base_name[: -len(".gcode")]
  741. possible_keys.append((printer_id, root_name))
  742. possible_keys.append((printer_id, f"{root_name}.3mf"))
  743. possible_keys.append((printer_id, base_name))
  744. else:
  745. possible_keys.append((printer_id, base_name))
  746. possible_keys.append((printer_id, f"{base_name}.3mf"))
  747. return possible_keys
  748. async def _print_user_id_if_still_there(db, print_user: dict | None) -> int | None:
  749. """The id of who started the print, unless that user has been deleted since.
  750. Deleting a user forgets them in printer_manager, but a print that ended a
  751. moment before still holds them.
  752. """
  753. if not print_user or print_user.get("user_id") is None:
  754. return None
  755. from backend.app.models.user import User
  756. return await db.scalar(select(User.id).where(User.id == print_user["user_id"]))
  757. def _is_bambuddy_authorized_print_in_memory(printer_id: int, state: PrinterState) -> bool:
  758. """Check the cheap, process-local print ownership signals."""
  759. if printer_manager.get_current_print_user(printer_id):
  760. return True
  761. return any(key in _expected_prints or key in _active_prints for key in _build_status_print_keys(printer_id, state))
  762. async def _is_printer_kill_switch_enabled_cached() -> bool:
  763. """Return the kill-switch setting without querying on every MQTT frame."""
  764. global _kill_switch_setting_cache
  765. now = time.monotonic()
  766. if _kill_switch_setting_cache is not None:
  767. enabled, expires_at = _kill_switch_setting_cache
  768. if now < expires_at:
  769. return enabled
  770. async with async_session() as db:
  771. from backend.app.services.finance_budget import is_printer_kill_switch_enabled
  772. enabled = await is_printer_kill_switch_enabled(db)
  773. _kill_switch_setting_cache = (enabled, now + _KILL_SWITCH_SETTING_CACHE_TTL_SECONDS)
  774. return enabled
  775. async def _is_bambuddy_authorized_print(printer_id: int, state: PrinterState, db) -> bool | None:
  776. """Resolve whether the current print was started by Bambuddy.
  777. ``None`` means identity is not yet safe to decide. The kill switch must
  778. defer in that case: stopping a print is irreversible, and the first status
  779. frames after a restart may arrive before all subtask fields are populated.
  780. """
  781. if _is_bambuddy_authorized_print_in_memory(printer_id, state):
  782. return True
  783. possible_keys = _build_status_print_keys(printer_id, state)
  784. # In-memory ownership is lost on every Bambuddy restart, so fall back to what
  785. # is on disk. subtask_id is minted per print and pins the answer to the job
  786. # actually running, rather than to an unrelated one that reuses a filename.
  787. raw_subtask_id = getattr(state, "subtask_id", None)
  788. subtask_id = str(raw_subtask_id).strip() if raw_subtask_id is not None else ""
  789. if subtask_id in ("", "0"):
  790. return None
  791. from backend.app.models.archive import PrintArchive
  792. result = await db.execute(
  793. select(PrintArchive)
  794. .where(
  795. PrintArchive.printer_id == printer_id,
  796. PrintArchive.status == "printing",
  797. PrintArchive.subtask_id == subtask_id,
  798. )
  799. .order_by(PrintArchive.created_at.desc())
  800. .limit(1)
  801. )
  802. archive = result.scalar_one_or_none()
  803. # An archive row on its own proves nothing: `on_print_start` archives every
  804. # print it observes, including ones started from Bambu Studio or Handy, and
  805. # stamps them with the same status and subtask_id. Authorizing on its mere
  806. # existence would disable the kill switch the moment the 3MF finishes
  807. # downloading. Only a dispatch marker Bambuddy writes itself counts —
  808. # `billing_run_id` (minted per dispatch in the scheduler) or `created_by_id`
  809. # (carried over from the queue item that started it).
  810. if archive is not None and (archive.billing_run_id is not None or archive.created_by_id is not None):
  811. # Rehydrate the fast in-memory path for subsequent status frames. Include
  812. # both the archive filename and every normalized key reported by MQTT.
  813. _active_prints[(printer_id, archive.filename)] = archive.id
  814. for key in possible_keys:
  815. _active_prints[key] = archive.id
  816. return True
  817. # No dispatch marker. Before calling this someone else's print, check whether
  818. # Bambuddy has a job of its own running on this printer: a library-file
  819. # dispatch has no archive at send time, and an archive created seconds later
  820. # by `on_print_start` carries neither marker. The queue row, which the
  821. # scheduler commits to status="printing" before the MQTT send, is the one
  822. # durable record every Bambuddy print has. It cannot be tied to this
  823. # subtask_id, so it is grounds to defer, never to authorize — stopping a
  824. # print is irreversible, and refusing to act costs nothing but a log line.
  825. from backend.app.models.print_queue import PrintQueueItem
  826. dispatched_here = await db.scalar(
  827. select(PrintQueueItem.id)
  828. .where(
  829. PrintQueueItem.printer_id == printer_id,
  830. PrintQueueItem.status == "printing",
  831. )
  832. .limit(1)
  833. )
  834. if dispatched_here is not None:
  835. return None
  836. return False
  837. async def _send_kill_switch_provider_notification(
  838. printer_id: int,
  839. printer_name: str,
  840. data: dict,
  841. ) -> bool:
  842. """Send the immediate print-stopped provider notification.
  843. Returning a success flag lets the normal MQTT completion path retry when
  844. this early notification could not be delivered.
  845. """
  846. logger = logging.getLogger(__name__)
  847. try:
  848. async with async_session() as db:
  849. await notification_service.on_print_complete(
  850. printer_id,
  851. printer_name,
  852. "stopped",
  853. data,
  854. db,
  855. )
  856. return True
  857. except Exception as e:
  858. logger.warning(
  859. "[KILL SWITCH] Immediate provider notification failed for printer %s: %s",
  860. printer_id,
  861. e,
  862. )
  863. return False
  864. async def _kill_switch_notification_already_sent(task: asyncio.Task[bool] | None) -> bool:
  865. """Wait for an immediate kill-switch notification, if one was scheduled."""
  866. if task is None:
  867. return False
  868. try:
  869. return await task
  870. except Exception as e:
  871. logging.getLogger(__name__).warning("[KILL SWITCH] Notification task failed: %s", e)
  872. return False
  873. async def _record_energy_start(archive, printer_id: int, db, *, context: str = "") -> bool:
  874. """Capture the smart plug lifetime counter on the archive at print start.
  875. Persists `energy_start_kwh` on the archive row (#941) so per-print energy
  876. tracking survives a backend restart mid-print. The print-end handler reads
  877. this value back from the DB and computes the delta against the current
  878. plug counter.
  879. """
  880. _logger = logging.getLogger(__name__)
  881. try:
  882. candidates = await energy_plug_candidates(db, printer_id)
  883. if not candidates:
  884. _logger.info("[ENERGY] No smart plug for printer %s (archive %s)", printer_id, archive.id)
  885. return False
  886. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  887. if selected is None:
  888. # Naming the plugs matters here: with several linked to one printer
  889. # this is the difference between "the meter is offline" and "you
  890. # linked only accessories" (#2859).
  891. _logger.warning(
  892. "[ENERGY] No plug on printer %s reports a lifetime energy counter for archive %s (tried: %s)",
  893. printer_id,
  894. archive.id,
  895. ", ".join(plug.name for plug in candidates),
  896. )
  897. return False
  898. plug, energy = selected
  899. archive.energy_start_kwh = float(energy["total"])
  900. # With the plug's snapshots, what lets the cost follow the price over
  901. # the print rather than take the price at its end (#1251). A price that
  902. # can't be had must not cost the print its energy reading.
  903. archive.energy_start_at = utcnow_naive()
  904. archive.energy_start_plug_id = plug.id
  905. try:
  906. from backend.app.services.energy_price import current_price
  907. archive.energy_start_price = await current_price(db)
  908. except Exception as e:
  909. _logger.warning("[ENERGY] Could not read the electricity price for archive %s: %s", archive.id, e)
  910. archive.energy_start_price = None
  911. await db.commit()
  912. _logger.info(
  913. "[ENERGY] Recorded starting energy%s for archive %s from plug '%s': %s kWh",
  914. f" ({context})" if context else "",
  915. archive.id,
  916. plug.name,
  917. energy["total"],
  918. )
  919. return True
  920. except Exception as e:
  921. _logger.warning("[ENERGY] Failed to record starting energy for archive %s: %s", archive.id, e)
  922. return False
  923. def forget_print_creator(user_id: int) -> None:
  924. """The print-start emails of a deleted user's jobs go to nobody, not to
  925. whoever is given the id next (SQLite reuses it)."""
  926. for key in [key for key, creator in _expected_print_creators.items() if creator == user_id]:
  927. del _expected_print_creators[key]
  928. async def forget_printer(printer_id: int) -> None:
  929. """Drop what is kept for a deleted printer's id, here and in the services.
  930. SQLite used to give the id to the next printer created, which inherited it
  931. all: the running print's owner (its prints passed the kill switch and were
  932. billed to that user), the plate-clear gate, pending and suppressed
  933. notifications, the camera feed, the plate references. Ids are no longer
  934. reused (AUTOINCREMENT), but nothing kept for a printer that is gone should
  935. stay. Called after the delete is committed, and again by work that was in
  936. flight and wrote state back.
  937. Every printer-keyed map of this module is listed here or, with the reason,
  938. in tests/unit/test_forget_printer.py.
  939. """
  940. from backend.app.api.routes import camera
  941. from backend.app.services import (
  942. bambu_ftp,
  943. kprofile_drift,
  944. layer_timelapse,
  945. plate_detection,
  946. print_dispatch_context,
  947. usage_tracker,
  948. )
  949. from backend.app.services.notify_live_activities import notify_live_activities
  950. from backend.app.services.obico_detection import obico_detection_service
  951. # Keyed (printer_id, filename). The archive-keyed maps of those prints go too.
  952. archive_ids = set()
  953. for tracked in (_active_prints, _expected_prints):
  954. for key in [key for key in tracked if key[0] == printer_id]:
  955. archive_ids.add(tracked.pop(key))
  956. for archive_id in archive_ids:
  957. _print_ams_mappings.pop(archive_id, None)
  958. _print_cost_center_ids.pop(archive_id, None)
  959. _print_plate_ids.pop(archive_id, None)
  960. for tracked in (_expected_print_creators, _expected_print_registered_at):
  961. for key in [key for key in tracked if key[0] == printer_id]:
  962. del tracked[key]
  963. for key in [key for key in _ams_index_only_logged if key[0] == printer_id]:
  964. _ams_index_only_logged.discard(key)
  965. for key in [key for key in _ams_alarm_cooldown if key.split(":", 1)[0] == str(printer_id)]:
  966. del _ams_alarm_cooldown[key]
  967. # Pending work that would act on the id: an offline notice, a 3MF retry.
  968. # A kill-switch notice is about a stop that happened and is left to finish.
  969. for tasks in (_printer_offline_notify_tasks, _fallback_3mf_retry_tasks):
  970. task = tasks.pop(printer_id, None)
  971. if task is not None:
  972. task.cancel()
  973. for keyed in (
  974. _stage22_finish_frames,
  975. _stage22_finish_in_flight,
  976. _inprint_frame_bank,
  977. _inprint_frame_bank_ts,
  978. _printer_reconciled_since_connect,
  979. _printer_kprofiles_primed_since_connect,
  980. _last_progress_milestone,
  981. _first_layer_notified,
  982. _kill_switch_notification_tasks,
  983. _notified_hms_errors,
  984. _hms_print_state,
  985. _hms_forget_when_gone,
  986. _timelapse_baselines,
  987. _bed_cool_waiters,
  988. _printer_last_connected,
  989. _unknown_tag_last_broadcast,
  990. _last_status_broadcast,
  991. _connection_watchdog_last_attempt,
  992. ):
  993. keyed.pop(printer_id, None)
  994. for marked in (
  995. _unauthorized_print_kill_sent,
  996. _user_stopped_printers,
  997. _printer_offline_published,
  998. _nozzle_count_updated,
  999. ):
  1000. marked.discard(printer_id)
  1001. printer_manager.forget_printer(printer_id)
  1002. print_dispatch_context.clear(printer_id)
  1003. kprofile_drift.forget_printer(printer_id, deleted=True)
  1004. layer_timelapse.cancel_session(printer_id)
  1005. usage_tracker.forget_printer(printer_id)
  1006. obico_detection_service.forget_printer(printer_id)
  1007. bambu_ftp.clear_3mf_cache(printer_id)
  1008. await camera.forget_printer(printer_id)
  1009. printers.clear_cover_cache(printer_id)
  1010. print_scheduler.forget_printer(printer_id)
  1011. notify_live_activities.forget_printer(printer_id)
  1012. plate_detection.remove_printer_references(printer_id)
  1013. def register_expected_print(
  1014. printer_id: int,
  1015. filename: str,
  1016. archive_id: int,
  1017. ams_mapping: list[int] | None = None,
  1018. created_by_id: int | None = None,
  1019. cost_center_id: int | None = None,
  1020. plate_id: int | None = None,
  1021. ):
  1022. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  1023. # Store with multiple filename variations to catch different naming patterns
  1024. _expected_prints[(printer_id, filename)] = archive_id
  1025. # Also store without .3mf extension if present
  1026. if filename.endswith(".3mf"):
  1027. base = filename[:-4]
  1028. _expected_prints[(printer_id, base)] = archive_id
  1029. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  1030. # Store AMS mapping for usage tracking at print completion
  1031. if ams_mapping is not None:
  1032. _print_ams_mappings[archive_id] = ams_mapping
  1033. if cost_center_id is not None:
  1034. _print_cost_center_ids[archive_id] = cost_center_id
  1035. # Store plate_id for usage tracking when this is a single-plate dispatch from
  1036. # a multi-plate 3MF — without this, the direct-Print path attributes the whole
  1037. # file's filament total to the spool instead of just the printed plate (#1697).
  1038. if plate_id is not None:
  1039. _print_plate_ids[archive_id] = plate_id
  1040. # Store created_by_id so the user start email can be sent even when the archive
  1041. # itself has no created_by_id (e.g. library-file-based queue prints)
  1042. if created_by_id is not None:
  1043. _expected_print_creators[(printer_id, filename)] = created_by_id
  1044. if filename.endswith(".3mf"):
  1045. base = filename[:-4]
  1046. _expected_print_creators[(printer_id, base)] = created_by_id
  1047. _expected_print_creators[(printer_id, f"{base}.gcode")] = created_by_id
  1048. # Record registration time for TTL-based eviction
  1049. _registered_at = time.monotonic()
  1050. _expected_print_registered_at[(printer_id, filename)] = _registered_at
  1051. if filename.endswith(".3mf"):
  1052. base = filename[:-4]
  1053. _expected_print_registered_at[(printer_id, base)] = _registered_at
  1054. _expected_print_registered_at[(printer_id, f"{base}.gcode")] = _registered_at
  1055. logging.getLogger(__name__).info(
  1056. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}, ams_mapping={ams_mapping}, plate_id={plate_id}"
  1057. )
  1058. def unregister_expected_print(printer_id: int, filename: str, archive_id: int) -> None:
  1059. """Undo :func:`register_expected_print` when the print never went out.
  1060. Registration has to happen *before* the MQTT print command, because the
  1061. printer can report the print before the line after the send executes. So
  1062. every path that registers and then fails to send — a cancel winning the
  1063. #1853 CAS race, a ``start_print()`` that returns False, or any exception in
  1064. between — leaves an expectation for a print that will never arrive.
  1065. The TTL sweep evicts those after two hours, which is far longer than it
  1066. takes a user to react to a failed dispatch by pressing print again: that
  1067. reprint would be folded into the *old* archive and take the stale
  1068. ``ams_mapping`` / ``plate_id`` with it. Hence the explicit inverse.
  1069. Mirrors the sweep's rules, including the one that is easy to get wrong:
  1070. ``_print_ams_mappings`` / ``_print_plate_ids`` / ``_print_cost_center_ids``
  1071. are keyed by archive, not by file, so they may only be dropped once no
  1072. live key still points at that archive.
  1073. """
  1074. keys = [(printer_id, filename)]
  1075. if filename.endswith(".3mf"):
  1076. base = filename[:-4]
  1077. keys.append((printer_id, base))
  1078. keys.append((printer_id, f"{base}.gcode"))
  1079. removed = False
  1080. for key in keys:
  1081. if _expected_prints.pop(key, None) is not None:
  1082. removed = True
  1083. _expected_print_creators.pop(key, None)
  1084. _expected_print_registered_at.pop(key, None)
  1085. if archive_id not in set(_expected_prints.values()):
  1086. _print_ams_mappings.pop(archive_id, None)
  1087. _print_cost_center_ids.pop(archive_id, None)
  1088. _print_plate_ids.pop(archive_id, None)
  1089. if removed:
  1090. logging.getLogger(__name__).info(
  1091. "Unregistered expected print: printer=%s, file=%s, archive=%s (print was never sent)",
  1092. printer_id,
  1093. filename,
  1094. archive_id,
  1095. )
  1096. def _compute_run_filament_grams(
  1097. status: str,
  1098. archive_filament_used_grams: float | None,
  1099. progress: float | int | None,
  1100. usage_results: list[dict] | None,
  1101. ) -> float | None:
  1102. """Per-run filament for PrintLogEntry, partial- and tracker-aware (#1378, #1390).
  1103. Priority for every status:
  1104. 1. Sum of tracked spool deltas in ``usage_results`` (AMS-measured
  1105. weight delta — same source that drives "Total Consumed" on the
  1106. Inventory page, so Stats and Inventory totals stay aligned).
  1107. 2. For ``completed``: the slicer estimate (no tracker available, fall
  1108. back to the canonical "this print used X" value).
  1109. 3. For partial statuses: ``estimate * progress%``.
  1110. 4. ``None`` if nothing is known.
  1111. """
  1112. tracked_grams = sum(r.get("weight_used") or 0 for r in (usage_results or []))
  1113. if tracked_grams > 0:
  1114. return round(tracked_grams, 1)
  1115. if status == "completed":
  1116. return archive_filament_used_grams
  1117. if archive_filament_used_grams:
  1118. scale = max(0.0, min(((progress or 0) / 100.0), 1.0))
  1119. if scale > 0:
  1120. return round(archive_filament_used_grams * scale, 1)
  1121. return None
  1122. def _get_start_ams_mapping(data: dict, archive_id: int | None) -> list[int] | None:
  1123. """Resolve AMS mapping for print start without consuming stored queue/reprint state."""
  1124. stored_ams_mapping = data.get("ams_mapping")
  1125. if not stored_ams_mapping and archive_id:
  1126. stored_ams_mapping = _print_ams_mappings.get(archive_id)
  1127. return stored_ams_mapping
  1128. def _get_start_plate_id(archive_id: int | None) -> int | None:
  1129. """Resolve plate_id for print start without consuming stored direct-Print state.
  1130. Direct-Print of a single plate from a multi-plate 3MF registers plate_id in
  1131. ``_print_plate_ids`` at dispatch time; this lets the spoolman / usage tracker
  1132. read it back at print-start without popping (the entry is popped on print
  1133. completion or TTL eviction, mirroring ``_print_ams_mappings``).
  1134. """
  1135. if archive_id is None:
  1136. return None
  1137. return _print_plate_ids.get(archive_id)
  1138. def _partial_progress_scale(progress: int | float | None) -> float:
  1139. """Clamp ``progress / 100`` into [0.0, 1.0] for partial-print scaling.
  1140. Used by every site that multiplies a "would-have-used" slicer estimate
  1141. down to "actually-used" for failed / cancelled / stopped prints. Centralised
  1142. so the three sites in ``_background_notifications`` (and the per-plate
  1143. override helper) can't drift apart on the coercion shape.
  1144. """
  1145. return max(0.0, min((progress or 0) / 100.0, 1.0))
  1146. def _scope_notification_archive_data_to_plate(
  1147. archive_data: dict,
  1148. archive_file_path: str | None,
  1149. plate_id: int | None,
  1150. print_status: str,
  1151. progress: int | float | None,
  1152. base_dir: Path,
  1153. ) -> dict:
  1154. """Override summed-across-plates totals in ``archive_data`` with the values
  1155. for ``plate_id`` so the completion notification reports what was actually
  1156. printed, not the whole project (#1785).
  1157. The 3MF parser at services/archive.py:200-264 sums ``prediction`` and
  1158. ``weight`` across every plate of a multi-plate file (#1593) — correct for
  1159. the archive card's "whole project" headline, wrong for the completion
  1160. notification of a single-plate print. The queue UI already re-reads the
  1161. 3MF per-plate at print_queue.py:272-285; this helper mirrors that for the
  1162. notification payload (filament grams, time estimate, per-slot breakdown).
  1163. No-ops when ``plate_id`` is None, the file is missing, or the 3MF carries
  1164. no per-plate values — in every fail case the original ``archive_data`` is
  1165. returned unchanged so the notification still sends.
  1166. """
  1167. if plate_id is None or not archive_file_path:
  1168. return archive_data
  1169. from backend.app.utils.threemf_tools import (
  1170. extract_filament_usage_from_3mf,
  1171. extract_print_time_from_3mf,
  1172. )
  1173. archive_path = base_dir / archive_file_path
  1174. if not archive_path.exists():
  1175. return archive_data
  1176. plate_slots = extract_filament_usage_from_3mf(archive_path, plate_id)
  1177. plate_grams = sum(f.get("used_g", 0) for f in plate_slots)
  1178. plate_time = extract_print_time_from_3mf(archive_path, plate_id)
  1179. scale = 1.0 if print_status == "completed" else _partial_progress_scale(progress)
  1180. if plate_time:
  1181. archive_data["print_time_seconds"] = plate_time
  1182. # Gate both the grams headline AND the per-slot breakdown on the same
  1183. # `plate_grams > 0` signal: if the 3MF carries per-plate filament rows but
  1184. # they all sum to zero (slicer bug / re-slice without estimate), drop back
  1185. # to the project-level grams the archive columns already provide rather
  1186. # than ship a project-level headline next to an all-zero per-plate
  1187. # breakdown.
  1188. if plate_grams > 0:
  1189. archive_data["actual_filament_grams"] = round(plate_grams * scale, 1)
  1190. archive_data["filament_slots"] = [
  1191. {
  1192. "slot_id": s.get("slot_id"),
  1193. "used_g": round((s.get("used_g") or 0) * scale, 1),
  1194. "type": s.get("type", ""),
  1195. "color": s.get("color", ""),
  1196. }
  1197. for s in plate_slots
  1198. ]
  1199. return archive_data
  1200. def _extract_filament_data_from_mqtt(data: dict, ams_mapping: list[int] | None = None) -> dict[str, str]:
  1201. """Best-effort filament metadata from the MQTT print-start snapshot.
  1202. Used when the 3MF can't be downloaded (P1S/A1/P2S firmwares lock the
  1203. file during print, see #1533) so the fallback PrintArchive still has
  1204. enough filament info to support the inventory views and AMS-expansion
  1205. planning the operator opens it for. Returns a dict with optional
  1206. ``filament_type`` and ``filament_color`` keys in the same
  1207. comma-separated format the 3MF extractor produces, so the rest of the
  1208. codebase treats the fallback archive identically to a normal one.
  1209. ``ams_mapping`` is the slicer's slot-per-print-filament list captured
  1210. from the MQTT print payload (global tray IDs, possibly -1 for VT-tray
  1211. entries). When supplied, only the slots actually consumed by this
  1212. print contribute. Without it the function falls back to every loaded
  1213. AMS slot — less accurate but still useful.
  1214. Accepts both the raw inner payload (``{"ams": {"ams": [...]}, ...}``)
  1215. that the unit tests pass directly, AND the on_print_start callback
  1216. shape (``{"raw_data": {"ams": {"ams": [...]}, ...}, ...}``) the
  1217. bambu_mqtt service hands to main.py at runtime. The original
  1218. ``_extract_filament_data_from_mqtt(data)`` shipped in #1533 only
  1219. handled the inner shape and silently returned ``{}`` for every real
  1220. print start, leaving fallback archives' filament fields NULL — the
  1221. exact regression the fix was meant to close. Reported with a log
  1222. proving the AMS state was right there at
  1223. ``data["raw_data"]["ams"]["ams"][0]["tray"][0]`` (#1533 follow-up).
  1224. """
  1225. result: dict[str, str] = {}
  1226. # Look at the on_print_start wrapper first, then the inner shape.
  1227. raw_data = (data or {}).get("raw_data")
  1228. ams_root = (raw_data or {}).get("ams") if isinstance(raw_data, dict) else None
  1229. if not isinstance(ams_root, dict):
  1230. ams_root = (data or {}).get("ams") or {}
  1231. ams_units = ams_root.get("ams") if isinstance(ams_root, dict) else None
  1232. if not isinstance(ams_units, list) or not ams_units:
  1233. return result
  1234. # Map global tray id (unit * 4 + tray) → (type, color).
  1235. loaded: dict[int, tuple[str, str]] = {}
  1236. for unit in ams_units:
  1237. if not isinstance(unit, dict):
  1238. continue
  1239. try:
  1240. unit_id = int(unit.get("id", 0))
  1241. except (TypeError, ValueError):
  1242. continue
  1243. for tray in unit.get("tray") or []:
  1244. if not isinstance(tray, dict):
  1245. continue
  1246. try:
  1247. tray_id = int(tray.get("id", 0))
  1248. except (TypeError, ValueError):
  1249. continue
  1250. ttype = (tray.get("tray_type") or "").strip()
  1251. tcolor = (tray.get("tray_color") or "").strip().upper()
  1252. if not ttype:
  1253. continue # Empty / unloaded slot.
  1254. loaded[unit_id * 4 + tray_id] = (ttype, tcolor)
  1255. if not loaded:
  1256. return result
  1257. if ams_mapping:
  1258. used_ids = [int(x) for x in ams_mapping if isinstance(x, (int, float)) and int(x) >= 0]
  1259. filaments = [loaded[g] for g in used_ids if g in loaded]
  1260. if not filaments:
  1261. return result # Mapping points entirely at slots we have no data for.
  1262. else:
  1263. filaments = [loaded[g] for g in sorted(loaded.keys())]
  1264. types_joined = ",".join(f[0] for f in filaments)
  1265. colors_joined = ",".join(f[1] for f in filaments if f[1])
  1266. # Column limits per backend/app/models/archive.py: filament_type=50,
  1267. # filament_color=200.
  1268. if types_joined:
  1269. result["filament_type"] = types_joined[:50]
  1270. if colors_joined:
  1271. result["filament_color"] = colors_joined[:200]
  1272. return result
  1273. def _maybe_start_layer_timelapse(printer, printer_id: int, archive_id: int) -> bool:
  1274. """Start a layer-timelapse session for *archive_id* when the printer has
  1275. an external camera configured. Returns True if a session was started.
  1276. Three call sites in on_print_start (expected-archive promotion, fallback
  1277. archive creation, fresh-archive creation) used to inline this same
  1278. if-block; the inline copies kept drifting (#1353 fixed only one of them
  1279. on the first pass). Centralising the conditional + call here makes the
  1280. contract testable in isolation and keeps the three sites locked in step.
  1281. """
  1282. if not (printer.external_camera_enabled and printer.external_camera_url):
  1283. return False
  1284. from backend.app.services.layer_timelapse import start_session
  1285. start_session(
  1286. printer_id,
  1287. archive_id,
  1288. printer.external_camera_url,
  1289. printer.external_camera_type or "mjpeg",
  1290. snapshot_url=printer.external_camera_snapshot_url,
  1291. rotation=getattr(printer, "camera_rotation", 0),
  1292. )
  1293. logging.getLogger(__name__).info("Started layer timelapse for printer %s, archive %s", printer_id, archive_id)
  1294. return True
  1295. def _format_hms_error_summary(hms_errors: list[dict]) -> str | None:
  1296. """Build a human-readable failure reason from MQTT hms_errors for PrintQueueItem.error_message.
  1297. Each entry has keys: code ('0x4038'), attr (32-bit int), module, severity, and
  1298. — since #2926 — the description the parser already resolved, which is preferred
  1299. when present so the queue's failure reason reads the same as the status
  1300. response. The short code still produces the bracketed label, and still
  1301. resolves the sentence for a caller whose entries predate the field. An entry
  1302. with a 16-char ``full_code`` is labelled with it instead, since the short code
  1303. of an ``hms[]`` fault is not a code anyone can look up. Falls back to the bare
  1304. label when no description is on file. Returns None for an empty list so
  1305. callers can leave error_message unset.
  1306. """
  1307. if not hms_errors:
  1308. return None
  1309. from backend.app.services.hms_errors import get_error_description
  1310. parts: list[str] = []
  1311. for err in hms_errors:
  1312. try:
  1313. # `_hms_short_code` rather than a local derivation: this one used to
  1314. # format the error without masking it to 16 bits, so an `hms[]` entry
  1315. # whose code carries an alert-level group produced a five-digit label
  1316. # like "0500_3000A" — not a code the user can look up, and never a
  1317. # catalogue key, so the sentence was lost with it.
  1318. short_code = _hms_short_code(err.get("attr", 0), err.get("code", 0))
  1319. except (TypeError, ValueError):
  1320. continue
  1321. description = err.get("description") or get_error_description(short_code)
  1322. # An `hms[]` fault's short code ("0500_000E") drops the part and level
  1323. # groups and is not a code anyone can look up; its full code in the
  1324. # printer screen's four groups is (#2728).
  1325. full_code = str(err.get("full_code") or "")
  1326. label = "-".join(full_code[i : i + 4] for i in range(0, 16, 4)) if len(full_code) == 16 else short_code
  1327. parts.append(f"[{label}] {description}" if description else f"[{label}]")
  1328. return "; ".join(parts) if parts else None
  1329. async def _bump_library_file_usage_if_completed(db, item, queue_status: str) -> None:
  1330. """Increment LibraryFile.print_count and stamp last_printed_at when a queued
  1331. print completes successfully. Gated to status=='completed': failed, cancelled
  1332. and aborted prints do not count as usage. Caller is responsible for committing
  1333. the session. No-op when the queue item has no linked library file (e.g. reprints
  1334. from an archive). See #1008."""
  1335. if queue_status != "completed" or item.library_file_id is None:
  1336. return
  1337. from backend.app.models.library import LibraryFile
  1338. lib_file = await db.scalar(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1339. if lib_file is None:
  1340. return
  1341. lib_file.print_count = (lib_file.print_count or 0) + 1
  1342. lib_file.last_printed_at = datetime.now(timezone.utc)
  1343. def mark_printer_stopped_by_user(printer_id: int) -> None:
  1344. """Mark that the active print on this printer was stopped by the user from the queue UI.
  1345. When on_print_complete fires with status 'failed' for a printer in this set we
  1346. reclassify it as 'cancelled' so the correct 'print stopped' notification is sent
  1347. rather than a 'print failed' notification.
  1348. """
  1349. _user_stopped_printers.add(printer_id)
  1350. logging.getLogger(__name__).info("Marked printer %s as user-stopped from queue", printer_id)
  1351. _last_status_broadcast: dict[int, str] = {}
  1352. # Track printers where we've updated nozzle_count
  1353. _nozzle_count_updated: set[int] = set()
  1354. async def _maybe_notify_printer_offline(printer_id: int) -> None:
  1355. """Wait the debounce window then fire `on_printer_offline` if the printer
  1356. is still offline.
  1357. Scheduled by `on_printer_status_change` on the connected → disconnected
  1358. edge (#1752). Cancelled by the same handler if the printer reconnects
  1359. before the window elapses, so a single MQTT blip + recovery doesn't
  1360. notify. Both the staleness-detector path (`bambu_mqtt.py::check_staleness`)
  1361. and the smart-plug power-off path (`printer_manager.mark_printer_offline`)
  1362. route through the same status-change callback, so this covers both.
  1363. """
  1364. logger = logging.getLogger(__name__)
  1365. try:
  1366. await asyncio.sleep(_PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS)
  1367. still_offline = not printer_manager.is_connected(printer_id)
  1368. logger.info(
  1369. "[#1752] Printer %s offline debounce elapsed: still_offline=%s",
  1370. printer_id,
  1371. still_offline,
  1372. )
  1373. if not still_offline:
  1374. return
  1375. async with async_session() as db:
  1376. from backend.app.models.printer import Printer
  1377. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1378. printer = result.scalar_one_or_none()
  1379. if not printer:
  1380. logger.warning(
  1381. "[#1752] Printer %s missing from DB at offline-notify time; skipping",
  1382. printer_id,
  1383. )
  1384. return
  1385. # Recorded only when the relay can publish it, so the reconnect's
  1386. # online event always has an offline before it.
  1387. if mqtt_relay.enabled and mqtt_relay.connected:
  1388. _printer_offline_published.add(printer_id)
  1389. try:
  1390. await mqtt_relay.on_printer_offline(printer_id, printer.name, printer.serial_number)
  1391. except Exception as e:
  1392. logger.warning("MQTT relay offline event failed for printer %s: %s", printer_id, e)
  1393. logger.info(
  1394. "[#1752] Dispatching on_printer_offline for printer %s (%s)",
  1395. printer_id,
  1396. printer.name,
  1397. )
  1398. await notification_service.on_printer_offline(printer_id, printer.name, db)
  1399. except asyncio.CancelledError:
  1400. raise
  1401. except Exception as e:
  1402. logger.warning("Printer offline notification failed for printer %s: %s", printer_id, e)
  1403. finally:
  1404. _printer_offline_notify_tasks.pop(printer_id, None)
  1405. def _hms_notify_key(error) -> str:
  1406. """What identifies a fault for notification de-duplication.
  1407. The full code, which is unique per fault. ``attr`` alone used to be the key:
  1408. unique for a ``print_error``, but for an ``hms[]`` fault it is only the
  1409. module and part, so two faults on one part (#1840's H2C held 0500-0600-0002-0005
  1410. and -0006 together) shared a key and only the first was ever notified. An
  1411. entry without a full code falls back to attr and code together.
  1412. """
  1413. full_code = getattr(error, "full_code", "") or ""
  1414. if full_code:
  1415. return full_code.upper()
  1416. return f"{error.attr:08X}:{error.code}"
  1417. def _hms_fault_counts(error) -> bool:
  1418. """Whether a fault counts as a problem: the same rule the frontend's
  1419. ``filterKnownHMSErrors`` applies to the printer card, badge and camera wall.
  1420. It counts when Bambu publishes text for it or it offers action buttons, and
  1421. its level is a real one. An ``hms[]`` fault at level 3 (notification) with
  1422. no actions does not count: those are things like "the top cover is open" or
  1423. "the chamber is hot, fan speed increased", which a printer can hold through
  1424. a whole print. A ``print_error`` at the same level (0xCxxx) still counts, as
  1425. it always has; those are prompts such as "unable to start drying" (#2728).
  1426. """
  1427. if error.severity < 1:
  1428. return False
  1429. has_actions = bool(getattr(error, "actions", None))
  1430. is_hms_notice = len(getattr(error, "full_code", "") or "") == 16 and error.severity == 3
  1431. return has_actions or (bool(getattr(error, "description", None)) and not is_hms_notice)
  1432. def _hms_errors_to_notify(errors: list, new_error_codes: set[str]) -> list:
  1433. """The new faults that count (see ``_hms_fault_counts``).
  1434. These go to the MQTT relay; the caller also needs a description before it
  1435. sends a notification. Level 0, Bambu's "invalid" level, never counts. This
  1436. used to read ``severity >= 2`` when severity held the part byte; on the real
  1437. level that would drop the task-stopping errors (#2728).
  1438. """
  1439. return [e for e in errors if _hms_notify_key(e) in new_error_codes and _hms_fault_counts(e)]
  1440. def _take_new_hms_faults(printer_id: int, errors: list, print_state: str | None = None) -> list:
  1441. """The faults on this printer not notified yet, and record them as notified.
  1442. Tracking is updated before anything is sent, so concurrent status callbacks
  1443. cannot notify the same fault twice. A notified fault is forgotten once it
  1444. has been gone for ``_HMS_CLEAR_GRACE_SECONDS``, so one that flickers off
  1445. and on is notified once (#3226), while one that clears and comes back much
  1446. later is notified again.
  1447. When ``print_state`` changes (a print resumed, started or finished), every
  1448. fault recorded so far is forgotten the first time it is gone, without the
  1449. wait: a runout fixed before resuming must be notified if it happens again a
  1450. few minutes later, while the printer sits paused. Not only the faults gone
  1451. at the change itself, because the update that flips the state can still
  1452. carry the old fault (a ``print_error`` entry stays until a payload brings
  1453. ``hms``).
  1454. """
  1455. now = time.time()
  1456. current = {_hms_notify_key(e) for e in errors}
  1457. seen = _notified_hms_errors.setdefault(printer_id, {})
  1458. forget_when_gone = _hms_forget_when_gone.setdefault(printer_id, set())
  1459. if print_state is not None:
  1460. print_state = print_state.upper()
  1461. if _hms_print_state.get(printer_id, print_state) != print_state:
  1462. forget_when_gone.update(seen)
  1463. _hms_print_state[printer_id] = print_state
  1464. for key, last_seen in list(seen.items()):
  1465. if key not in current and (key in forget_when_gone or now - last_seen >= _HMS_CLEAR_GRACE_SECONDS):
  1466. del seen[key]
  1467. forget_when_gone.discard(key)
  1468. new = current - seen.keys()
  1469. for key in current:
  1470. seen[key] = now
  1471. if not seen:
  1472. _notified_hms_errors.pop(printer_id, None)
  1473. if not forget_when_gone:
  1474. _hms_forget_when_gone.pop(printer_id, None)
  1475. return _hms_errors_to_notify(errors, new)
  1476. # `stg_cur` values that mean the printer is not in a preparation stage: 0 is
  1477. # "Printing", -1 and 255 are "no stage" (#3211).
  1478. _NO_PREPARATION_STAGES = frozenset({0, -1, 255})
  1479. def _progress_milestone_to_notify(printer_id: int, state: PrinterState) -> int | None:
  1480. """The milestone (25, 50 or 75) this status update reaches for the first time, if any.
  1481. Records it as notified. Called only for a printing state with progress above 0.
  1482. Progress before the first layer is not progress through the print (#3211).
  1483. An A1 mini reports ``mc_percent`` 85 in the first frame of a print, while
  1484. still preheating the bed at layer 0, then 3, 7, 40 and 44 through its
  1485. calibration, and starts layer 1 at 45. Read as progress, that 85 sent the
  1486. 75% notification together with Print Started, and since 75 was then on
  1487. record, 25 and 50 could never fire. So nothing counts while the printer
  1488. reports a layer count but has not started layer 1.
  1489. Without a layer count -- a print whose first frame carried no
  1490. ``total_layer_num``, until the pushall that asks for it is answered
  1491. (#2702) -- the preparation stage says the same thing: before layer 1 the
  1492. A1 mini reported ``stg_cur`` 2, 4, 14 and 1 (bed preheating, calibration,
  1493. homing), and 0 from layer 1 on. -1 and 255 are "no stage". A printer that
  1494. reports neither keeps the old behaviour rather than never notifying.
  1495. """
  1496. if (state.layer_num or 0) < 1:
  1497. if (state.total_layers or 0) > 0:
  1498. return None
  1499. if state.stg_cur not in _NO_PREPARATION_STAGES:
  1500. return None
  1501. progress = state.progress or 0
  1502. current_milestone = 0
  1503. if progress >= 75:
  1504. current_milestone = 75
  1505. elif progress >= 50:
  1506. current_milestone = 50
  1507. elif progress >= 25:
  1508. current_milestone = 25
  1509. if current_milestone > _last_progress_milestone.get(printer_id, 0):
  1510. _last_progress_milestone[printer_id] = current_milestone
  1511. return current_milestone
  1512. return None
  1513. async def on_printer_status_change(printer_id: int, state: PrinterState):
  1514. """Handle printer status changes - broadcast via WebSocket."""
  1515. try:
  1516. notify_live_activities.observe(printer_id, state)
  1517. except Exception:
  1518. logging.getLogger(__name__).exception("Notify Live Activity status hook failed for printer %s", printer_id)
  1519. # Connected-edge reconciliation (#1542 follow-up). When the printer
  1520. # transitions disconnected → connected — which covers both Bambuddy
  1521. # startup (no prior connection) and a mid-session MQTT reconnect — fire
  1522. # `reconcile_stale_active_prints` exactly once for this connection so
  1523. # any archive still in `status="printing"` that can't actually be
  1524. # running anymore (printer IDLE / different subtask / empty subtask)
  1525. # gets a synthesised PRINT COMPLETE. Without this, a print that
  1526. # finished during a disconnect window + a smart-plug power cycle
  1527. # leaves the .3mf on the SD card and the firmware ghost-replays it on
  1528. # next boot. Reconciliation runs concurrently — it must not block the
  1529. # WebSocket dedup / broadcast logic below, and the connected edge is
  1530. # marked True BEFORE the await so concurrent status updates inside
  1531. # the same connection don't re-trigger reconciliation.
  1532. #
  1533. # Wait for a real push_status before reconciling (#1679): MQTT
  1534. # `_on_connect` broadcasts `state` IMMEDIATELY after the broker accepts
  1535. # the connection, BEFORE `_request_push_all` round-trips. At that
  1536. # instant the `PrinterState` is still on construction defaults — most
  1537. # importantly `state.state == "unknown"` and `state.subtask_name == ""`.
  1538. # If reconcile spawns here, every in-flight archive falls through to
  1539. # the empty-subtask_name trigger and gets synthesised `aborted`, which
  1540. # creates a duplicate archive on the real PRINT COMPLETE and
  1541. # double-counts filament. Gating on `state.state ∉ ("", "unknown")`
  1542. # keeps the #1542 mechanism intact: once the first real push_status
  1543. # updates `state.state` (RUNNING / IDLE / FINISH / …), this handler
  1544. # fires again with the flag still False — reconcile then runs against
  1545. # actual evidence.
  1546. state_known = bool(state.state) and state.state.upper() not in ("", "UNKNOWN")
  1547. if state.connected and state_known and not _printer_reconciled_since_connect.get(printer_id, False):
  1548. _printer_reconciled_since_connect[printer_id] = True
  1549. spawn_background_task(
  1550. reconcile_stale_active_prints(printer_id),
  1551. name=f"reconcile-stale-prints-{printer_id}",
  1552. )
  1553. elif not state.connected and _printer_reconciled_since_connect.get(printer_id, False):
  1554. # Re-arm so the next reconnect triggers reconciliation again.
  1555. _printer_reconciled_since_connect[printer_id] = False
  1556. # Same edge, for the calibration table the AMS card reads its K values from.
  1557. #
  1558. # Also gated on knowing a nozzle diameter, which is what decides *which*
  1559. # tables to ask for. A `state_known` gate alone is not enough: the first
  1560. # real push_status is what makes the state known, and the nozzle fields do
  1561. # not always arrive in it. Latching there would spend this connection's one
  1562. # attempt on a printer that could not yet say what was fitted.
  1563. nozzle_known = any(n.nozzle_diameter for n in (state.nozzles or []))
  1564. if (
  1565. state.connected
  1566. and state_known
  1567. and nozzle_known
  1568. and not _printer_kprofiles_primed_since_connect.get(printer_id, False)
  1569. ):
  1570. _printer_kprofiles_primed_since_connect[printer_id] = True
  1571. spawn_background_task(
  1572. prime_kprofile_table(printer_id),
  1573. name=f"prime-kprofiles-{printer_id}",
  1574. )
  1575. elif not state.connected and _printer_kprofiles_primed_since_connect.get(printer_id, False):
  1576. _printer_kprofiles_primed_since_connect[printer_id] = False
  1577. # A slot can lose its K-profile selection (cali_idx back to -1) with nothing
  1578. # else in the AMS report changing -- a power cycle does it to every slot --
  1579. # and on_ams_change never hears of it (#3219). Checked here, on every push
  1580. # while the printer is idle; needs_check is cheap and throttled per slot.
  1581. # Guarded: nothing here may stop the status broadcast below.
  1582. try:
  1583. if not state.connected:
  1584. kprofile_drift.forget_printer(printer_id)
  1585. elif kprofile_drift.needs_check(printer_id, state):
  1586. spawn_background_task(
  1587. kprofile_drift.reapply_lost_kprofiles(printer_id),
  1588. name=f"reapply-kprofiles-{printer_id}",
  1589. )
  1590. except Exception:
  1591. logging.getLogger(__name__).exception("[Printer %s] K-profile check failed", printer_id)
  1592. # Offline-notification edge (#1752): schedule `on_printer_offline` on
  1593. # connected → disconnected. The "back online" channel is already covered
  1594. # by the print-failure notification (firmware reports gcode_state=FAILED
  1595. # on reconnect of an interrupted print), so there is no online
  1596. # notification. The MQTT relay gets both: offline after the debounce, and
  1597. # online on the reconnect that follows a published offline.
  1598. prev_connected = _printer_last_connected.get(printer_id)
  1599. _printer_last_connected[printer_id] = state.connected
  1600. if prev_connected is True and not state.connected:
  1601. existing = _printer_offline_notify_tasks.get(printer_id)
  1602. if existing is None or existing.done():
  1603. logging.getLogger(__name__).info(
  1604. "[#1752] Printer %s connected→disconnected edge; scheduling offline notification in %.0fs",
  1605. printer_id,
  1606. _PRINTER_OFFLINE_NOTIFY_DEBOUNCE_SECONDS,
  1607. )
  1608. _printer_offline_notify_tasks[printer_id] = asyncio.create_task(
  1609. _maybe_notify_printer_offline(printer_id),
  1610. name=f"printer-offline-notify-{printer_id}",
  1611. )
  1612. elif state.connected:
  1613. # Kept until the relay can actually send online: with its broker down
  1614. # now, the next status update after the reconnect sends it.
  1615. if printer_id in _printer_offline_published and mqtt_relay.enabled and mqtt_relay.connected:
  1616. _printer_offline_published.discard(printer_id)
  1617. printer_info = printer_manager.get_printer(printer_id)
  1618. if printer_info:
  1619. try:
  1620. await mqtt_relay.on_printer_online(printer_id, printer_info.name, printer_info.serial_number)
  1621. except Exception as e:
  1622. logging.getLogger(__name__).warning(
  1623. "MQTT relay online event failed for printer %s: %s", printer_id, e
  1624. )
  1625. pending = _printer_offline_notify_tasks.pop(printer_id, None)
  1626. if pending is not None and not pending.done():
  1627. logging.getLogger(__name__).info(
  1628. "[#1752] Printer %s reconnected before debounce; cancelling pending offline notification",
  1629. printer_id,
  1630. )
  1631. pending.cancel()
  1632. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  1633. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  1634. temps = state.temperatures or {}
  1635. nozzle_temp = round(temps.get("nozzle", 0))
  1636. bed_temp = round(temps.get("bed", 0))
  1637. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  1638. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  1639. # Auto-detect dual-nozzle printers from MQTT temperature data
  1640. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  1641. _nozzle_count_updated.add(printer_id)
  1642. # Update nozzle_count in database
  1643. async with async_session() as db:
  1644. from backend.app.models.printer import Printer
  1645. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1646. printer = result.scalar_one_or_none()
  1647. if printer and printer.nozzle_count != 2:
  1648. printer.nozzle_count = 2
  1649. await db.commit()
  1650. logging.getLogger(__name__).info(
  1651. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  1652. )
  1653. # Include target temps for heating phase detection
  1654. bed_target = round(temps.get("bed_target", 0))
  1655. nozzle_target = round(temps.get("nozzle_target", 0))
  1656. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  1657. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  1658. # Include AMS dry_time and tray state values so drying/slot changes trigger broadcasts.
  1659. #
  1660. # dry_countdown_stalled rides along because it is the one drying signal the
  1661. # countdown itself cannot carry: the MQTT layer raises it precisely BECAUSE
  1662. # dry_time stopped moving, so on the frame that flips it every other member
  1663. # of this key is identical and the push would be deduplicated away. Mid-print
  1664. # a temperature would eventually break the tie, but a parked command on an
  1665. # idle machine changes nothing else at all — AMS temp and humidity are not in
  1666. # the key — so the badge could sit unreachable indefinitely. The flag flips at
  1667. # most once per drying cycle, so it costs no mid-print broadcast traffic.
  1668. ams_dry_key = (
  1669. tuple((a.get("dry_time", 0), bool(a.get("dry_countdown_stalled"))) for a in (state.raw_data.get("ams") or []))
  1670. if state.raw_data
  1671. else ()
  1672. )
  1673. # Include tray states so load/unload transitions (state 11→10) trigger broadcasts (#784)
  1674. #
  1675. # The filament identity fields are here because Configure Slot writes
  1676. # exactly those and nothing else. Re-configuring a slot from PLA to another
  1677. # brand or colour of PLA leaves id/tray_type/state identical, so the key
  1678. # matched, this function returned before broadcasting, and the card kept
  1679. # showing the old filament until the 30s fallback poll or a page reload —
  1680. # even though the configure route asks the printer for a fresh pushall and
  1681. # that push does carry the new values. Reset always worked, because it
  1682. # clears tray_type.
  1683. #
  1684. # These fields only change when someone configures a slot or swaps a spool,
  1685. # so unlike temperature or progress they add no broadcast traffic mid-print.
  1686. ams_tray_key = (
  1687. tuple(
  1688. (
  1689. t.get("id"),
  1690. t.get("tray_type", ""),
  1691. t.get("state"),
  1692. t.get("tray_color", ""),
  1693. t.get("tray_info_idx", ""),
  1694. t.get("tray_sub_brands", ""),
  1695. t.get("cali_idx"),
  1696. )
  1697. for a in (state.raw_data.get("ams") or [])
  1698. for t in a.get("tray", [])
  1699. )
  1700. if state.raw_data
  1701. else ()
  1702. )
  1703. # Filament Track Switch: which inlet each AMS is bound to, and whether the
  1704. # accessory is fitted at all. Neither is in ams_tray_key (it is per-tray) nor
  1705. # in the AMS change-hash (tray fields only, and widening that would fire
  1706. # spurious Spoolman syncs), so without them a "Join IN-B" on the printer
  1707. # screen changed no key at all and the card's inlet badges sat stale until a
  1708. # reload. Like the filament-backup flag, these only move when someone
  1709. # reconfigures the machine, so they add no mid-print broadcast traffic.
  1710. fts_key = (
  1711. state.fila_switch.installed if state.fila_switch else False,
  1712. tuple(sorted(state.ams_switch_inlet.items())),
  1713. # Which hotend holds which slot. Unlike the two above this does move
  1714. # mid-print, on every filament change — but only between discrete slots,
  1715. # so it adds a push per toolchange, not a stream. The AMS slot menu needs
  1716. # it live: it decides which hotend the Load dialog may offer and whether
  1717. # Unload has anything to act on.
  1718. tuple(
  1719. sorted(
  1720. ((ext, slot.ams_id, slot.slot_id, slot.has_filament) for ext, slot in state.extruder_slots.items()),
  1721. # Sort on the extruder id alone: the other members are nullable
  1722. # and comparing None with an int raises.
  1723. key=lambda entry: entry[0],
  1724. )
  1725. ),
  1726. )
  1727. status_key = (
  1728. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  1729. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  1730. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  1731. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  1732. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}:"
  1733. f"{ams_dry_key}:{ams_tray_key}:{state.door_open}:{state.ams_filament_backup}:{fts_key}"
  1734. )
  1735. is_active_print = state.state in _ACTIVE_PRINT_STATES
  1736. if not is_active_print:
  1737. _unauthorized_print_kill_sent.discard(printer_id)
  1738. elif printer_id in _unauthorized_print_kill_sent:
  1739. # stop_print() was already sent for this print; avoid all further
  1740. # ownership and settings work until the printer leaves an active state.
  1741. pass
  1742. elif _is_bambuddy_authorized_print_in_memory(printer_id, state):
  1743. # Normal Bambuddy-started prints stay entirely on the in-memory path.
  1744. _unauthorized_print_kill_sent.discard(printer_id)
  1745. else:
  1746. kill_switch_enabled = False
  1747. authorization: bool | None = None
  1748. status_logger = logging.getLogger(__name__)
  1749. try:
  1750. kill_switch_enabled = await _is_printer_kill_switch_enabled_cached()
  1751. if kill_switch_enabled:
  1752. async with async_session() as db:
  1753. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  1754. except Exception as e:
  1755. # Fail safe: a database/reconciliation error must never turn into an
  1756. # irreversible stop of a print whose ownership is still unknown.
  1757. authorization = None
  1758. status_logger.warning(
  1759. "[KILL SWITCH] Failed to reconcile print authorization for printer %s: %s", printer_id, e
  1760. )
  1761. if not kill_switch_enabled or authorization is True:
  1762. _unauthorized_print_kill_sent.discard(printer_id)
  1763. elif authorization is None:
  1764. _unauthorized_print_kill_sent.discard(printer_id)
  1765. status_logger.debug(
  1766. "[KILL SWITCH] Deferring authorization for printer %s until archive state is reconciled",
  1767. printer_id,
  1768. )
  1769. else:
  1770. try:
  1771. stopped = printer_manager.stop_print(printer_id)
  1772. if stopped:
  1773. _unauthorized_print_kill_sent.add(printer_id)
  1774. printer_info = printer_manager.get_printer(printer_id)
  1775. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  1776. filename = state.subtask_name or state.gcode_file or state.current_print or "Unknown"
  1777. notification_data = {
  1778. "status": "stopped",
  1779. "filename": state.gcode_file or state.current_print or "",
  1780. "subtask_name": state.subtask_name or "",
  1781. "progress": state.progress,
  1782. "reason": "unauthorized_print",
  1783. }
  1784. status_logger.warning(
  1785. "[KILL SWITCH] Stopped unauthorized print on printer %s (state=%s)",
  1786. printer_id,
  1787. state.state,
  1788. )
  1789. try:
  1790. await ws_manager.broadcast(
  1791. {
  1792. "type": "kill_switch_triggered",
  1793. "printer_id": printer_id,
  1794. "printer_name": printer_name,
  1795. "filename": filename,
  1796. "reason": "unauthorized_print",
  1797. }
  1798. )
  1799. except Exception as e:
  1800. status_logger.warning(
  1801. "[KILL SWITCH] WebSocket notification failed for printer %s: %s", printer_id, e
  1802. )
  1803. previous_task = _kill_switch_notification_tasks.pop(printer_id, None)
  1804. if previous_task is not None and not previous_task.done():
  1805. previous_task.cancel()
  1806. _kill_switch_notification_tasks[printer_id] = spawn_background_task(
  1807. _send_kill_switch_provider_notification(printer_id, printer_name, notification_data),
  1808. name=f"kill-switch-notification-{printer_id}",
  1809. )
  1810. else:
  1811. status_logger.warning(
  1812. "[KILL SWITCH] Could not stop unauthorized print on printer %s (state=%s)",
  1813. printer_id,
  1814. state.state,
  1815. )
  1816. except Exception as e:
  1817. status_logger.warning(
  1818. "[KILL SWITCH] Failed to stop unauthorized print on printer %s: %s", printer_id, e
  1819. )
  1820. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  1821. try:
  1822. printer_info = printer_manager.get_printer(printer_id)
  1823. if printer_info:
  1824. await mqtt_relay.on_printer_status(
  1825. printer_id,
  1826. state,
  1827. printer_info.name,
  1828. printer_info.serial_number,
  1829. printer_manager.is_awaiting_plate_clear(printer_id),
  1830. )
  1831. except Exception:
  1832. pass # Don't fail status callback if MQTT fails
  1833. if _last_status_broadcast.get(printer_id) == status_key:
  1834. return # No change, skip WebSocket broadcast
  1835. _last_status_broadcast[printer_id] = status_key
  1836. # Check for progress milestone notifications (25%, 50%, 75%)
  1837. progress = state.progress or 0
  1838. is_printing = state.state in ("RUNNING", "PRINTING")
  1839. if is_printing and progress > 0:
  1840. current_milestone = _progress_milestone_to_notify(printer_id, state)
  1841. if current_milestone is not None:
  1842. try:
  1843. from backend.app.models.printer import Printer
  1844. # Read the printer in a short session and release the connection
  1845. # BEFORE the ~15s camera snapshot below — holding it across the grab
  1846. # pinned a pooled connection per milestone, per printer (issue #2572).
  1847. async with async_session() as db:
  1848. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1849. printer = result.scalar_one_or_none()
  1850. printer_name = printer.name if printer else f"Printer {printer_id}"
  1851. filename = state.subtask_name or state.gcode_file or "Unknown"
  1852. # remaining_time is in minutes, convert to seconds for notification
  1853. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  1854. # Capture camera snapshot for notification image attachment (no DB held).
  1855. image_data = await _capture_snapshot_for_notification(printer_id, printer, logging.getLogger(__name__))
  1856. # Notification send needs a session (provider/template lookups).
  1857. async with async_session() as db:
  1858. await notification_service.on_print_progress(
  1859. printer_id,
  1860. printer_name,
  1861. filename,
  1862. current_milestone,
  1863. db,
  1864. remaining_time_seconds,
  1865. image_data=image_data,
  1866. )
  1867. except Exception as e:
  1868. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  1869. elif progress < 5:
  1870. # Reset milestone tracking when print restarts or new print begins
  1871. _last_progress_milestone[printer_id] = 0
  1872. _first_layer_notified[printer_id] = False
  1873. # HMS error codes that should not trigger notifications even though they
  1874. # have known descriptions (e.g. user-initiated actions, not real errors).
  1875. _HMS_NOTIFICATION_SUPPRESS = {
  1876. "0500_400E", # Printing was cancelled (user action, not an error)
  1877. }
  1878. # Check for new HMS errors and send notifications
  1879. current_hms_errors = getattr(state, "hms_errors", []) or []
  1880. if current_hms_errors:
  1881. new_errors = _take_new_hms_faults(printer_id, current_hms_errors, state.state)
  1882. if new_errors:
  1883. try:
  1884. from backend.app.models.printer import Printer
  1885. # Read the printer in a short session and release the connection
  1886. # BEFORE the ~15s camera snapshot below (issue #2572).
  1887. async with async_session() as db:
  1888. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1889. printer = result.scalar_one_or_none()
  1890. printer_name = printer.name if printer else f"Printer {printer_id}"
  1891. # Format error details for notification
  1892. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  1893. module_names = {
  1894. 0x03: "Print/Task",
  1895. 0x05: "Nozzle/Extruder",
  1896. 0x07: "AMS/Filament",
  1897. 0x0C: "Motion Controller",
  1898. 0x12: "Chamber",
  1899. }
  1900. # Capture camera snapshot once for all error notifications (no DB held).
  1901. error_image_data = await _capture_snapshot_for_notification(
  1902. printer_id, printer, logging.getLogger(__name__)
  1903. )
  1904. # Notification sends need a session (provider/template lookups).
  1905. async with async_session() as db:
  1906. sent_count = 0
  1907. for error in new_errors:
  1908. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  1909. # Build short code like "0700_8010"
  1910. # Mask to 16 bits to handle printers that send larger values
  1911. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  1912. error_code_masked = error_code_int & 0xFFFF
  1913. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  1914. # Only notify for errors Bambu publishes text for — printers
  1915. # send undocumented codes that aren't real errors, and Bambu
  1916. # lists some with empty text. Resolved at parse time (#2926);
  1917. # short_code is still needed for the suppression set below.
  1918. description = error.description
  1919. if not description or short_code in _HMS_NOTIFICATION_SUPPRESS:
  1920. continue
  1921. error_type = f"{module_name} Error"
  1922. error_detail = description
  1923. await notification_service.on_printer_error(
  1924. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  1925. )
  1926. sent_count += 1
  1927. if sent_count:
  1928. logging.getLogger(__name__).info(
  1929. f"[HMS] Sent notification for {sent_count} error(s) on printer {printer_id}"
  1930. )
  1931. # Also publish to MQTT relay (no DB): every new fault that
  1932. # counts, with or without text, the same set the UI counts.
  1933. printer_info = printer_manager.get_printer(printer_id)
  1934. if printer_info:
  1935. errors_data = [
  1936. {
  1937. "code": e.code,
  1938. "attr": e.attr,
  1939. "module": e.module,
  1940. "severity": e.severity,
  1941. }
  1942. for e in new_errors
  1943. ]
  1944. await mqtt_relay.on_printer_error(
  1945. printer_id, printer_info.name, printer_info.serial_number, errors_data
  1946. )
  1947. except Exception as e:
  1948. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  1949. else:
  1950. # No HMS errors: nothing to send, but faults gone long enough (or gone
  1951. # across a print state change) are forgotten. Some codes, e.g. chamber
  1952. # temperature regulation during PETG prints, toggle every few seconds.
  1953. _take_new_hms_faults(printer_id, [], state.state)
  1954. await ws_manager.send_printer_status(
  1955. printer_id,
  1956. printer_state_to_dict(
  1957. state,
  1958. printer_id,
  1959. printer_manager.get_model(printer_id),
  1960. printer_manager.get_drying_targets(printer_id),
  1961. ),
  1962. )
  1963. def _is_bambu_uuid(tray_uuid: str) -> bool:
  1964. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  1965. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  1966. async def on_fts_inlet_change(printer_id: int, ams_id: int, inlet: str):
  1967. """Re-point a moved AMS's K-profiles at the nozzle it now feeds.
  1968. K-profiles are per-nozzle and the printer's calibration table is numbered
  1969. per-nozzle, but a tray holds exactly one ``cali_idx``. Moving an AMS to the
  1970. switch's other inlet therefore silently invalidates every configured slot in
  1971. it: the index stays put and now resolves against the other nozzle's table.
  1972. Measured on the maintainer's H2C — one spool calibrated 0.018 on the left
  1973. and 0.020 on the right kept the left profile after the move, and a manual
  1974. RFID re-read only re-asserted the same wrong one.
  1975. Configuring a slot is a deliberate preparation step, so this re-selects
  1976. rather than re-configures: only the calibration binding moves, and only for
  1977. slots whose spool already has a stored profile for the new nozzle. A slot
  1978. Bambuddy knows nothing about is left exactly as the operator left it.
  1979. """
  1980. logger = logging.getLogger(__name__)
  1981. target_extruder = extruder_for_inlet(inlet)
  1982. if target_extruder is None:
  1983. return
  1984. client = printer_manager.get_client(printer_id)
  1985. state = printer_manager.get_status(printer_id)
  1986. if not client or not state or not state.raw_data:
  1987. return
  1988. # The nozzle the AMS now feeds -- the diameter of the TARGET extruder, not
  1989. # of nozzle 0. On a machine with two sizes fitted, moving the inlet changes
  1990. # the nozzle width, which changes both the K profile to select and the
  1991. # preset the slot should carry.
  1992. nozzle_diameter = nozzle_diameter_for_extruder(state, target_extruder, printer_manager.get_model(printer_id))
  1993. ams_raw = state.raw_data.get("ams")
  1994. ams_list = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  1995. unit = next((u for u in ams_list if str(u.get("id")) == str(ams_id)), None)
  1996. if not unit:
  1997. return
  1998. try:
  1999. async with async_session() as db:
  2000. for tray in unit.get("tray", []):
  2001. tray_id = int(tray.get("id", -1))
  2002. if tray_id < 0 or not tray.get("tray_type"):
  2003. continue
  2004. current_idx = tray.get("cali_idx")
  2005. profile = await find_slot_kprofile_for_extruder(
  2006. db,
  2007. printer_id,
  2008. ams_id,
  2009. tray_id,
  2010. target_extruder,
  2011. nozzle_diameter,
  2012. printer_manager.get_model(printer_id),
  2013. nozzle_flow_for_extruder(state, target_extruder, printer_manager.get_model(printer_id)),
  2014. )
  2015. if profile is None or profile.cali_idx is None:
  2016. continue
  2017. if current_idx == profile.cali_idx:
  2018. continue # Already on the right one.
  2019. logger.info(
  2020. "[Printer %s] AMS %s slot %s moved to inlet %s (nozzle %s): "
  2021. "re-selecting K-profile %s (cali_idx %s -> %s, K=%s)",
  2022. printer_id,
  2023. ams_id,
  2024. tray_id,
  2025. inlet,
  2026. target_extruder,
  2027. profile.name,
  2028. current_idx,
  2029. profile.cali_idx,
  2030. profile.k_value,
  2031. )
  2032. client.extrusion_cali_sel(
  2033. ams_id=ams_id,
  2034. tray_id=tray_id,
  2035. cali_idx=profile.cali_idx,
  2036. filament_id=printer_safe_filament_id(profile.filament_id, tray.get("tray_info_idx", "")),
  2037. nozzle_diameter=nozzle_diameter,
  2038. )
  2039. except Exception as e:
  2040. logger.warning("[Printer %s] Could not re-apply K-profiles after inlet move: %s", printer_id, e)
  2041. async def _unlink_stale_assignments(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2042. """Unlink built-in inventory assignments whose slot no longer holds their spool.
  2043. Runs from ``on_ams_change`` and, for removals held by ``slot_unlink_grace``,
  2044. from the delayed re-check -- which is why it takes the AMS data and print
  2045. state as arguments instead of reading them from the push (#3186).
  2046. """
  2047. logger = logging.getLogger(__name__)
  2048. from backend.app.utils.color_utils import colors_similar as _colors_similar
  2049. # Auto-unlink spool assignments with stale fingerprints. Under the
  2050. # per-printer assignment lock since #3186: the held-removal re-check runs
  2051. # this outside any MQTT push, so it can now overlap one.
  2052. try:
  2053. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2054. from sqlalchemy.orm import selectinload
  2055. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2056. from backend.app.models.spool import Spool as _Spool
  2057. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2058. from backend.app.services.ams_slot_presence import spool_present
  2059. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2060. # Built-in assignments only. Since #2812 they survive a switch to
  2061. # Spoolman mode rather than being deleted by it, and this pass ends
  2062. # in ``db.delete`` — left ungated it would unlink them one slot at a
  2063. # time as the AMS contents changed under the other mode, undoing the
  2064. # preservation more slowly but just as completely.
  2065. assignments = []
  2066. if not await spoolman_owns_assignments(db):
  2067. result = await db.execute(
  2068. select(SA)
  2069. .where(SA.printer_id == printer_id)
  2070. .options(selectinload(SA.spool).selectinload(_Spool.k_profiles))
  2071. )
  2072. assignments = result.scalars().all()
  2073. # ``printing_now`` (top of this function) keeps a runout from
  2074. # unlinking the spool that fed the print — the next idle-time pass
  2075. # unlinks it if the user really did take it out.
  2076. stale = []
  2077. # Removals this pass is holding rather than unlinking (#3186).
  2078. held: set[tuple] = set()
  2079. for assignment in assignments:
  2080. # External spool assignments (ams_id=255) live in vt_tray, not AMS data
  2081. if assignment.ams_id == 255:
  2082. ps = printer_manager.get_status(printer_id)
  2083. vt_tray_raw = ps.raw_data.get("vt_tray", []) if ps else []
  2084. ext_id = assignment.tray_id + 254 # 0→254, 1→255
  2085. current_tray = None
  2086. for vt in vt_tray_raw:
  2087. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2088. current_tray = vt
  2089. break
  2090. if not current_tray:
  2091. # vt_tray data may not have arrived yet — keep assignment
  2092. continue
  2093. else:
  2094. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  2095. if not current_tray:
  2096. if printing_now:
  2097. logger.info(
  2098. "Auto-unlink skipped: spool %d AMS%d-T%d — slot empty during a running print (runout?)",
  2099. assignment.spool_id,
  2100. assignment.ams_id,
  2101. assignment.tray_id,
  2102. )
  2103. continue
  2104. # A whole AMS unit can drop out of one push and come back in
  2105. # the next; only a slot that stays gone is a removal (#3186).
  2106. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2107. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2108. held.add(hold_key)
  2109. logger.info(
  2110. "Auto-unlink held: spool %d AMS%d-T%d — tray not found in AMS data; "
  2111. "unlinking if it is still gone in %ds",
  2112. assignment.spool_id,
  2113. assignment.ams_id,
  2114. assignment.tray_id,
  2115. int(slot_unlink_grace.GRACE_SECONDS),
  2116. )
  2117. continue
  2118. logger.info(
  2119. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  2120. assignment.spool_id,
  2121. assignment.ams_id,
  2122. assignment.tray_id,
  2123. )
  2124. stale.append(assignment) # Slot empty
  2125. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  2126. # A Bambu Lab spool is in this slot — check if it's the same spool
  2127. # that's currently assigned. If yes, keep the assignment (avoids
  2128. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  2129. # the printer's filament preset on every startup).
  2130. tray_uuid = current_tray.get("tray_uuid", "")
  2131. tag_uid = current_tray.get("tag_uid", "")
  2132. spool = assignment.spool
  2133. spool_matches = False
  2134. if spool:
  2135. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  2136. spool.tag_uid
  2137. and tag_uid
  2138. and tag_uid != "0000000000000000"
  2139. and spool.tag_uid.upper() == tag_uid.upper()
  2140. ):
  2141. spool_matches = True
  2142. if spool_matches:
  2143. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  2144. cur_color = current_tray.get("tray_color", "")
  2145. cur_type = current_tray.get("tray_type", "")
  2146. fp_color = assignment.fingerprint_color or ""
  2147. fp_type = assignment.fingerprint_type or ""
  2148. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  2149. assignment.fingerprint_color = cur_color
  2150. assignment.fingerprint_type = cur_type
  2151. logger.debug(
  2152. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  2153. assignment.spool_id,
  2154. assignment.ams_id,
  2155. assignment.tray_id,
  2156. )
  2157. continue
  2158. # Different BL spool or unrecognized — unlink so auto-assign can match
  2159. logger.info(
  2160. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  2161. assignment.spool_id,
  2162. assignment.ams_id,
  2163. assignment.tray_id,
  2164. tray_uuid,
  2165. )
  2166. stale.append(assignment)
  2167. else:
  2168. cur_color = current_tray.get("tray_color", "")
  2169. cur_type = current_tray.get("tray_type", "")
  2170. cur_state = current_tray.get("state")
  2171. fp_color = assignment.fingerprint_color or ""
  2172. fp_type = assignment.fingerprint_type or ""
  2173. # SpoolBuddy pre-config replay: fingerprint_type empty means
  2174. # the slot was empty when the user pre-assigned via SpoolBuddy
  2175. # (the firmware drops ams_filament_setting on empty slots, so
  2176. # MQTT was deferred). The moment any filament gets inserted
  2177. # — Bambu RFID, 3rd-party, or even an existing-but-now-
  2178. # reconfigured spool — fire the deferred configuration.
  2179. # The "loaded" signal is state == 11 (Bambu's "filament fed to
  2180. # extruder" code) OR, on firmwares that don't use the state
  2181. # enum meaningfully, a non-empty tray_type when state is
  2182. # NOT one of the firmware's explicit empty signals (9, 10).
  2183. # state-only was wrong for firmwares that never set 11 — A1
  2184. # Mini BMCU 01.07.02.00 and P1S Standard AMS 00.00.06.75 both
  2185. # always report state=3 — so the replay never fired for them
  2186. # (#1322). The state ∉ {9,10} guard keeps the firmware's
  2187. # explicit "empty" signals authoritative over any stale
  2188. # tray_type that might survive the relay's auto-clearing.
  2189. #
  2190. # tray_exist_bits comes first because that guard cannot tell
  2191. # a firmware "empty" from Bambuddy's own: apply_tray_exist_bits
  2192. # writes state=9 when the bit is 0 and leaves it there when the
  2193. # bit returns. A non-RFID spool inserted into a pre-assigned
  2194. # slot brings no tray_type with it, so the stale 9 made this
  2195. # expression false forever and the deferred config never fired
  2196. # — the deadlock #1322 removed from the assign path, still in
  2197. # place here (#3084, #3100).
  2198. loaded = spool_present(current_tray) is True or (
  2199. cur_state == 11 or (cur_state not in (9, 10) and cur_type.strip())
  2200. )
  2201. if not fp_type.strip() and loaded and assignment.spool:
  2202. try:
  2203. from backend.app.api.routes.inventory import (
  2204. apply_spool_to_slot_via_mqtt,
  2205. )
  2206. await apply_spool_to_slot_via_mqtt(
  2207. db=db,
  2208. current_user=None,
  2209. spool=assignment.spool,
  2210. printer_id=printer_id,
  2211. ams_id=assignment.ams_id,
  2212. tray_id=assignment.tray_id,
  2213. current_tray_info_idx=current_tray.get("tray_info_idx", ""),
  2214. current_tray_type=cur_type,
  2215. )
  2216. logger.info(
  2217. "SpoolBuddy pre-config applied on insert: spool %d → printer %d AMS%d-T%d",
  2218. assignment.spool_id,
  2219. printer_id,
  2220. assignment.ams_id,
  2221. assignment.tray_id,
  2222. )
  2223. except Exception:
  2224. logger.exception(
  2225. "Pre-config apply failed for spool %d on printer %d AMS%d-T%d",
  2226. assignment.spool_id,
  2227. printer_id,
  2228. assignment.ams_id,
  2229. assignment.tray_id,
  2230. )
  2231. assignment.fingerprint_color = cur_color
  2232. assignment.fingerprint_type = cur_type
  2233. continue
  2234. if not _colors_similar(cur_color, fp_color) or cur_type.upper() != fp_type.upper():
  2235. # Blank tray data mid-print is a runout, not a swap: the
  2236. # firmware clears colour and type when it unloads a spool
  2237. # it just emptied. Unlinking here would erase the record
  2238. # of which spool fed the print so far.
  2239. if printing_now and not cur_color.strip() and not cur_type.strip():
  2240. logger.info(
  2241. "Auto-unlink skipped: spool %d AMS%d-T%d — tray data cleared during a running print "
  2242. "(runout?)",
  2243. assignment.spool_id,
  2244. assignment.ams_id,
  2245. assignment.tray_id,
  2246. )
  2247. continue
  2248. # Same reasoning off the print, on firmware's own say-so:
  2249. # a blank tray report from a slot whose tray_exist_bits
  2250. # bit is set describes a spool the AMS cannot identify —
  2251. # a non-RFID one, or one whose slot was reset — not a
  2252. # spool that was taken out. Deleting the assignment there
  2253. # threw away the identity the user had supplied, which is
  2254. # the only place it existed (#3100). A slot the bit calls
  2255. # empty, or one that carries no bit at all, still unlinks.
  2256. #
  2257. # Unless the slot was reported empty first: a removal
  2258. # already held means a spool came out and another went
  2259. # in, so the blank report keeps the hold running below
  2260. # rather than cancelling it (#3186).
  2261. if (
  2262. spool_present(current_tray) is True
  2263. and not cur_color.strip()
  2264. and not cur_type.strip()
  2265. and not slot_unlink_grace.is_held(
  2266. printer_id,
  2267. ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id),
  2268. )
  2269. ):
  2270. logger.info(
  2271. "Auto-unlink skipped: spool %d AMS%d-T%d — slot still occupied, "
  2272. "tray reports no filament data yet",
  2273. assignment.spool_id,
  2274. assignment.ams_id,
  2275. assignment.tray_id,
  2276. )
  2277. continue
  2278. # A blank report the presence bit does not vouch for is
  2279. # still only one push. An idle X1C cleared a whole AMS
  2280. # unit's bits, colour and type for a moment and lost
  2281. # four saved assignments that way (#3186); unlink only
  2282. # if the slot is still blank after the grace period.
  2283. if not cur_color.strip() and not cur_type.strip():
  2284. hold_key = ("inventory", assignment.ams_id, assignment.tray_id, assignment.spool_id)
  2285. if not slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2286. held.add(hold_key)
  2287. logger.info(
  2288. "Auto-unlink held: spool %d AMS%d-T%d — tray reports no filament data; "
  2289. "unlinking if it is still blank in %ds",
  2290. assignment.spool_id,
  2291. assignment.ams_id,
  2292. assignment.tray_id,
  2293. int(slot_unlink_grace.GRACE_SECONDS),
  2294. )
  2295. continue
  2296. # Fingerprint mismatch — but check if tray now matches the
  2297. # assigned spool (e.g. auto-configure changed the tray).
  2298. # Both sides are reduced to the type the slot can carry
  2299. # before comparing: the assign path writes that rather
  2300. # than the spool's raw material (#2902), so a spool whose
  2301. # material is a product line — "PLA+", "HTPLA" — reports
  2302. # back as "PLA" and would otherwise fail this check and
  2303. # be auto-unlinked from the slot it was just assigned to.
  2304. # Reducing the printer's side too keeps slots configured
  2305. # by an older Bambuddy, still reporting "PLA+", matching.
  2306. spool = assignment.spool
  2307. if spool:
  2308. spool_color = (spool.rgba or "FFFFFFFF").upper()
  2309. # Two ways the assign path can have arrived at the
  2310. # slot's type, so both count as "we wrote this".
  2311. # The material column is one; the spool's preset is
  2312. # the other, and it outranks the material when the
  2313. # spool has one -- a spool whose material says PLA
  2314. # and whose preset is "Bambu PLA Aero" puts
  2315. # PLA-AERO in the slot (#2902). Read from the stored
  2316. # preset name rather than resolving the preset,
  2317. # because this runs on every AMS push and a cloud
  2318. # lookup here would be both slow and unavailable on
  2319. # the unauthenticated replay path.
  2320. spool_types = {printer_filament_type(spool.material).upper()}
  2321. if spool.slicer_filament_name:
  2322. spool_types.add(printer_filament_type(spool.slicer_filament_name).upper())
  2323. # An imported local preset stores its type outright,
  2324. # which is what the assign path used -- and the name
  2325. # above may be unset. One keyed read, and only on a
  2326. # mismatch, which is rare.
  2327. #
  2328. # slicer_filament is free text up to fifty characters,
  2329. # so the digits have to be checked against the range
  2330. # of the integer primary key they are about to be
  2331. # compared with. Postgres raises on an out-of-range
  2332. # integer rather than simply not matching, and that
  2333. # would poison this session and abandon the rest of
  2334. # the cleanup pass.
  2335. lp_ref = (spool.slicer_filament or "").strip()
  2336. if lp_ref.isdigit() and int(lp_ref) <= 2147483647:
  2337. from backend.app.models.local_preset import LocalPreset as _LP
  2338. lp_type = await db.scalar(select(_LP.filament_type).where(_LP.id == int(lp_ref)))
  2339. if lp_type:
  2340. spool_types.add(printer_filament_type(lp_type).upper())
  2341. if (
  2342. _colors_similar(cur_color, spool_color)
  2343. and printer_filament_type(cur_type).upper() in spool_types
  2344. ):
  2345. logger.info(
  2346. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  2347. assignment.spool_id,
  2348. assignment.ams_id,
  2349. assignment.tray_id,
  2350. )
  2351. assignment.fingerprint_color = cur_color
  2352. assignment.fingerprint_type = cur_type
  2353. continue
  2354. logger.info(
  2355. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  2356. assignment.spool_id,
  2357. assignment.ams_id,
  2358. assignment.tray_id,
  2359. cur_color,
  2360. cur_type,
  2361. fp_color,
  2362. fp_type,
  2363. spool.rgba if spool else "?",
  2364. spool.material if spool else "?",
  2365. )
  2366. stale.append(assignment) # Spool changed
  2367. slot_unlink_grace.settle(printer_id, "inventory", held)
  2368. # Snapshot slots before delete — ORM attribute access after the
  2369. # commit would refresh against a deleted row.
  2370. unlinked_slots = [(a.ams_id, a.tray_id) for a in stale]
  2371. for a in stale:
  2372. await db.delete(a)
  2373. if stale:
  2374. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  2375. # Commit any changes (stale deletions and/or fingerprint updates)
  2376. await db.commit()
  2377. # Tell open browsers the assignment is gone (#2575). Only the manual
  2378. # REST assign/unassign endpoints broadcast this event; without it the
  2379. # frontend's spool-assignments cache keeps rendering the unlinked
  2380. # spool on the slot until an unrelated refetch — which reads exactly
  2381. # like "the fix didn't work" (reporter verified: a browser refresh
  2382. # after the swap showed the correct state all along).
  2383. for ams_id, tray_id in unlinked_slots:
  2384. await ws_manager.broadcast(
  2385. {
  2386. "type": "spool_assignment_changed",
  2387. "printer_id": printer_id,
  2388. "ams_id": ams_id,
  2389. "tray_id": tray_id,
  2390. }
  2391. )
  2392. except Exception as e:
  2393. logger.warning("Spool assignment cleanup failed: %s", e, exc_info=True)
  2394. async def _expire_spoolman_empty_slots(printer_id: int, ams_data: list, printing_now: bool) -> None:
  2395. """Delete Spoolman slot rows whose held removal has run its grace period.
  2396. The Spoolman half of the #3186 re-check. The full sync in ``on_ams_change``
  2397. talks to Spoolman for every tray; this only needs the local rows, so it
  2398. repeats that pass's empty-slot decision -- a tray with no type or no colour
  2399. (``parse_ams_tray`` returns None for exactly those), not during a print, and
  2400. not in a slot the presence bit calls occupied -- and nothing else.
  2401. """
  2402. logger = logging.getLogger(__name__)
  2403. try:
  2404. async with async_session() as db:
  2405. from backend.app.api.routes.settings import get_setting
  2406. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2407. from backend.app.services.ams_slot_presence import spool_present
  2408. enabled = await get_setting(db, "spoolman_enabled")
  2409. if not enabled or enabled.lower() != "true":
  2410. return
  2411. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2412. if sync_mode and sync_mode != "auto":
  2413. return
  2414. trays: dict[tuple[int, int], dict] = {}
  2415. for ams_unit in ams_data or []:
  2416. if not isinstance(ams_unit, dict):
  2417. continue
  2418. for tray in ams_unit.get("tray", []):
  2419. if isinstance(tray, dict):
  2420. trays[(int(ams_unit.get("id", 0)), int(tray.get("id", 0)))] = tray
  2421. rows = (
  2422. (
  2423. await db.execute(
  2424. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2425. )
  2426. )
  2427. .scalars()
  2428. .all()
  2429. )
  2430. held: set[tuple] = set()
  2431. expired: list[tuple[int, int]] = []
  2432. for row in rows:
  2433. tray = trays.get((row.ams_id, row.tray_id))
  2434. if tray is None or printing_now:
  2435. continue
  2436. if (tray.get("tray_type") or "").strip() and (tray.get("tray_color") or "").strip():
  2437. continue
  2438. hold_key = ("spoolman", row.ams_id, row.tray_id, row.spoolman_spool_id)
  2439. if spool_present(tray) is True and not slot_unlink_grace.is_held(printer_id, hold_key):
  2440. continue
  2441. if slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2442. expired.append((row.ams_id, row.tray_id))
  2443. else:
  2444. held.add(hold_key)
  2445. slot_unlink_grace.settle(printer_id, "spoolman", held)
  2446. if not expired:
  2447. return
  2448. # A statement rather than ORM deletes, like the sync pass: the two
  2449. # can overlap, and a row the other already removed must not fail
  2450. # this commit.
  2451. for ams_id, tray_id in expired:
  2452. await db.execute(
  2453. delete(SpoolmanSlotAssignment).where(
  2454. SpoolmanSlotAssignment.printer_id == printer_id,
  2455. SpoolmanSlotAssignment.ams_id == ams_id,
  2456. SpoolmanSlotAssignment.tray_id == tray_id,
  2457. )
  2458. )
  2459. await db.commit()
  2460. logger.info("Unlinked %d Spoolman slot(s) that stayed empty for printer %d", len(expired), printer_id)
  2461. for ams_id, tray_id in expired:
  2462. await ws_manager.broadcast(
  2463. {
  2464. "type": "spool_assignment_changed",
  2465. "printer_id": printer_id,
  2466. "ams_id": ams_id,
  2467. "tray_id": tray_id,
  2468. }
  2469. )
  2470. except Exception as e:
  2471. logger.warning("Spoolman slot re-check failed for printer %s: %s", printer_id, e, exc_info=True)
  2472. async def _recheck_held_unlinks(printer_id: int) -> None:
  2473. """Re-run just the slot cleanup against the printer's current AMS state.
  2474. Scheduled by ``slot_unlink_grace`` when it holds a removal. The unlink
  2475. passes otherwise run only when the AMS hash changes, and a slot that went
  2476. empty and stayed empty may never change it again.
  2477. """
  2478. status = printer_manager.get_status(printer_id)
  2479. # A disconnected printer's state is its last report, not a new one: acting
  2480. # on it would "confirm" a removal nobody has seen for the whole grace
  2481. # period. Leave the holds; the first push after reconnecting decides.
  2482. if status is None or not status.connected:
  2483. return
  2484. ams_raw = status.raw_data.get("ams")
  2485. ams_data = ams_raw.get("ams", []) if isinstance(ams_raw, dict) else ams_raw if isinstance(ams_raw, list) else []
  2486. printing_now = (getattr(status, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2487. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2488. await _expire_spoolman_empty_slots(printer_id, ams_data, printing_now)
  2489. slot_unlink_grace.set_recheck(_recheck_held_unlinks)
  2490. async def on_ams_change(printer_id: int, ams_data: list):
  2491. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  2492. logger = logging.getLogger(__name__)
  2493. # Snapshot BEFORE any await: if a print is active, skip weight sync later.
  2494. # on_print_complete may pop _active_sessions during our awaits (#880).
  2495. from backend.app.services.usage_tracker import _active_sessions
  2496. _print_active = printer_id in _active_sessions
  2497. # A slot that reports empty while a print is running is a filament runout,
  2498. # not a spool swap: the spool is still physically in the AMS, just
  2499. # consumed. Dropping either inventory backend's slot link there loses the
  2500. # only record of which spool fed the print, so the completion path can't
  2501. # charge the runout segment to anything. Both cleanup passes below consult
  2502. # this; computed once, up front, so neither depends on the other having run.
  2503. _unlink_state = printer_manager.get_status(printer_id)
  2504. printing_now = (getattr(_unlink_state, "state", "") or "").upper() in ("RUNNING", "PAUSE")
  2505. # The session alone is not enough: a restart that finds a stale persisted
  2506. # session registers none for the print that is running.
  2507. _print_active = _print_active or printing_now
  2508. # MQTT relay - publish AMS change
  2509. try:
  2510. printer_info = printer_manager.get_printer(printer_id)
  2511. if printer_info:
  2512. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  2513. except Exception:
  2514. pass # Don't fail AMS callback if MQTT fails
  2515. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  2516. # This ensures frontend gets immediate updates when AMS slots are configured
  2517. try:
  2518. state = printer_manager.get_status(printer_id)
  2519. if state:
  2520. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  2521. await ws_manager.send_printer_status(
  2522. printer_id,
  2523. printer_state_to_dict(
  2524. state,
  2525. printer_id,
  2526. printer_manager.get_model(printer_id),
  2527. printer_manager.get_drying_targets(printer_id),
  2528. ),
  2529. )
  2530. except Exception as e:
  2531. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  2532. await _unlink_stale_assignments(printer_id, ams_data, printing_now)
  2533. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS).
  2534. # Serialised per-printer via _ams_assignment_locks: MQTT bursts can deliver
  2535. # two AMS pushes ~30 ms apart, and without the lock both callbacks read
  2536. # "no existing assignment" for the same (printer, ams, tray) and race to
  2537. # INSERT, hitting the spool_assignment_printer_id_ams_id_tray_id_key
  2538. # unique constraint on Postgres. SQLite's WAL serialises writes so the
  2539. # bug stayed latent there. See _ams_assignment_locks comment for details.
  2540. try:
  2541. async with _get_ams_assignment_lock(printer_id), async_session() as db:
  2542. from sqlalchemy.orm import selectinload
  2543. from backend.app.api.routes.settings import get_setting
  2544. from backend.app.models.spool import Spool
  2545. from backend.app.models.spool_assignment import SpoolAssignment as SA
  2546. from backend.app.services.spool_tag_matcher import (
  2547. auto_assign_spool,
  2548. create_spool_from_tray,
  2549. find_matching_untagged_spool,
  2550. get_spool_by_tag,
  2551. is_bambu_tag,
  2552. is_valid_tag,
  2553. link_tag_to_inventory_spool,
  2554. tag_belongs_to_archived_spool,
  2555. )
  2556. _spoolman_on = await get_setting(db, "spoolman_enabled")
  2557. _auto_add_raw = await get_setting(db, "auto_add_unknown_rfid")
  2558. _auto_add_unknown = _auto_add_raw is None or _auto_add_raw.lower() == "true"
  2559. if not _spoolman_on or _spoolman_on.lower() != "true":
  2560. for ams_unit in ams_data:
  2561. if not isinstance(ams_unit, dict):
  2562. continue
  2563. ams_id = int(ams_unit.get("id", 0))
  2564. for tray in ams_unit.get("tray", []):
  2565. if not isinstance(tray, dict):
  2566. continue
  2567. tray_id = int(tray.get("id", 0))
  2568. tag_uid = tray.get("tag_uid", "")
  2569. tray_uuid = tray.get("tray_uuid", "")
  2570. tray_info_idx = tray.get("tray_info_idx", "")
  2571. if not tray.get("tray_type"):
  2572. # Slot reported empty — drop any cached unknown-tag
  2573. # broadcast so reinserting the same spool re-prompts.
  2574. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2575. continue # Empty slot
  2576. # Check if assignment already exists for this slot
  2577. existing = await db.execute(
  2578. select(SA)
  2579. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  2580. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  2581. )
  2582. existing_assignment = existing.scalar_one_or_none()
  2583. if existing_assignment:
  2584. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  2585. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  2586. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  2587. # Skip during active prints: the usage tracker handles deduction
  2588. # precisely via 3MF data on print completion. Without this guard the
  2589. # AMS remain% SET and the usage tracker ADD both fire from the same
  2590. # MQTT message, doubling the deduction (#880).
  2591. if _print_active:
  2592. continue
  2593. remain_raw = tray.get("remain")
  2594. if (
  2595. remain_raw is not None
  2596. and existing_assignment.spool
  2597. and not existing_assignment.spool.weight_locked
  2598. ):
  2599. try:
  2600. remain_val = int(remain_raw)
  2601. except (TypeError, ValueError):
  2602. remain_val = -1
  2603. if 1 <= remain_val <= 100:
  2604. lw = existing_assignment.spool.label_weight or 1000
  2605. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  2606. current_used = existing_assignment.spool.weight_used or 0
  2607. if new_used > current_used + 1:
  2608. logger.info(
  2609. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  2610. existing_assignment.spool_id,
  2611. current_used,
  2612. new_used,
  2613. remain_val,
  2614. )
  2615. existing_assignment.spool.weight_used = new_used
  2616. await db.commit()
  2617. # Re-apply stored K-profile when the live tray's
  2618. # cali_idx drifted from the spool's stored profile.
  2619. # This catches "reset slot → re-read" and any other
  2620. # path where the firmware loses the user's K-profile
  2621. # selection while the SpoolAssignment row persists.
  2622. # Per the maintainer's rule: any time a spool tag is
  2623. # identified and matches inventory, the slot must be
  2624. # configured with the spool's stored settings. Without
  2625. # this block the existing-assignment branch only ran
  2626. # weight-sync and let the firmware-default cali_idx win.
  2627. try:
  2628. spool = existing_assignment.spool
  2629. if (
  2630. spool is not None
  2631. and is_bambu_tag(tag_uid, tray_uuid, tray_info_idx)
  2632. and spool.k_profiles
  2633. ):
  2634. state = printer_manager.get_status(printer_id)
  2635. slot_nozzle = resolve_slot_nozzle(
  2636. state, ams_id, tray_id, printer_manager.get_model(printer_id)
  2637. )
  2638. nozzle_diameter = slot_nozzle.diameter
  2639. slot_extruder = slot_nozzle.extruder
  2640. # Prefer exact extruder match, fall back to
  2641. # extruder-agnostic kp for the same printer +
  2642. # nozzle. Avoids hard-skipping when the AMS is
  2643. # mapped differently than at calibration time.
  2644. matching_kp = None
  2645. fallback_kp = None
  2646. for kp in spool.k_profiles:
  2647. if (
  2648. kp.printer_id != printer_id
  2649. or kp.nozzle_diameter != nozzle_diameter
  2650. or kp.cali_idx is None
  2651. or not slot_nozzle.flow_matches(kp.nozzle_type)
  2652. ):
  2653. continue
  2654. if (
  2655. slot_extruder is not None
  2656. and kp.extruder is not None
  2657. and kp.extruder == slot_extruder
  2658. ):
  2659. matching_kp = kp
  2660. break
  2661. if fallback_kp is None:
  2662. fallback_kp = kp
  2663. chosen_kp = matching_kp or fallback_kp
  2664. if chosen_kp is not None:
  2665. live_cali_idx = tray.get("cali_idx")
  2666. # Only fire MQTT when the printer's live
  2667. # cali_idx differs from the stored value.
  2668. # Avoids spamming the broker on every
  2669. # MQTT push during steady-state operation.
  2670. if live_cali_idx != chosen_kp.cali_idx:
  2671. client = printer_manager.get_client(printer_id)
  2672. if client:
  2673. cali_filament_id = spool.slicer_filament or tray_info_idx or ""
  2674. client.extrusion_cali_sel(
  2675. ams_id=ams_id,
  2676. tray_id=tray_id,
  2677. cali_idx=chosen_kp.cali_idx,
  2678. filament_id=cali_filament_id,
  2679. nozzle_diameter=nozzle_diameter,
  2680. )
  2681. logger.info(
  2682. "Re-applied K-profile cali_idx=%d for spool %d "
  2683. "on printer %d AMS%d-T%d (live=%s drift detected)",
  2684. chosen_kp.cali_idx,
  2685. spool.id,
  2686. printer_id,
  2687. ams_id,
  2688. tray_id,
  2689. live_cali_idx,
  2690. )
  2691. except Exception:
  2692. logger.exception(
  2693. "K-profile re-apply failed for printer %d AMS%d-T%d",
  2694. printer_id,
  2695. ams_id,
  2696. tray_id,
  2697. )
  2698. continue
  2699. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  2700. # BL spool with RFID tag: auto-match → inventory match → auto-create
  2701. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  2702. if not spool and await tag_belongs_to_archived_spool(db, tag_uid, tray_uuid):
  2703. # An archived spool still in the AMS: the slot
  2704. # stays free rather than adopting its tag.
  2705. continue
  2706. if not spool:
  2707. # Try matching an untagged inventory spool (same material/color)
  2708. spool = await find_matching_untagged_spool(db, tray)
  2709. if spool:
  2710. await link_tag_to_inventory_spool(db, spool, tray)
  2711. elif _auto_add_unknown:
  2712. spool = await create_spool_from_tray(db, tray)
  2713. else:
  2714. # Auto-add disabled: surface the slot so the
  2715. # user can add it manually via the UI.
  2716. await _broadcast_unknown_tag(
  2717. printer_id=printer_id,
  2718. ams_id=ams_id,
  2719. tray_id=tray_id,
  2720. tag_uid=tag_uid,
  2721. tray_uuid=tray_uuid,
  2722. tray_type=tray.get("tray_type"),
  2723. tray_color=tray.get("tray_color"),
  2724. tray_sub_brands=tray.get("tray_sub_brands"),
  2725. tray_count=len(ams_unit.get("tray", [])),
  2726. )
  2727. continue
  2728. # Slot matched (existing tag, untagged inventory
  2729. # match, or freshly auto-created spool) — drop any
  2730. # stale dedup so a future tag swap re-prompts.
  2731. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id)
  2732. await auto_assign_spool(
  2733. printer_id,
  2734. ams_id,
  2735. tray_id,
  2736. spool,
  2737. printer_manager,
  2738. db,
  2739. tray_info_idx=tray_info_idx,
  2740. )
  2741. await db.commit()
  2742. await ws_manager.broadcast(
  2743. {
  2744. "type": "spool_auto_assigned",
  2745. "printer_id": printer_id,
  2746. "ams_id": ams_id,
  2747. "tray_id": tray_id,
  2748. "spool_id": spool.id,
  2749. }
  2750. )
  2751. logger.info(
  2752. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  2753. spool.id,
  2754. printer_id,
  2755. ams_id,
  2756. tray_id,
  2757. )
  2758. elif is_valid_tag(tag_uid, tray_uuid) and not await tag_belongs_to_archived_spool(
  2759. db, tag_uid, tray_uuid
  2760. ):
  2761. # Non-BL spool with some tag — let user choose (not
  2762. # an archived one's, whose slot stays free)
  2763. await _broadcast_unknown_tag(
  2764. printer_id=printer_id,
  2765. ams_id=ams_id,
  2766. tray_id=tray_id,
  2767. tag_uid=tag_uid,
  2768. tray_uuid=tray_uuid,
  2769. tray_type=tray.get("tray_type"),
  2770. tray_color=tray.get("tray_color"),
  2771. tray_sub_brands=tray.get("tray_sub_brands"),
  2772. tray_count=len(ams_unit.get("tray", [])),
  2773. )
  2774. # No-tag slots (generic non-RFID filament) are left alone:
  2775. # nothing to identify, prompting "+ Add" would just create
  2776. # ghost spools with empty tags on every confirm.
  2777. except Exception as e:
  2778. logger.warning("RFID spool auto-assign failed: %s", e, exc_info=True)
  2779. try:
  2780. async with async_session() as db:
  2781. from backend.app.api.routes.settings import get_setting
  2782. from backend.app.models.printer import Printer
  2783. # Check if Spoolman is enabled
  2784. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2785. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  2786. return
  2787. # Check sync mode
  2788. sync_mode = await get_setting(db, "spoolman_sync_mode")
  2789. if sync_mode and sync_mode != "auto":
  2790. return # Only sync on auto mode
  2791. _auto_add_raw_sm = await get_setting(db, "auto_add_unknown_rfid")
  2792. auto_add_unknown_rfid = _auto_add_raw_sm is None or _auto_add_raw_sm.lower() == "true"
  2793. # `spoolman_disable_weight_sync` is deprecated (#1119) — weight is now
  2794. # always owned by per-print tracking, never by AMS auto-sync. The
  2795. # setting is still read by the settings UI for backwards compat but
  2796. # has no effect on the sync path here.
  2797. # Get Spoolman URL
  2798. spoolman_url = await get_setting(db, "spoolman_url")
  2799. if not spoolman_url:
  2800. return
  2801. # Get or create Spoolman client
  2802. client = await get_spoolman_client()
  2803. if not client:
  2804. try:
  2805. client = await init_spoolman_client(spoolman_url)
  2806. except ValueError as exc:
  2807. logger.warning("Spoolman URL %r rejected by SSRF guard: %s", spoolman_url, exc)
  2808. return
  2809. # Check if Spoolman is reachable
  2810. if not await client.health_check():
  2811. logger.warning("Spoolman not reachable at %s", spoolman_url)
  2812. return
  2813. # Get printer name for location
  2814. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2815. printer = result.scalar_one_or_none()
  2816. printer_name = printer.name if printer else f"Printer {printer_id}"
  2817. # OPTIMIZATION: Fetch all spools once before processing trays
  2818. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  2819. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  2820. try:
  2821. cached_spools = await client.get_spools()
  2822. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  2823. except Exception as e:
  2824. logger.error(
  2825. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  2826. printer_id,
  2827. e,
  2828. )
  2829. return
  2830. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  2831. from sqlalchemy.orm import selectinload
  2832. from backend.app.models.spool_assignment import SpoolAssignment
  2833. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2834. from backend.app.services.ams_slot_presence import spool_present
  2835. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2836. # Built-in remaining weight, used by sync_ams_tray only when the
  2837. # firmware reports an unusable remain%/tray_weight for a slot.
  2838. #
  2839. # Left empty since #2812. This block runs in Spoolman mode only,
  2840. # and until then the built-in table was emptied on the switch, so
  2841. # there was never anything here to read and the fallback was inert.
  2842. # Preserving those rows makes it live again, and it is keyed by slot
  2843. # rather than by spool: after a mode switch the tray may well hold
  2844. # different filament, and ``create_spool`` writes ``remaining_weight``
  2845. # unconditionally, so a stale figure would be seeded into a brand new
  2846. # Spoolman spool. Deliberately kept inert rather than deleted, so the
  2847. # intent survives for whoever revisits the cross-mode fallback.
  2848. inventory_weights: dict[tuple[int, int], float] = {}
  2849. if not await spoolman_owns_assignments(db):
  2850. try:
  2851. assign_result = await db.execute(
  2852. select(SpoolAssignment)
  2853. .options(selectinload(SpoolAssignment.spool))
  2854. .where(SpoolAssignment.printer_id == printer_id)
  2855. )
  2856. for assignment in assign_result.scalars().all():
  2857. spool = assignment.spool
  2858. if spool and spool.label_weight > 0:
  2859. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  2860. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  2861. except Exception as e:
  2862. logger.warning("Could not load inventory weights for printer %s: %s", printer_id, e)
  2863. # Load existing Spoolman slot assignments for the no-RFID fallback path
  2864. spoolman_slot_map: dict[tuple[int, int], int] = {}
  2865. try:
  2866. slot_result = await db.execute(
  2867. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2868. )
  2869. for slot in slot_result.scalars().all():
  2870. spoolman_slot_map[(slot.ams_id, slot.tray_id)] = slot.spoolman_spool_id
  2871. except Exception as e:
  2872. logger.warning("Could not load Spoolman slot assignments for printer %s: %s", printer_id, e)
  2873. # Sync each AMS tray and collect slot changes for DB persistence
  2874. synced = 0
  2875. slot_changes: list[tuple[int, int, int]] = [] # (ams_id, tray_id, spoolman_spool_id) to upsert
  2876. empty_slots: list[tuple[int, int]] = [] # (ams_id, tray_id) whose tray is now empty
  2877. spoolman_held: set[tuple] = set() # removals held for the grace period (#3186)
  2878. for ams_unit in ams_data:
  2879. if not isinstance(ams_unit, dict):
  2880. continue
  2881. ams_id = int(ams_unit.get("id", 0))
  2882. trays = ams_unit.get("tray", [])
  2883. for tray_data in trays:
  2884. if not isinstance(tray_data, dict):
  2885. continue
  2886. tray_id_raw = int(tray_data.get("id", 0))
  2887. tray = client.parse_ams_tray(ams_id, tray_data)
  2888. if not tray:
  2889. # Empty tray slot — record for local assignment cleanup
  2890. # and drop any cached unknown-tag broadcast so a
  2891. # reinserted spool re-prompts.
  2892. #
  2893. # Not during a running print: a slot that empties there
  2894. # is a filament runout, and the spool is still in the
  2895. # AMS. `spoolman_slot_assignments` is how a tag-less
  2896. # spool assigned through the Bambuddy UI is resolved at
  2897. # completion (#1459), so deleting the row mid-print
  2898. # loses the runout segment's usage — the same failure
  2899. # the internal inventory's auto-unlink had.
  2900. #
  2901. # Nor when firmware's presence bit says the slot is
  2902. # occupied. parse_ams_tray calls a tray with no type or
  2903. # no colour empty, and a spool the AMS cannot read has
  2904. # neither until something configures it — so a tag-less
  2905. # spool assigned through the UI had its row deleted by
  2906. # the first idle push after it was inserted. Same
  2907. # deletion as the internal inventory's in #3100, same
  2908. # answer, so the two modes stay in step.
  2909. #
  2910. # And only once the slot has stayed empty for the grace
  2911. # period -- the internal inventory's #3186 answer, for
  2912. # the same one-push blank.
  2913. linked_spool = spoolman_slot_map.get((ams_id, tray_id_raw))
  2914. hold_key = ("spoolman", ams_id, tray_id_raw, linked_spool)
  2915. if not printing_now and (
  2916. spool_present(tray_data) is not True or slot_unlink_grace.is_held(printer_id, hold_key)
  2917. ):
  2918. if linked_spool is None or slot_unlink_grace.removal_confirmed(printer_id, hold_key):
  2919. empty_slots.append((ams_id, tray_id_raw))
  2920. else:
  2921. spoolman_held.add(hold_key)
  2922. logger.info(
  2923. "Spoolman slot unlink held: AMS%d-T%d (spool %d) reports empty; "
  2924. "unlinking if it is still empty in %ds",
  2925. ams_id,
  2926. tray_id_raw,
  2927. linked_spool,
  2928. int(slot_unlink_grace.GRACE_SECONDS),
  2929. )
  2930. _clear_unknown_tag_dedup(printer_id, ams_id, tray_id_raw)
  2931. continue
  2932. spool_tag = (
  2933. tray.tray_uuid
  2934. if tray.tray_uuid and tray.tray_uuid != "00000000000000000000000000000000"
  2935. else tray.tag_uid
  2936. )
  2937. # Provide the hint only when no RFID is available
  2938. hint = spoolman_slot_map.get((ams_id, tray.tray_id)) if not spool_tag else None
  2939. try:
  2940. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  2941. result = await client.sync_ams_tray(
  2942. tray,
  2943. printer_name,
  2944. db,
  2945. # Per-print tracking is the only weight writer (#1119).
  2946. # AMS auto-sync still maintains spool metadata / slot
  2947. # assignments but no longer touches remaining_weight.
  2948. disable_weight_sync=True,
  2949. cached_spools=cached_spools,
  2950. inventory_remaining=inv_remaining,
  2951. spoolman_spool_id_hint=hint,
  2952. auto_add_unknown_rfid=auto_add_unknown_rfid,
  2953. )
  2954. if result is None and spool_tag and not auto_add_unknown_rfid:
  2955. # Spoolman skipped auto-create per user setting — surface
  2956. # the slot so the UI can offer "+ Add to inventory".
  2957. await _broadcast_unknown_tag(
  2958. printer_id=printer_id,
  2959. ams_id=ams_id,
  2960. tray_id=tray.tray_id,
  2961. tag_uid=tray.tag_uid or "",
  2962. tray_uuid=tray.tray_uuid or "",
  2963. tray_type=tray.tray_type,
  2964. tray_color=tray.tray_color,
  2965. tray_sub_brands=tray.tray_sub_brands,
  2966. tray_count=len(trays),
  2967. )
  2968. elif result:
  2969. _clear_unknown_tag_dedup(printer_id, ams_id, tray.tray_id)
  2970. if result:
  2971. synced += 1
  2972. if result.get("id"):
  2973. slot_changes.append((ams_id, tray.tray_id, result["id"]))
  2974. # If a new spool was created, add it to the cache
  2975. # so subsequent trays can find it if they reference the same tag
  2976. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  2977. if not spool_exists:
  2978. cached_spools.append(result)
  2979. logger.debug(
  2980. "[Printer %s] Added newly created spool %s to cache",
  2981. printer_id,
  2982. result["id"],
  2983. )
  2984. # Reconcile slot_preset_mappings (the same row internal
  2985. # mode keeps in sync via inventory + spool_tag_matcher).
  2986. # Without this the slot card surfaces the previous spool's
  2987. # preset name — same bug shape, different inventory mode.
  2988. from backend.app.services.slot_preset_writer import (
  2989. upsert_slot_preset_for_spoolman_spool,
  2990. )
  2991. await upsert_slot_preset_for_spoolman_spool(
  2992. db=db,
  2993. spoolman_spool=result,
  2994. tray_info_idx=tray.tray_info_idx or "",
  2995. tray_sub_brands=tray.tray_sub_brands or "",
  2996. tray_type=tray.tray_type or "",
  2997. printer_id=printer_id,
  2998. ams_id=ams_id,
  2999. tray_id=tray.tray_id,
  3000. )
  3001. except Exception as e:
  3002. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  3003. slot_unlink_grace.settle(printer_id, "spoolman", spoolman_held)
  3004. if synced > 0:
  3005. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  3006. # Persist slot assignment changes to the local table
  3007. if slot_changes or empty_slots:
  3008. try:
  3009. for ams_id, tray_id, spool_id in slot_changes:
  3010. await db.execute(
  3011. text(
  3012. "INSERT INTO spoolman_slot_assignments"
  3013. " (printer_id, ams_id, tray_id, spoolman_spool_id)"
  3014. " VALUES (:printer_id, :ams_id, :tray_id, :spool_id)"
  3015. " ON CONFLICT(printer_id, ams_id, tray_id)"
  3016. " DO UPDATE SET spoolman_spool_id = excluded.spoolman_spool_id"
  3017. ),
  3018. {
  3019. "printer_id": printer_id,
  3020. "ams_id": ams_id,
  3021. "tray_id": tray_id,
  3022. "spool_id": spool_id,
  3023. },
  3024. )
  3025. for ams_id, tray_id in empty_slots:
  3026. await db.execute(
  3027. delete(SpoolmanSlotAssignment).where(
  3028. SpoolmanSlotAssignment.printer_id == printer_id,
  3029. SpoolmanSlotAssignment.ams_id == ams_id,
  3030. SpoolmanSlotAssignment.tray_id == tray_id,
  3031. )
  3032. )
  3033. await db.commit()
  3034. except Exception as e:
  3035. await db.rollback()
  3036. logger.error("Error persisting Spoolman slot assignments for printer %s: %s", printer_id, e)
  3037. else:
  3038. # Tell open browsers the slot changed. This loop rewrites
  3039. # slot_preset_mappings via upsert_slot_preset_for_spoolman_spool
  3040. # above, and the AMS slot card reads that row ahead of the
  3041. # live tray_info_idx -- so with no event the card keeps
  3042. # showing the previous spool's preset name. Internal mode
  3043. # raises spool_auto_assigned for the same reason; this loop
  3044. # broadcast nothing at all, which made Spoolman mode the
  3045. # worse half of the same bug. On the else branch so a
  3046. # failed commit stays silent and a broadcast failure cannot
  3047. # roll back rows that are already committed.
  3048. for ams_id, tray_id, *_ in (*slot_changes, *empty_slots):
  3049. await ws_manager.broadcast(
  3050. {
  3051. "type": "spool_assignment_changed",
  3052. "printer_id": printer_id,
  3053. "ams_id": ams_id,
  3054. "tray_id": tray_id,
  3055. }
  3056. )
  3057. except Exception as e:
  3058. logging.getLogger(__name__).error("Spoolman AMS sync failed for printer %s: %s", printer_id, e)
  3059. # Largest finish photo attached to a notification; a bigger one is still linked.
  3060. _FINISH_PHOTO_ATTACH_MAX_BYTES = 2_500_000
  3061. async def _finish_photo_for_notification(
  3062. db, archive, archive_id: int, filename: str
  3063. ) -> tuple[str | None, bytes | None]:
  3064. """The ``{finish_photo_url}`` link and the bytes to attach, for a print's finish photo.
  3065. With authentication off the link is the archive's own photo route, as it
  3066. always was: it opens without a login and doesn't expire. With
  3067. authentication on that route needs a media token, which nothing tapping a
  3068. link in Telegram, CallMeBot or a Home Assistant notification has, so the
  3069. link only ever answered 401. The photo is then saved as a notification
  3070. photo as well (utils/notification_photos.py) and the link points there: an
  3071. unguessable name that opens this one photo and nothing else, for 3 days.
  3072. The link is relative when no External URL is set. Bytes over
  3073. ``_FINISH_PHOTO_ATTACH_MAX_BYTES`` are linked but not attached. Returns
  3074. ``(None, None)`` when the photo can't be found.
  3075. """
  3076. from backend.app.api.routes.settings import get_setting
  3077. from backend.app.core.auth import is_auth_enabled
  3078. from backend.app.utils.archive_paths import find_archive_photo
  3079. from backend.app.utils.notification_photos import save_notification_photo
  3080. log = logging.getLogger(__name__)
  3081. base = ((await get_setting(db, "external_url")) or "").strip().rstrip("/")
  3082. url: str | None = f"{base}/api/v1/archives/{archive_id}/photos/{filename}"
  3083. photo_bytes: bytes | None = None
  3084. try:
  3085. photo_path = find_archive_photo(archive, filename)
  3086. if photo_path is not None:
  3087. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  3088. except Exception as e:
  3089. log.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  3090. try:
  3091. auth_on = await is_auth_enabled(db)
  3092. except Exception:
  3093. auth_on = True # Unknown: the archive link may need a login, so don't rely on it.
  3094. if auth_on:
  3095. url = None
  3096. if photo_bytes:
  3097. try:
  3098. name = await asyncio.to_thread(save_notification_photo, photo_bytes, "print_complete")
  3099. url = f"{base}/api/v1/notifications/photos/{name}"
  3100. except Exception as e:
  3101. log.warning("[NOTIFY-BG] Failed to save finish photo for its link: %s", e)
  3102. if photo_bytes is not None and len(photo_bytes) > _FINISH_PHOTO_ATTACH_MAX_BYTES:
  3103. log.warning("[NOTIFY-BG] Finish photo too large for attachment: %s bytes", len(photo_bytes))
  3104. return url, None
  3105. if photo_bytes:
  3106. log.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  3107. return url, photo_bytes
  3108. async def _capture_snapshot_for_notification(printer_id: int, printer, logger, *, light: bool = True) -> bytes | None:
  3109. """Capture a camera snapshot for notification image attachment.
  3110. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  3111. Uses: external camera > buffered frame > fresh capture.
  3112. Turns the chamber light on for the picture when the printer asks for it
  3113. (#1655). ``light=False`` is for callers that capture all through a print,
  3114. where the light would flash with every frame.
  3115. """
  3116. if not printer:
  3117. return None
  3118. async with camera_light(printer if light else None):
  3119. return await _capture_snapshot_frame(printer_id, printer, logger)
  3120. async def _capture_snapshot_frame(printer_id: int, printer, logger) -> bytes | None:
  3121. """The capture behind ``_capture_snapshot_for_notification``."""
  3122. try:
  3123. from backend.app.api.routes.settings import get_setting
  3124. async with async_session() as db:
  3125. capture_enabled = await get_setting(db, "capture_finish_photo")
  3126. if capture_enabled is not None and capture_enabled.lower() != "true":
  3127. return None
  3128. # Try external camera first
  3129. if printer.external_camera_enabled and printer.external_camera_url:
  3130. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  3131. from backend.app.api.routes.camera import live_frame_for_capture
  3132. from backend.app.services.external_camera import capture_frame
  3133. # An external camera allows one reader, so capturing while a viewer
  3134. # is attached fails (#2707). A None here falls through to the paths
  3135. # below exactly as a failed capture did.
  3136. defer, buffered = live_frame_for_capture(printer_id)
  3137. if defer:
  3138. frame_data = buffered
  3139. else:
  3140. frame_data = await capture_frame(
  3141. printer.external_camera_url,
  3142. printer.external_camera_type or "mjpeg",
  3143. snapshot_url=printer.external_camera_snapshot_url,
  3144. )
  3145. if frame_data and len(frame_data) <= 2_500_000:
  3146. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  3147. return _apply_camera_rotation(frame_data, printer, logger)
  3148. # Try buffered frame from active stream
  3149. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  3150. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  3151. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  3152. buffered_frame = get_buffered_frame(printer_id)
  3153. if (active_for_printer or active_chamber) and buffered_frame:
  3154. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  3155. if len(buffered_frame) <= 2_500_000:
  3156. return _apply_camera_rotation(buffered_frame, printer, logger)
  3157. # Fresh capture from printer camera
  3158. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  3159. from backend.app.services.camera import capture_camera_frame_bytes
  3160. frame_data = await capture_camera_frame_bytes(
  3161. printer.ip_address, printer.access_code, printer.model, timeout=15
  3162. )
  3163. if frame_data and len(frame_data) <= 2_500_000:
  3164. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  3165. return _apply_camera_rotation(frame_data, printer, logger)
  3166. except Exception as e:
  3167. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  3168. return None
  3169. async def _maybe_bank_inprint_frame(printer_id: int, layer_num: int) -> None:
  3170. """#1867: bank a recent in-print camera frame for the finish photo.
  3171. Called on every layer change and (#2547) on every print-progress advance.
  3172. Grabs one frame (throttled) into ``_inprint_frame_bank`` so the finish-photo
  3173. path has a pre-End-G-code image for prints that end with a plate swap.
  3174. Both drivers are print telemetry that stops the instant printing ends: no
  3175. further layers, and progress freezes before the End G-code (e.g. SwapMod
  3176. plate swap) executes. So the last banked frame is always the finished print,
  3177. never the swapped plate — that property is what the #1867 path relies on and
  3178. it must survive any change to the throttle below.
  3179. Layer changes alone were not enough: they stop when the *final* layer
  3180. begins, which on a three-minute last layer left the bank stale by the whole
  3181. length of that layer (#2547). Progress keeps ticking through it.
  3182. Best-effort: any failure just leaves the previous banked frame.
  3183. """
  3184. logger = logging.getLogger(__name__)
  3185. client = printer_manager.get_client(printer_id)
  3186. state = client.state if client else None
  3187. if not state or state.state != "RUNNING":
  3188. return
  3189. # Only during actual extrusion — firmware ticks layer_num during the
  3190. # pre-print calibration sequence, whose sub-stages are non-zero.
  3191. if state.mc_print_sub_stage not in (None, 0):
  3192. return
  3193. # #2547: throttled uniformly, with no last-layer exemption. The old code
  3194. # bypassed the throttle on the final layer to guarantee a fresh frame there;
  3195. # now that progress advances also drive banking, that exemption would fire a
  3196. # camera grab on every percent tick of the last layer. Bambu printers accept
  3197. # one RTSP client at a time, so each grab contends with the live view.
  3198. now = time.monotonic()
  3199. last = _inprint_frame_bank_ts.get(printer_id, 0.0)
  3200. if (now - last) < _INPRINT_BANK_MIN_INTERVAL:
  3201. return
  3202. total = state.total_layers or 0
  3203. try:
  3204. async with async_session() as db:
  3205. from backend.app.models.printer import Printer
  3206. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3207. printer = result.scalar_one_or_none()
  3208. if not printer:
  3209. return
  3210. # Reuses the notification snapshot path, which honours the
  3211. # `capture_finish_photo` setting (returns None when disabled) so we
  3212. # don't bank frames the user never asked for. Without the chamber light
  3213. # (#1655): this runs every 25 seconds for the whole print.
  3214. frame = await _capture_snapshot_for_notification(printer_id, printer, logger, light=False)
  3215. if frame:
  3216. _inprint_frame_bank[printer_id] = frame
  3217. _inprint_frame_bank_ts[printer_id] = now
  3218. logger.debug(
  3219. "[FINISH-PHOTO-BANK] banked in-print frame for printer %s at layer %s/%s (%d bytes)",
  3220. printer_id,
  3221. layer_num,
  3222. total,
  3223. len(frame),
  3224. )
  3225. except Exception as e:
  3226. logger.debug("[FINISH-PHOTO-BANK] bank failed for printer %s: %s", printer_id, e)
  3227. def _apply_camera_rotation(image_data: bytes, printer, logger) -> bytes:
  3228. """Apply camera rotation to snapshot image if configured."""
  3229. from backend.app.services.camera import apply_camera_rotation
  3230. return apply_camera_rotation(image_data, getattr(printer, "camera_rotation", 0), logger)
  3231. async def _send_print_start_notification(
  3232. printer_id: int,
  3233. data: dict,
  3234. archive_data: dict | None = None,
  3235. logger=None,
  3236. ):
  3237. """Helper to send print start notification with optional archive data."""
  3238. if logger is None:
  3239. logger = logging.getLogger(__name__)
  3240. try:
  3241. async with async_session() as db:
  3242. from backend.app.models.printer import Printer
  3243. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3244. printer = result.scalar_one_or_none()
  3245. printer_name = printer.name if printer else f"Printer {printer_id}"
  3246. # Capture camera snapshot for notification image attachment
  3247. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3248. if image_data:
  3249. if archive_data is None:
  3250. archive_data = {}
  3251. archive_data["image_data"] = image_data
  3252. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  3253. # Send user-specific email notification for print start
  3254. if archive_data and archive_data.get("created_by_id"):
  3255. await notification_service.send_user_print_email(
  3256. event_type="user_print_start",
  3257. created_by_id=archive_data["created_by_id"],
  3258. printer_name=printer_name,
  3259. filename=data.get("subtask_name") or data.get("filename", "Unknown"),
  3260. db=db,
  3261. )
  3262. except Exception as e:
  3263. logger.warning("Notification on_print_start failed: %s", e)
  3264. async def _dispatch_user_print_email(
  3265. status: str,
  3266. created_by_id: int | None,
  3267. printer_name: str,
  3268. filename: str,
  3269. db,
  3270. image_data: bytes | None = None,
  3271. finish_photo_url: str | None = None,
  3272. ) -> None:
  3273. """Send a user-specific print-completion email based on print status.
  3274. Maps the normalised print status to the correct event type and delegates
  3275. to :meth:`NotificationService.send_user_print_email`. A single helper
  3276. avoids duplicating the ``if status == "completed" / elif "failed" / elif
  3277. "stopped"`` dispatch block at every call site.
  3278. Does nothing if *created_by_id* is ``None``.
  3279. """
  3280. if created_by_id is None:
  3281. return
  3282. if status == "completed":
  3283. event_type = "user_print_complete"
  3284. elif status == "failed":
  3285. event_type = "user_print_failed"
  3286. elif status in ("stopped", "aborted", "cancelled"):
  3287. event_type = "user_print_stopped"
  3288. else:
  3289. return
  3290. await notification_service.send_user_print_email(
  3291. event_type=event_type,
  3292. created_by_id=created_by_id,
  3293. printer_name=printer_name,
  3294. filename=filename,
  3295. db=db,
  3296. image_data=image_data,
  3297. finish_photo_url=finish_photo_url,
  3298. )
  3299. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  3300. """Extract printable objects from an archive's 3MF file and store in printer state."""
  3301. try:
  3302. from backend.app.services.archive import extract_printable_objects_from_archive
  3303. client = printer_manager.get_client(printer_id)
  3304. if not client:
  3305. return
  3306. # Extract with positions for UI overlay, scoped to the plate that
  3307. # is printing — resolve_plate_id is the same resolver /cover uses,
  3308. # so the object list can't disagree with the thumbnail it is drawn
  3309. # over (#2522).
  3310. printable_objects, bbox_all = extract_printable_objects_from_archive(
  3311. app_settings.base_dir / archive.file_path,
  3312. plate_number=resolve_plate_id(client.state),
  3313. )
  3314. if printable_objects:
  3315. client.state.printable_objects = printable_objects
  3316. client.state.printable_objects_bbox_all = bbox_all
  3317. client.state.skipped_objects = []
  3318. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  3319. except Exception as e:
  3320. logger.debug("Failed to extract printable objects from archive: %s", e)
  3321. async def _restore_printable_objects(printer_id: int, state, db, logger) -> None:
  3322. """Put the skip-objects list back after a restart mid-print.
  3323. ``PrinterState.printable_objects`` is in-memory only, and the only thing
  3324. that fills it is ``_load_objects_from_archive`` on the print-start paths —
  3325. which the #1304 guard suppresses on the first RUNNING push after startup.
  3326. Everything else this hook restores (the archive, the usage-tracking session,
  3327. the timelapse baseline) was already handled; the object list was not, so a
  3328. restart mid-print took skip-objects away for the rest of that print.
  3329. Nothing recovered it either: the printer card gates its Skip button on the
  3330. object count, and the one endpoint that can rebuild the list is reachable
  3331. only from the modal that button opens.
  3332. Anchored on ``subtask_id``, which the firmware mints per print, so a
  3333. leftover ``status="printing"`` row from a completion we never saw cannot
  3334. hand this print someone else's objects. Without one, nothing is loaded
  3335. rather than guessed — the reload path on ``GET /print/objects`` covers that
  3336. case on demand.
  3337. """
  3338. client = printer_manager.get_client(printer_id)
  3339. if client is None or client.state.printable_objects:
  3340. return
  3341. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  3342. if subtask_id in ("", "0"):
  3343. return
  3344. from backend.app.models.archive import PrintArchive
  3345. archive = await db.scalar(
  3346. select(PrintArchive)
  3347. .where(
  3348. PrintArchive.printer_id == printer_id,
  3349. PrintArchive.status == "printing",
  3350. PrintArchive.subtask_id == subtask_id,
  3351. )
  3352. .order_by(PrintArchive.created_at.desc())
  3353. .limit(1)
  3354. )
  3355. if archive is not None:
  3356. _load_objects_from_archive(archive, printer_id, logger)
  3357. # Retry ladder for a fallback archive created while the printer's FTPS cool-off
  3358. # was running (#2957). The cool-off is 300s, so the first attempt is placed just
  3359. # past it; the second covers a handshake that failed again on the way back and
  3360. # armed a fresh one. Module-level so tests can shrink them.
  3361. _FALLBACK_3MF_RETRY_DELAYS_SECONDS: tuple[float, ...] = (310.0, 620.0)
  3362. # Retry ladder for the other temporary give-up: the file service answered and
  3363. # the transfer still did not finish, which at print start is usually the printer
  3364. # serving MQTT, the camera and a job upload at the same time (#3063). Nothing has
  3365. # to expire here, so the first attempt comes early -- #3063's reporter had the
  3366. # same 19MB file complete 48 seconds after the download budget ran out. The later
  3367. # two cover a printer that stays busy well into the print.
  3368. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS: tuple[float, ...] = (60.0, 240.0, 600.0)
  3369. # printer_id -> the in-flight retry task, so print completion can cancel it.
  3370. _fallback_3mf_retry_tasks: dict[int, asyncio.Task] = {}
  3371. # printer_id -> lock serialising recovery attempts for that printer. Three callers
  3372. # can reach one archive at once: the cover endpoint (whose single-flight coalesces
  3373. # by view, so two views race), the cool-off retry task, and print completion.
  3374. # Without this they each read file_path == "" and each run a full copy, so the row
  3375. # ends up pointing at one timestamped directory while the others sit orphaned.
  3376. #
  3377. # Keyed by printer rather than archive because a printer runs one print at a time,
  3378. # which makes the two equally strong here — and it bounds the dict by printer
  3379. # count instead of needing a cleanup pass. Popping a per-archive entry cannot be
  3380. # done safely: `Lock.locked()` reads False between release and the queued waiter
  3381. # resuming, so "no waiters" is not a question this API can answer.
  3382. _fallback_recovery_locks: dict[int, asyncio.Lock] = {}
  3383. async def _recover_fallback_archive(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3384. """Fill in a no-3MF archive from a 3MF that turned up later.
  3385. Returns True when the row was upgraded. Safe to call speculatively: it
  3386. verifies the archive still exists, is still a fallback, and that the file
  3387. is a readable 3MF before touching anything.
  3388. Serialised per printer — see ``_fallback_recovery_locks``.
  3389. """
  3390. lock = _fallback_recovery_locks.setdefault(printer_id, asyncio.Lock())
  3391. async with lock:
  3392. return await _recover_fallback_archive_locked(archive_id, source_3mf, printer_id)
  3393. async def _recover_fallback_archive_locked(archive_id: int, source_3mf: Path, printer_id: int) -> bool:
  3394. """The body of :func:`_recover_fallback_archive`, under its per-printer lock."""
  3395. import zipfile
  3396. from backend.app.models.archive import PrintArchive
  3397. from backend.app.services.archive import ArchiveService
  3398. logger = logging.getLogger(__name__)
  3399. if not source_3mf.exists() or source_3mf.stat().st_size == 0:
  3400. return False
  3401. if not await asyncio.to_thread(zipfile.is_zipfile, source_3mf):
  3402. # A truncated or half-written download is worse than no download: it
  3403. # would replace an honest empty archive with wrong metadata.
  3404. logger.warning("[RECOVER] %s is not a readable 3MF; leaving archive %s as-is", source_3mf, archive_id)
  3405. return False
  3406. async with async_session() as db:
  3407. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3408. if archive is None or archive.deleted_at is not None:
  3409. return False
  3410. if archive.file_path:
  3411. # Already recovered, or never was a fallback. Either way there is a
  3412. # real 3MF attached and overwriting it is not this function's job.
  3413. return False
  3414. print_data = (archive.extra_data or {}).get("_print_data") or {}
  3415. service = ArchiveService(db)
  3416. recovered = await service.archive_print(
  3417. printer_id=printer_id,
  3418. source_file=source_3mf,
  3419. print_data={**print_data, "status": archive.status or "printing"},
  3420. subtask_id=archive.subtask_id,
  3421. update_archive_id=archive.id,
  3422. )
  3423. if recovered is None:
  3424. return False
  3425. logger.info(
  3426. "[RECOVER] Archive %s filled in from %s (%s bytes) — it started as a no-3MF fallback",
  3427. archive_id,
  3428. source_3mf,
  3429. recovered.file_size,
  3430. )
  3431. # `archive_updated`, not `archive_created` — the row was already on the
  3432. # Archives page as an empty card and is now filled in, not new.
  3433. await ws_manager.send_archive_updated(
  3434. {
  3435. "id": recovered.id,
  3436. "printer_id": recovered.printer_id,
  3437. "filename": recovered.filename,
  3438. "print_name": recovered.print_name,
  3439. "status": recovered.status,
  3440. }
  3441. )
  3442. return True
  3443. async def try_recover_fallback_archive(printer_id: int, name: str, path: Path) -> bool:
  3444. """Offer a freshly-downloaded 3MF to this printer's running fallback archive.
  3445. Called from the paths that pull a 3MF for a print that is already under way
  3446. — chiefly the cover endpoint, which downloads the very file the archive flow
  3447. could not get and, before #2957, used it for a thumbnail and nothing else.
  3448. The bytes are already local, so this costs a parse and a row update.
  3449. No-op when the running print has a real archive, which is the common case.
  3450. """
  3451. from backend.app.models.archive import PrintArchive
  3452. logger = logging.getLogger(__name__)
  3453. # `_active_prints` is keyed on the raw names seen at print start — the
  3454. # dispatch filename, the subtask name, and the subtask name plus ".3mf".
  3455. # Callers here arrive with whichever variant their own path produced, so
  3456. # match on the same normalization the download cache uses rather than on an
  3457. # exact string; that is what makes "Desktop_Goose.gcode.3mf" from the cover
  3458. # endpoint find an archive registered under "Desktop_Goose".
  3459. wanted = normalize_3mf_name(name)
  3460. archive_id = None
  3461. for (key_printer_id, key_name), value in list(_active_prints.items()):
  3462. if key_printer_id == printer_id and normalize_3mf_name(key_name) == wanted:
  3463. archive_id = value
  3464. break
  3465. if archive_id is None:
  3466. return False
  3467. async with async_session() as db:
  3468. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3469. # Cheap pre-check so the common case (a normal archive) does no work.
  3470. if archive is None or archive.file_path or archive.deleted_at is not None:
  3471. return False
  3472. try:
  3473. return await _recover_fallback_archive(archive_id, path, printer_id)
  3474. except Exception as e:
  3475. # Recovery is opportunistic. A failure here must never take down the
  3476. # caller, which is usually just trying to render a thumbnail.
  3477. logger.warning("[RECOVER] Could not fill in archive %s from %s: %s", archive_id, path, e)
  3478. return False
  3479. def _schedule_fallback_3mf_retry(
  3480. printer_id: int,
  3481. archive_id: int,
  3482. filenames: list[str],
  3483. delays: tuple[float, ...] | None = None,
  3484. reason: str = REASON_FTPS_COOLOFF,
  3485. ) -> None:
  3486. """Re-attempt the 3MF download after a temporary give-up.
  3487. ``reason`` says which give-up this is, and picks the default ladder: an
  3488. FTPS cool-off has to be waited out, while a transfer that timed out under
  3489. contention is worth asking about again straight away (#3063). It is only
  3490. read for the ladder and the log line -- the retry itself is identical, since
  3491. in both cases the file is on the printer and the last attempt at it failed
  3492. for a reason that does not last.
  3493. """
  3494. logger = logging.getLogger(__name__)
  3495. if delays is None:
  3496. delays = (
  3497. _FALLBACK_3MF_TRANSFER_RETRY_DELAYS_SECONDS
  3498. if reason == REASON_FTP_TRANSFER_FAILED
  3499. else _FALLBACK_3MF_RETRY_DELAYS_SECONDS
  3500. )
  3501. async def _retry() -> None:
  3502. from backend.app.models.archive import PrintArchive
  3503. from backend.app.models.printer import Printer
  3504. for delay in delays:
  3505. await asyncio.sleep(delay)
  3506. async with async_session() as db:
  3507. archive = (
  3508. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  3509. ).scalar_one_or_none()
  3510. if archive is None or archive.deleted_at is not None or archive.file_path:
  3511. return
  3512. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  3513. if printer is None:
  3514. return
  3515. # Read the fields while the session is open rather than touching
  3516. # a detached instance minutes later, mid-download.
  3517. printer_ip = printer.ip_address
  3518. printer_code = printer.access_code
  3519. printer_model = printer.model
  3520. # Someone else may have fetched it in the meantime — the cover
  3521. # endpoint routinely does, and its copy is the same bytes.
  3522. for name in filenames:
  3523. cached = get_cached_3mf(printer_id, name)
  3524. if cached and await _recover_fallback_archive(archive_id, cached, printer_id):
  3525. return
  3526. if ftps_handshake_blocked(printer_ip):
  3527. logger.info(
  3528. "[RECOVER] Printer %s is still in its FTPS cool-off; archive %s retry deferred",
  3529. printer_id,
  3530. archive_id,
  3531. )
  3532. continue
  3533. _, _, _, ftp_timeout = await get_ftp_retry_settings()
  3534. for candidate in filenames:
  3535. # Bare name only. These come from the print-start flow, which
  3536. # already strips the path, but the local temp write must not
  3537. # depend on that holding for every future caller — a name that
  3538. # is absolute or contains ".." would otherwise escape the data
  3539. # volume via the `/` operator.
  3540. name = Path(candidate).name
  3541. if not name or name in (".", ".."):
  3542. continue
  3543. if not name.endswith(".3mf"):
  3544. name = f"{name}.3mf"
  3545. temp_path = app_settings.archive_dir / "temp" / name
  3546. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3547. try:
  3548. hit = await download_file_try_paths_async(
  3549. printer_ip,
  3550. printer_code,
  3551. ftp_probe_paths(name),
  3552. temp_path,
  3553. socket_timeout=ftp_timeout,
  3554. printer_model=printer_model,
  3555. )
  3556. except Exception as e:
  3557. logger.debug("[RECOVER] Retry download of %s failed: %s", name, e)
  3558. continue
  3559. if not hit:
  3560. continue
  3561. cache_3mf_download(printer_id, name, temp_path)
  3562. if await _recover_fallback_archive(archive_id, temp_path, printer_id):
  3563. return
  3564. logger.info("[RECOVER] Archive %s still has no 3MF after a retry", archive_id)
  3565. async def _guarded() -> None:
  3566. try:
  3567. await _retry()
  3568. except asyncio.CancelledError:
  3569. raise
  3570. except Exception as e:
  3571. logger.warning("[RECOVER] Retry task for archive %s failed: %s", archive_id, e)
  3572. finally:
  3573. if _fallback_3mf_retry_tasks.get(printer_id) is asyncio.current_task():
  3574. _fallback_3mf_retry_tasks.pop(printer_id, None)
  3575. existing = _fallback_3mf_retry_tasks.pop(printer_id, None)
  3576. if existing and not existing.done():
  3577. existing.cancel()
  3578. task = asyncio.create_task(_guarded())
  3579. _fallback_3mf_retry_tasks[printer_id] = task
  3580. logger.info(
  3581. "[RECOVER] Archive %s has no 3MF (%s) and the file should still be on printer %s; will retry in %s",
  3582. archive_id,
  3583. reason,
  3584. printer_id,
  3585. ", ".join(f"{d:g}s" for d in delays),
  3586. )
  3587. async def _ask_outcome_for_external_print(db, printer_id: int, observed_name: str | None = None) -> bool:
  3588. """Whether an archive created here should ask for the print's outcome (#1898).
  3589. Only a print Bambuddy did not dispatch reaches the archive-*creating*
  3590. branches below: a queued job already has its archive and takes the
  3591. expected-print branch, where the queue item's own ``confirm_outcome``
  3592. decides. The queue is still consulted, because a restart mid-print empties
  3593. ``_expected_prints`` — without the check the setting could override a queue
  3594. item that deliberately has the flag off. Any failure answers "don't ask":
  3595. an unwanted prompt is worse than a missing one, and this must never be the
  3596. reason a print goes unarchived.
  3597. A ``printing`` row is not proof on its own, though: Bambuddy deliberately
  3598. leaves one behind when a completion cannot be matched to it
  3599. (``_completion_belongs_to_queue_item``), and the scheduler's stranded sweep
  3600. only takes it back once the printer has sat connected and terminal for
  3601. minutes. Until then every screen-started print on that printer would
  3602. silently lose its prompt, so the row is held against ``observed_name`` by
  3603. the same comparison a completion uses: a positive disagreement means the row
  3604. is about some other run and this print is external after all.
  3605. """
  3606. logger = logging.getLogger(__name__)
  3607. try:
  3608. # A savepoint rather than a rollback of the caller's transaction on
  3609. # failure: a failed statement leaves the transaction unusable, but a
  3610. # full rollback also expires every object the caller has loaded (the
  3611. # printer, the archive it just created), and on an async session the
  3612. # next attribute read then raises instead of reloading. Everything here
  3613. # is a read, so undoing the savepoint loses nothing.
  3614. async with db.begin_nested():
  3615. return await _decide_outcome_for_external_print(db, printer_id, observed_name, logger)
  3616. except Exception as e:
  3617. logger.warning("[CALLBACK] Could not decide the outcome prompt for printer %s: %s", printer_id, e)
  3618. return False
  3619. async def _decide_outcome_for_external_print(db, printer_id: int, observed_name: str | None, logger) -> bool:
  3620. """The reads behind ``_ask_outcome_for_external_print``; see there."""
  3621. from backend.app.api.routes.settings import get_setting, setting_is_true
  3622. if not setting_is_true(await get_setting(db, "confirm_outcome_external_prints")):
  3623. return False
  3624. from backend.app.models.print_queue import PrintQueueItem
  3625. dispatched_here = await db.scalar(
  3626. select(PrintQueueItem)
  3627. .where(
  3628. PrintQueueItem.printer_id == printer_id,
  3629. PrintQueueItem.status == "printing",
  3630. )
  3631. .limit(1)
  3632. )
  3633. if dispatched_here is None:
  3634. return True
  3635. expected = await _queue_item_dispatched_name(db, dispatched_here)
  3636. observed = (observed_name or "").strip()
  3637. if not expected or not observed or _subtask_names_match(expected, observed):
  3638. logger.info(
  3639. "[CALLBACK] Not asking for the outcome on printer %s: queue item %s is still printing, so "
  3640. "Bambuddy dispatched this run and the item's own ask-for-outcome flag decides.",
  3641. printer_id,
  3642. dispatched_here.id,
  3643. )
  3644. return False
  3645. logger.info(
  3646. "[CALLBACK] Queue item %s is still marked printing on printer %s but was dispatched as %r, not "
  3647. "%r; treating this as an externally started print.",
  3648. dispatched_here.id,
  3649. printer_id,
  3650. expected,
  3651. observed,
  3652. )
  3653. return True
  3654. async def _dispatch_outcome_confirmation_safely(
  3655. db,
  3656. printer_id: int,
  3657. printer_name: str,
  3658. data: dict,
  3659. archive_id: int,
  3660. archive_data: dict | None = None,
  3661. ) -> None:
  3662. """``dispatch_outcome_confirmation`` for a caller that has more to do on ``db``.
  3663. The completion task sends the per-user print email on the same session
  3664. right after the prompt. A failed statement in the prompt leaves that
  3665. session needing a rollback, and without one the email step fails with
  3666. PendingRollbackError; the prompt is the optional part, so it must not be
  3667. the reason the email never goes out.
  3668. """
  3669. try:
  3670. await dispatch_outcome_confirmation(db, printer_id, printer_name, data, archive_id, archive_data)
  3671. except Exception as e:
  3672. logging.getLogger(__name__).error("[NOTIFY-BG] Outcome-confirmation dispatch failed: %s", e, exc_info=True)
  3673. try:
  3674. await db.rollback()
  3675. except Exception:
  3676. pass
  3677. async def dispatch_outcome_confirmation(
  3678. db,
  3679. printer_id: int,
  3680. printer_name: str,
  3681. data: dict,
  3682. archive_id: int,
  3683. archive_data: dict | None = None,
  3684. ) -> bool:
  3685. """Emit the post-print outcome prompt for a completed archive (#1898).
  3686. Gated on the archive itself: ``confirm_requested`` is the opt-in (from the
  3687. queue item, or from ``confirm_outcome_external_prints`` for a print
  3688. Bambuddy did not start) and ``user_verdict`` being unset is what makes the
  3689. question still open. Mints the per-archive capability token the one-tap
  3690. verdict links carry.
  3691. Lives here rather than inline in ``on_print_complete``'s notification task
  3692. because that task swallows every exception: extracted, the gate and the two
  3693. emissions can be driven by a test, which is the only thing standing between
  3694. a regression here and a farm that quietly stops asking.
  3695. Returns whether a prompt was sent.
  3696. """
  3697. logger = logging.getLogger(__name__)
  3698. from backend.app.models.archive import PrintArchive
  3699. confirm_archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  3700. if not (confirm_archive and confirm_archive.confirm_requested and confirm_archive.user_verdict is None):
  3701. return False
  3702. import secrets as _secrets
  3703. # A spent token stays on the row so the one-tap route can recognise it, so
  3704. # "has a token" no longer means "answerable". A prompt going out now needs a
  3705. # live one: mint a new token whenever the stored one is already spent, or
  3706. # every button in the new message would land on the already-answered page.
  3707. if not confirm_archive.confirm_token or confirm_archive.confirm_token_used_at is not None:
  3708. confirm_archive.confirm_token = _secrets.token_urlsafe(32)
  3709. confirm_archive.confirm_token_used_at = None
  3710. await db.commit()
  3711. from backend.app.api.routes.settings import get_external_base_url, get_setting
  3712. base = await get_external_base_url(db)
  3713. if not await get_setting(db, "external_url"):
  3714. # Both the Telegram inline keyboard and the ntfy action buttons need an
  3715. # absolute URL, so an unconfigured install used to get a message body
  3716. # with two unusable relative paths and no buttons at all. The shared
  3717. # fallback at least produces tappable links; say which setting makes
  3718. # them resolve from a phone.
  3719. logger.warning(
  3720. "[#1898] No external_url configured — the outcome prompt's Good/Reject links point at %s. "
  3721. "Set Settings → External URL so they resolve away from this host.",
  3722. base,
  3723. )
  3724. token = confirm_archive.confirm_token
  3725. good_url = f"{base}/api/v1/archives/confirm/{token}/good"
  3726. reject_url = f"{base}/api/v1/archives/confirm/{token}/reject"
  3727. confirm_url = f"{base}/archives?confirm={archive_id}"
  3728. await ws_manager.send_print_confirm_request(
  3729. printer_id,
  3730. {
  3731. "archive_id": archive_id,
  3732. "print_name": confirm_archive.print_name or confirm_archive.filename,
  3733. },
  3734. )
  3735. await notification_service.on_print_confirm_request(
  3736. printer_id,
  3737. printer_name,
  3738. data,
  3739. db,
  3740. archive_data=archive_data,
  3741. good_url=good_url,
  3742. reject_url=reject_url,
  3743. confirm_url=confirm_url,
  3744. archive_id=archive_id,
  3745. )
  3746. return True
  3747. async def _printer_gone(db, printer_id: int) -> bool:
  3748. """Whether the printer was deleted. A column read: the session's loaded
  3749. Printer would otherwise answer for the database."""
  3750. from backend.app.models.printer import Printer
  3751. return await db.scalar(select(Printer.id).where(Printer.id == printer_id)) is None
  3752. async def _drop_archive_of_deleted_printer(db, printer_id: int, archive_id: int) -> bool:
  3753. """Remove the archive just written if its printer was deleted meanwhile.
  3754. The delete route sweeps the printer's archives before it commits, so a row
  3755. committed after that sweep (the check before writing passed while the
  3756. delete was still uncommitted) is left for a printer that will never report
  3757. the print's end. A row the sweep reached is the route's: deleted with the
  3758. printer's archives, or detached (printer_id NULL) when the user kept them,
  3759. and then left as it is. Either way nothing is registered for it. Run after
  3760. the archive's commit, before anything is registered for it.
  3761. """
  3762. from backend.app.models.archive import PrintArchive
  3763. if not await _printer_gone(db, printer_id):
  3764. return False
  3765. owner = await db.scalar(select(PrintArchive.printer_id).where(PrintArchive.id == archive_id))
  3766. if owner == printer_id:
  3767. logging.getLogger(__name__).info(
  3768. "Printer %s was deleted while archive %s was written; removing it", printer_id, archive_id
  3769. )
  3770. await ArchiveService(db).delete_archive(archive_id)
  3771. await forget_printer(printer_id)
  3772. return True
  3773. async def _refused_for_deleted_printer(db, printer_id: int, what: str) -> bool:
  3774. """After an IntegrityError on a print start's archive write: whether it was
  3775. the printer being deleted, forgotten then (the caller returns).
  3776. PostgreSQL: the delete route locks the printer from its archive sweep to its
  3777. commit, so an archive written or adopted for it meanwhile (one that sets
  3778. printer_id) waits and the printer's foreign key then refuses it. That is
  3779. the printer being deleted, not an error; anything else is re-raised by the
  3780. caller.
  3781. """
  3782. await db.rollback()
  3783. if not await _printer_gone(db, printer_id):
  3784. return False
  3785. logging.getLogger(__name__).info("Printer %s was deleted while %s; refused", printer_id, what)
  3786. await forget_printer(printer_id)
  3787. return True
  3788. async def _forget_if_printer_gone(printer_id: int) -> None:
  3789. """At the end of a print start: the slow steps after the last check (smart
  3790. plug, notifications, the timelapse baseline's FTP listing) can outlast the
  3791. printer's delete and its forget_printer, and then wrote state back.
  3792. (An ActivePrintSpoolman row written then is the init_db orphan sweep's on
  3793. SQLite; PostgreSQL refuses it.)
  3794. Its own session: those steps can leave the handler's needing a rollback (a
  3795. write to the archive the delete removed). Never raises: it runs inside the
  3796. fallback branch's try, whose except reports the archive as failed.
  3797. """
  3798. try:
  3799. async with async_session() as db:
  3800. gone = await _printer_gone(db, printer_id)
  3801. if gone:
  3802. await forget_printer(printer_id)
  3803. except Exception:
  3804. logging.getLogger(__name__).warning(
  3805. "Could not check whether printer %s was deleted during its print start", printer_id, exc_info=True
  3806. )
  3807. async def on_print_start(printer_id: int, data: dict):
  3808. """Handle print start - archive the 3MF file immediately."""
  3809. logger = logging.getLogger(__name__)
  3810. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  3811. try:
  3812. notify_live_activities.print_started(printer_id, printer_manager.get_status(printer_id), data)
  3813. except Exception:
  3814. logger.exception("Notify Live Activity start hook failed for printer %s", printer_id)
  3815. # Clear any stale user-stopped flag from previous print cycles
  3816. _user_stopped_printers.discard(printer_id)
  3817. # A new print starts its milestones from zero (#3211). The status path only
  3818. # resets on progress below 5 while not printing, which a printer that goes
  3819. # from FINISH at 100% straight into a new print at a preparation-phase 85%
  3820. # never shows. This callback does not fire after a Bambuddy restart (#1304)
  3821. # or on resume from pause, so it cannot repeat a milestone mid-print.
  3822. _last_progress_milestone[printer_id] = 0
  3823. _kill_switch_notification_tasks.pop(printer_id, None)
  3824. # #1721: drop any leftover pre-captured finish frame from a prior print
  3825. # so a never-consumed cache entry can't bleed into the new print's photo.
  3826. _stage22_finish_frames.pop(printer_id, None)
  3827. # #1867: same for the in-print frame bank — a queued print must not reuse
  3828. # the previous job's banked frame.
  3829. _inprint_frame_bank.pop(printer_id, None)
  3830. _inprint_frame_bank_ts.pop(printer_id, None)
  3831. # #2547: bind (or clear) the "this print ends with injected End G-code" flag.
  3832. # Unconditional, so a print Bambuddy didn't dispatch drops the previous
  3833. # print's flag instead of inheriting it.
  3834. print_dispatch_context.adopt(printer_id)
  3835. # Cancel any active bed cooldown waiter for this printer
  3836. if _bed_cool_waiters.pop(printer_id, None):
  3837. logger.info("[BED-COOL] Cancelled bed cooldown waiter for printer %s (new print started)", printer_id)
  3838. # Clear cached cover images so the new print's thumbnail is fetched fresh
  3839. from backend.app.api.routes.printers import clear_cover_cache
  3840. clear_cover_cache(printer_id)
  3841. await ws_manager.send_print_start(printer_id, data)
  3842. # Notify when the print-start AMS mapping references tray slots without spool assignments.
  3843. await notify_missing_spool_assignments_on_print_start(printer_id, data, logger)
  3844. # MQTT relay - publish print start
  3845. try:
  3846. printer_info = printer_manager.get_printer(printer_id)
  3847. if printer_info:
  3848. await mqtt_relay.on_print_start(
  3849. printer_id,
  3850. printer_info.name,
  3851. printer_info.serial_number,
  3852. data.get("filename", ""),
  3853. data.get("subtask_name", ""),
  3854. )
  3855. except Exception:
  3856. pass # Don't fail print start callback if MQTT fails
  3857. # Capture AMS tray remain%, the assignment snapshot, the dispatched plate
  3858. # and mapping, and the seeded tray-change log.
  3859. #
  3860. # Unconditional, for both inventory backends. This only *captures* — the
  3861. # writing is still split, with the internal tracker skipped at completion
  3862. # when Spoolman owns usage. Spoolman's own durable row (#1820) already
  3863. # carries its plate-scoped 3MF figures and stored mapping, but not the
  3864. # tray-change log, and that log is the only record of which spool fed
  3865. # which layers when AMS Filament Backup swaps trays mid-print. Capturing
  3866. # it on one side only would leave Spoolman users with the mid-print
  3867. # restart bug this fixes for everyone else.
  3868. try:
  3869. async with async_session() as db:
  3870. from backend.app.api.routes.settings import get_setting
  3871. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  3872. _spoolman_on = await get_setting(db, "spoolman_enabled")
  3873. await usage_on_print_start(
  3874. printer_id,
  3875. data,
  3876. printer_manager,
  3877. db=db,
  3878. spoolman_owns_usage=bool(_spoolman_on) and _spoolman_on.lower() == "true",
  3879. )
  3880. except Exception as e:
  3881. logger.warning("Usage tracker on_print_start failed: %s", e)
  3882. # Track if notification was sent (to avoid sending twice)
  3883. notification_sent = False
  3884. # Smart plug automation: turn on plug when print starts
  3885. try:
  3886. async with async_session() as db:
  3887. await smart_plug_manager.on_print_start(printer_id, db)
  3888. except Exception as e:
  3889. logger.warning("Smart plug on_print_start failed: %s", e)
  3890. async with async_session() as db:
  3891. from backend.app.models.printer import Printer
  3892. from backend.app.services.bambu_ftp import list_files_async
  3893. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3894. printer = result.scalar_one_or_none()
  3895. # Plate detection check - pause if objects detected on build plate
  3896. logger.info(
  3897. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  3898. )
  3899. if printer and printer.plate_detection_enabled:
  3900. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  3901. # Release the pooled DB connection before the plate-detection camera
  3902. # work (a 2.5s light-settle sleep + FTP/camera capture). Only the
  3903. # printer SELECT has run so far — nothing to persist — so this commit
  3904. # is a data-noop that ends the read transaction and returns the
  3905. # connection to the pool during the I/O (issue #2572). expire_on_commit
  3906. # =False keeps printer.* readable; on_plate_not_empty (rare) and the
  3907. # archive lookups below re-acquire a fresh connection on next execute.
  3908. await db.commit()
  3909. try:
  3910. from backend.app.services.plate_detection import check_plate_empty
  3911. # Build ROI tuple from printer settings if available
  3912. roi = None
  3913. if all(
  3914. [
  3915. printer.plate_detection_roi_x is not None,
  3916. printer.plate_detection_roi_y is not None,
  3917. printer.plate_detection_roi_w is not None,
  3918. printer.plate_detection_roi_h is not None,
  3919. ]
  3920. ):
  3921. roi = (
  3922. printer.plate_detection_roi_x,
  3923. printer.plate_detection_roi_y,
  3924. printer.plate_detection_roi_w,
  3925. printer.plate_detection_roi_h,
  3926. )
  3927. # Auto-turn on chamber light if it's off for better detection
  3928. light_was_off = False
  3929. client = printer_manager.get_client(printer_id)
  3930. if client and client.state:
  3931. light_was_off = not client.state.chamber_light
  3932. if light_was_off:
  3933. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  3934. client.set_chamber_light(True)
  3935. # Wait for light to physically turn on and camera to adjust exposure
  3936. await asyncio.sleep(2.5)
  3937. plate_photo_data = None
  3938. objects_detected = False
  3939. try:
  3940. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  3941. plate_result = await check_plate_empty(
  3942. printer_id=printer_id,
  3943. ip_address=printer.ip_address,
  3944. access_code=printer.access_code,
  3945. model=printer.model,
  3946. include_debug_image=False,
  3947. external_camera_url=printer.external_camera_url,
  3948. external_camera_type=printer.external_camera_type,
  3949. use_external=printer.external_camera_enabled,
  3950. roi=roi,
  3951. external_camera_snapshot_url=printer.external_camera_snapshot_url,
  3952. )
  3953. objects_detected = not plate_result.needs_calibration and not plate_result.is_empty
  3954. if objects_detected:
  3955. # Objects detected - pause the print!
  3956. logger.warning(
  3957. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  3958. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  3959. )
  3960. pause_client = printer_manager.get_client(printer_id)
  3961. if pause_client:
  3962. pause_client.pause_print()
  3963. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  3964. # Snapshot while the light's still on — restoring it first
  3965. # would leave the notification with a dark photo.
  3966. try:
  3967. plate_photo_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  3968. except Exception as snap_err:
  3969. logger.warning(
  3970. "[PLATE CHECK] Failed to capture snapshot for printer %s: %s", printer_id, snap_err
  3971. )
  3972. finally:
  3973. # Restore chamber light to original state as soon as the
  3974. # camera is done with it, whatever happened above.
  3975. if light_was_off and client:
  3976. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  3977. try:
  3978. client.set_chamber_light(False)
  3979. except Exception as light_err:
  3980. logger.warning(
  3981. "[PLATE CHECK] Failed to restore chamber light for printer %s: %s",
  3982. printer_id,
  3983. light_err,
  3984. )
  3985. if objects_detected:
  3986. # Send notification about plate not empty
  3987. await ws_manager.broadcast(
  3988. {
  3989. "type": "plate_not_empty",
  3990. "printer_id": printer_id,
  3991. "printer_name": printer.name,
  3992. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  3993. }
  3994. )
  3995. # Also send push notification
  3996. try:
  3997. await notification_service.on_plate_not_empty(
  3998. printer_id=printer_id,
  3999. printer_name=printer.name,
  4000. db=db,
  4001. difference_percent=plate_result.difference_percent,
  4002. image_data=plate_photo_data,
  4003. )
  4004. except Exception as notif_err:
  4005. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  4006. else:
  4007. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  4008. except Exception as plate_err:
  4009. # Don't block print on plate detection errors
  4010. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  4011. if not printer:
  4012. logger.info("[CALLBACK] Skipping archive - printer not found in database")
  4013. if not notification_sent:
  4014. await _send_print_start_notification(printer_id, data, logger=logger)
  4015. return
  4016. # Skip the printer's own jobs — a calibration run is not a user's print.
  4017. # See is_internal_printer_job for what counts and why both fields are
  4018. # tested; the pressure-advance line reports as a subtask name with no
  4019. # /usr/ path, which the old prefix-only test here missed entirely.
  4020. #
  4021. # No notification either. The event describes the printer calibrating
  4022. # itself, so "Print started" is as wrong as the archive was, and the
  4023. # matching completion is suppressed in on_print_complete for the same
  4024. # reason. Checked before the auto-archive switches, whose "off" path
  4025. # still notifies.
  4026. if is_internal_printer_job(data.get("filename", ""), data.get("subtask_name", "")):
  4027. logger.info(
  4028. "[CALLBACK] Skipping archive — internal printer job detected: filename=%s, subtask=%s",
  4029. data.get("filename", ""),
  4030. data.get("subtask_name", ""),
  4031. )
  4032. return
  4033. # The global switch is the master: off, no printer archives prints
  4034. # started outside Bambuddy; on, each printer's own switch decides.
  4035. from backend.app.api.routes.settings import get_setting
  4036. _global_auto_archive = await get_setting(db, "auto_archive")
  4037. archives_prints = printer.auto_archive and (
  4038. _global_auto_archive is None or _global_auto_archive.lower() == "true"
  4039. )
  4040. if not archives_prints:
  4041. # auto-archive disabled — check if there's an expected print (dispatched
  4042. # by BamBuddy via queue/reprint) that already has an archive to promote.
  4043. # If so, fall through to the expected-print handling below so the archive
  4044. # is tracked in _active_prints and usage tracking works at completion.
  4045. _fn = data.get("filename", "")
  4046. _sn = data.get("subtask_name", "")
  4047. _check_keys: list[tuple[int, str]] = []
  4048. if _sn:
  4049. _check_keys += [
  4050. (printer_id, _sn),
  4051. (printer_id, f"{_sn}.3mf"),
  4052. (printer_id, f"{_sn}.gcode.3mf"),
  4053. ]
  4054. if _fn:
  4055. _base_fn = _fn.split("/")[-1] if "/" in _fn else _fn
  4056. _check_keys.append((printer_id, _base_fn))
  4057. _no_archive_base = _base_fn.replace(".gcode", "").replace(".3mf", "")
  4058. _check_keys += [
  4059. (printer_id, _no_archive_base),
  4060. (printer_id, f"{_no_archive_base}.3mf"),
  4061. ]
  4062. _has_expected = any(k in _expected_prints for k in _check_keys)
  4063. if not _has_expected:
  4064. # No expected print — truly external print (started from slicer/touchscreen)
  4065. logger.info("[CALLBACK] Skipping archive - auto_archive: False, no expected print")
  4066. if not notification_sent:
  4067. _no_archive_creator: int | None = None
  4068. for _key in _check_keys:
  4069. _expected_prints.pop(_key, None)
  4070. _expected_print_registered_at.pop(_key, None)
  4071. popped_creator = _expected_print_creators.pop(_key, None)
  4072. if _no_archive_creator is None:
  4073. _no_archive_creator = popped_creator
  4074. _creator_data = {"created_by_id": _no_archive_creator} if _no_archive_creator else None
  4075. await _send_print_start_notification(printer_id, data, _creator_data, logger)
  4076. return
  4077. else:
  4078. logger.info("[CALLBACK] auto_archive disabled but expected print found — promoting archive")
  4079. # Get the filename and subtask_name
  4080. filename = data.get("filename", "")
  4081. subtask_name = data.get("subtask_name", "")
  4082. # MQTT subtask_id uniquely identifies a print job on the printer. When
  4083. # present, it lets us match an archive across a backend restart (#972):
  4084. # same id → same print → resume the existing row instead of cancelling
  4085. # it and recreating from scratch (which loses started_at). Treat "0"
  4086. # and "" as absent — Bambu reports "0" for non-cloud / local prints.
  4087. raw_mqtt = data.get("raw_data") or {}
  4088. subtask_id = raw_mqtt.get("subtask_id")
  4089. if subtask_id is not None:
  4090. subtask_id = str(subtask_id).strip()
  4091. if subtask_id in ("", "0"):
  4092. subtask_id = None
  4093. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  4094. if not filename and not subtask_name:
  4095. # Send notification without archive data (no filename)
  4096. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  4097. if not notification_sent:
  4098. await _send_print_start_notification(printer_id, data, logger=logger)
  4099. return
  4100. # Check if this is an expected print from reprint/scheduled
  4101. # Build list of possible keys to check
  4102. expected_keys = []
  4103. if subtask_name:
  4104. expected_keys.append((printer_id, subtask_name))
  4105. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  4106. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  4107. if filename:
  4108. fname = filename.split("/")[-1] if "/" in filename else filename
  4109. expected_keys.append((printer_id, fname))
  4110. # Strip extensions to match
  4111. base = fname.replace(".gcode", "").replace(".3mf", "")
  4112. expected_keys.append((printer_id, base))
  4113. expected_keys.append((printer_id, f"{base}.3mf"))
  4114. expected_archive_id = None
  4115. for key in expected_keys:
  4116. expected_archive_id = _expected_prints.pop(key, None)
  4117. _expected_print_registered_at.pop(key, None)
  4118. if expected_archive_id:
  4119. # Clean up other possible keys for this print
  4120. for other_key in expected_keys:
  4121. _expected_prints.pop(other_key, None)
  4122. _expected_print_registered_at.pop(other_key, None)
  4123. break
  4124. if expected_archive_id:
  4125. # This is a reprint/scheduled print - use existing archive, don't create new one
  4126. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  4127. from backend.app.models.archive import PrintArchive
  4128. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  4129. archive = result.scalar_one_or_none()
  4130. # Deleted after this handler loaded it (the plate check waits
  4131. # seconds) but before the route forgot the expected print: the
  4132. # archive the route kept or deleted is left as the route left it.
  4133. if archive and await _printer_gone(db, printer_id):
  4134. logger.info(
  4135. "Printer %s was deleted before its print started; not adopting archive %s", printer_id, archive.id
  4136. )
  4137. await forget_printer(printer_id)
  4138. return
  4139. if archive:
  4140. # As it was before this adoption: put back if the printer turns
  4141. # out to have been deleted while it was adopted (below).
  4142. before_adoption = {
  4143. attr.columns[0].name: getattr(archive, attr.key)
  4144. for attr in sa_inspect(PrintArchive).column_attrs
  4145. if attr.key != "id"
  4146. }
  4147. # Update archive status to printing
  4148. archive.status = "printing"
  4149. archive.started_at = datetime.now(timezone.utc)
  4150. # The previous run's outcome is not this one's: a reprint that
  4151. # completes must not keep showing why the last one failed.
  4152. archive.failure_reason = None
  4153. archive.completed_at = None
  4154. # The previous run's answer is still on this row and the
  4155. # completion prompt is gated on ``user_verdict is None`` (#1898),
  4156. # so without a reset the second run inherits the first run's
  4157. # verdict: no prompt at all, and a green "good" badge on a run
  4158. # nobody ever judged.
  4159. if archive.confirm_requested:
  4160. archive.user_verdict = None
  4161. archive.user_verdict_source = None
  4162. archive.user_verdict_at = None
  4163. archive.confirm_token = None
  4164. archive.confirm_token_used_at = None
  4165. # Reprint of an archive reuses the source row. Without resetting
  4166. # ``timelapse_path`` _scan_for_timelapse_with_retries early-returns
  4167. # ("already has timelapse") and _capture_finish_photo_from_timelapse
  4168. # extracts the *original* print's last frame, which then ships in
  4169. # the completion notification (#1707). Clear the path so the
  4170. # scanner runs fresh; also unlink the old video file so reprints
  4171. # don't accumulate orphans in the archive directory. Photos list
  4172. # is left alone — accumulating one finish photo per run is fine.
  4173. # The print-start baseline (#2704) is stale for the same reason:
  4174. # it describes the printer before the previous run. The capture
  4175. # below overwrites it, but clear it here too so an early failure
  4176. # can't leave the scan diffing against the wrong snapshot.
  4177. #
  4178. # Unlinked only when it is the same plate printing again. Every
  4179. # plate of a Send All shares this archive, and the video on it
  4180. # can be the only copy of another plate's run -- the printer's
  4181. # was deleted once it attached (#3275). That one is left in the
  4182. # archive directory, which goes with the archive. A video whose
  4183. # plate is not on record (attached by hand, or before the
  4184. # column existed) is kept too: nothing tells it apart from
  4185. # another plate's, and keeping costs one file where deleting
  4186. # can cost the only copy.
  4187. archive.timelapse_baseline = None
  4188. stale_timelapse_relpath = archive.timelapse_path
  4189. stale_timelapse_plate_id = archive.timelapse_plate_id
  4190. starting_plate_id = _print_plate_ids.get(expected_archive_id)
  4191. if stale_timelapse_relpath:
  4192. archive.timelapse_path = None
  4193. archive.timelapse_plate_id = None
  4194. if stale_timelapse_relpath and stale_timelapse_plate_id != starting_plate_id:
  4195. logger.info(
  4196. "Kept timelapse %s of plate %s on archive %s: plate %s is starting",
  4197. stale_timelapse_relpath,
  4198. stale_timelapse_plate_id,
  4199. expected_archive_id,
  4200. starting_plate_id,
  4201. )
  4202. # The video is deleted once the adoption stands (below).
  4203. delete_stale_video = bool(stale_timelapse_relpath) and stale_timelapse_plate_id == starting_plate_id
  4204. # Persist a restart-stable id so a later restart resumes this
  4205. # archive by subtask_id instead of name-matching + duplicating
  4206. # it (#1485). The printer often hasn't echoed subtask_id back
  4207. # this soon after dispatch, so fall back to the id Bambuddy
  4208. # minted when it sent the print command. Scoped to this
  4209. # expected-print branch on purpose: an expected match means
  4210. # Bambuddy dispatched this exact print in this process, so the
  4211. # client's last-dispatch id genuinely belongs to it — using it
  4212. # for an externally-started print could mis-tag the archive.
  4213. effective_subtask_id = subtask_id
  4214. if not effective_subtask_id:
  4215. _client = printer_manager.get_client(printer_id)
  4216. _dispatched = getattr(_client, "last_dispatch_subtask_id", None) if _client else None
  4217. if _dispatched:
  4218. effective_subtask_id = str(_dispatched).strip() or None
  4219. # Update on first-set OR on reprint (the queue dispatcher mints
  4220. # a fresh subtask_id per dispatch in bambu_mqtt:3647). Skipping
  4221. # the rewrite for reprints leaves the archive holding the FIRST
  4222. # run's id; if MQTT then reconnects mid-print, the reconciler
  4223. # (#1542) compares the stale stored id against the printer's
  4224. # live id, sees a mismatch, and synthesises a bogus PRINT
  4225. # COMPLETE — exactly the false-positive "Print Stopped" reported
  4226. # in #1807. Inequality check preserves the noop-on-stable-push
  4227. # behaviour the earlier `not archive.subtask_id` guard provided.
  4228. if effective_subtask_id and archive.subtask_id != effective_subtask_id:
  4229. archive.subtask_id = effective_subtask_id
  4230. # #1403 follow-up: VP-queue archives are created with
  4231. # printer_id=None at queue-add time (we don't know which
  4232. # printer will run the job yet). When the print actually
  4233. # starts on a specific printer the expected-archive lookup
  4234. # used to skip this assignment, leaving printer_id=None
  4235. # forever — which then disables the "Scan for timelapse"
  4236. # button in ArchivesPage (gated on !archive.printer_id).
  4237. if archive.printer_id != printer_id:
  4238. archive.printer_id = printer_id
  4239. adopting_id = archive.id # a rollback expires the object
  4240. try:
  4241. await db.commit()
  4242. except (IntegrityError, StaleDataError):
  4243. # The archive stays unchanged, or is gone: "delete archives"
  4244. # removed the row under the adoption, which then matched no
  4245. # row (StaleDataError) rather than being refused.
  4246. if await _refused_for_deleted_printer(db, printer_id, f"archive {adopting_id} was adopted"):
  4247. return
  4248. raise
  4249. # The printer can be deleted between the check above and this
  4250. # commit (the route's transaction lasts seconds), and the commit
  4251. # then adopted the archive anyway: status, verdict and timelapse
  4252. # changed, and the deleted printer's id written on a row the
  4253. # route had detached or never touched. Undo the adoption.
  4254. if await _printer_gone(db, printer_id):
  4255. logger.info(
  4256. "Printer %s was deleted while archive %s was adopted; undoing the adoption",
  4257. printer_id,
  4258. archive.id,
  4259. )
  4260. # Everything as before this adoption. The printer it had
  4261. # then stays, unless it was the deleted one: the route
  4262. # detached that row (kept) or deleted it (no row matches).
  4263. previous_printer = before_adoption["printer_id"]
  4264. await db.execute(
  4265. update(PrintArchive)
  4266. .where(PrintArchive.id == archive.id)
  4267. .values(
  4268. {
  4269. **before_adoption,
  4270. "printer_id": None if previous_printer == printer_id else previous_printer,
  4271. }
  4272. )
  4273. )
  4274. await db.commit()
  4275. await forget_printer(printer_id)
  4276. return
  4277. if delete_stale_video and stale_timelapse_relpath:
  4278. try:
  4279. stale_path = app_settings.base_dir / stale_timelapse_relpath
  4280. if stale_path.is_file():
  4281. stale_path.unlink()
  4282. logger.info(
  4283. "Deleted stale timelapse %s on reprint of archive %s",
  4284. stale_timelapse_relpath,
  4285. expected_archive_id,
  4286. )
  4287. except OSError as e:
  4288. logger.warning(
  4289. "Failed to delete stale timelapse %s on reprint: %s",
  4290. stale_timelapse_relpath,
  4291. e,
  4292. )
  4293. # Track as active print
  4294. _active_prints[(printer_id, archive.filename)] = archive.id
  4295. if subtask_name:
  4296. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  4297. # Start timelapse session if external camera is enabled (#1353).
  4298. # Queue / VP-dispatched prints land here in the expected-archive
  4299. # branch and used to skip start_session entirely — frames were
  4300. # never captured and the post-print stitch silently returned None.
  4301. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  4302. # Inject ams_mapping into usage tracker session — the session was created
  4303. # before expected-print promotion, so it may have ams_mapping=None when
  4304. # the MQTT request topic subscription failed (common on P1S/A1).
  4305. _stored_map = _print_ams_mappings.get(expected_archive_id)
  4306. _stored_plate_id = _print_plate_ids.get(expected_archive_id)
  4307. if _stored_map or _stored_plate_id is not None:
  4308. try:
  4309. from backend.app.services.usage_tracker import _active_sessions
  4310. _ut_session = _active_sessions.get(printer_id)
  4311. if _ut_session and _stored_map and not _ut_session.ams_mapping:
  4312. _ut_session.ams_mapping = _stored_map
  4313. logger.info("[CALLBACK] Injected ams_mapping into usage tracker session: %s", _stored_map)
  4314. # plate_id injection covers direct-Print of plate N of a multi-plate
  4315. # 3MF — queue prints already capture it via the on_print_start queue
  4316. # lookup, but direct-Print never goes through the queue (#1697).
  4317. if _ut_session and _stored_plate_id is not None and _ut_session.plate_id is None:
  4318. _ut_session.plate_id = _stored_plate_id
  4319. logger.info("[CALLBACK] Injected plate_id into usage tracker session: %s", _stored_plate_id)
  4320. except Exception:
  4321. pass
  4322. # Set up energy tracking (#941: persist start on archive row)
  4323. await _record_energy_start(archive, printer_id, db, context="expected-print")
  4324. await ws_manager.send_archive_updated(
  4325. {
  4326. "id": archive.id,
  4327. "status": "printing",
  4328. }
  4329. )
  4330. # Send notification with archive data (reprint/scheduled)
  4331. if not notification_sent:
  4332. # Use archive's created_by_id; fall back to the creator registered via
  4333. # register_expected_print (handles library-file-based queue items where
  4334. # the freshly-created archive has no created_by_id yet).
  4335. # Pop ALL matching keys so no stale entries remain in the dict.
  4336. fallback_creator = None
  4337. for key in expected_keys:
  4338. popped = _expected_print_creators.pop(key, None)
  4339. if fallback_creator is None:
  4340. fallback_creator = popped
  4341. archive_data = {
  4342. "print_time_seconds": archive.print_time_seconds,
  4343. "created_by_id": archive.created_by_id or fallback_creator,
  4344. }
  4345. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4346. # Extract printable objects from the archived 3MF file
  4347. _load_objects_from_archive(archive, printer_id, logger)
  4348. # Store Spoolman tracking data for per-filament usage reporting
  4349. try:
  4350. await _store_spoolman_print_data(
  4351. printer_id,
  4352. archive.id,
  4353. archive.file_path,
  4354. db,
  4355. printer_manager,
  4356. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4357. plate_id=_get_start_plate_id(archive.id),
  4358. )
  4359. except Exception as e:
  4360. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  4361. # Price the print from its spools now rather than only at completion (#3261)
  4362. _schedule_archive_cost_estimate(
  4363. printer_id,
  4364. archive.id,
  4365. printer_manager,
  4366. ams_mapping=_get_start_ams_mapping(data, archive.id),
  4367. plate_id=_get_start_plate_id(archive.id),
  4368. session_factory=async_session,
  4369. )
  4370. # Capture timelapse file baseline for snapshot-diff on completion
  4371. # (mirrors the new-archive branch). Queue / VP-dispatched prints
  4372. # hit this branch — without the baseline the completion-time scan
  4373. # falls into its "take baseline now" fallback, which snapshots
  4374. # AFTER the new MP4 already exists and never matches a diff
  4375. # (#1403 follow-up — see pwostran's 2026-05-18 support bundle).
  4376. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  4377. await _forget_if_printer_gone(printer_id)
  4378. return # Skip creating a new archive
  4379. # The archive was deleted after the job was queued.
  4380. if not archives_prints:
  4381. # Only the expected print brought a printer that does not
  4382. # archive this far; with it gone, nothing is archived.
  4383. return
  4384. # Otherwise archive the print anew rather than drop it, so it still
  4385. # gets its notification, usage tracking and history.
  4386. logger.warning(
  4387. "Expected archive %s for printer %s no longer exists; archiving the print anew",
  4388. expected_archive_id,
  4389. printer_id,
  4390. )
  4391. # Check if there's already a "printing" archive for this printer/file
  4392. # This prevents duplicates when backend restarts during an active print
  4393. from backend.app.models.archive import PrintArchive
  4394. existing_archive: PrintArchive | None = None
  4395. # Preferred match: subtask_id equality. MQTT reports the same subtask_id
  4396. # across a backend restart for the same print, so this is the most
  4397. # reliable way to reattach. Only a row still printing: a cancelled one
  4398. # has been through completion (usage, history, notifications) already,
  4399. # and reopening it would count the print twice.
  4400. if subtask_id:
  4401. by_id = await db.execute(
  4402. select(PrintArchive)
  4403. .where(PrintArchive.printer_id == printer_id)
  4404. .where(PrintArchive.subtask_id == subtask_id)
  4405. .where(PrintArchive.status == "printing")
  4406. .order_by(PrintArchive.created_at.desc())
  4407. .limit(1)
  4408. )
  4409. existing_archive = by_id.scalar_one_or_none()
  4410. # Fallback match: name-based lookup. Kept as-is for prints whose
  4411. # subtask_id is missing ("0" / local / non-cloud prints).
  4412. if existing_archive is None:
  4413. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  4414. archive_filenames = [f"{check_name}.3mf", f"{check_name}.gcode.3mf"]
  4415. # A print started from the printer's screen names its file in full,
  4416. # so the forms above double its extension. The file itself is the
  4417. # one exact match, and nothing looser is added (#3009).
  4418. if _subtask_is_the_file(subtask_name, filename):
  4419. archive_filenames.append(subtask_name)
  4420. existing = await db.execute(
  4421. select(PrintArchive)
  4422. .where(PrintArchive.printer_id == printer_id)
  4423. .where(PrintArchive.status == "printing")
  4424. .where(
  4425. or_(
  4426. PrintArchive.print_name == check_name,
  4427. PrintArchive.filename.in_(archive_filenames),
  4428. )
  4429. )
  4430. .order_by(PrintArchive.created_at.desc())
  4431. .limit(1)
  4432. )
  4433. existing_archive = existing.scalar_one_or_none()
  4434. if existing_archive:
  4435. # subtask_id match → always resume, regardless of age. Same print,
  4436. # just a backend restart.
  4437. subtask_match = bool(subtask_id and existing_archive.subtask_id == subtask_id)
  4438. if subtask_match:
  4439. logger.info("Resuming archive %s on subtask_id match (%s)", existing_archive.id, subtask_id)
  4440. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4441. if existing_archive.energy_start_kwh is None:
  4442. await _record_energy_start(existing_archive, printer_id, db, context="subtask-resume")
  4443. if not notification_sent:
  4444. archive_data = {
  4445. "print_time_seconds": existing_archive.print_time_seconds,
  4446. "created_by_id": existing_archive.created_by_id,
  4447. }
  4448. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4449. _load_objects_from_archive(existing_archive, printer_id, logger)
  4450. return
  4451. # Name-match only (no subtask_id to anchor on): decide resume vs.
  4452. # stale from the printer's *current* progress, not wall-clock age.
  4453. # A genuinely long print used to trip a blind 4h cutoff and have its
  4454. # live archive cancelled + duplicated on every backend restart
  4455. # (#1485). If the printer reports real progress, this name-matched
  4456. # 'printing' archive IS that ongoing print — resume it whatever its
  4457. # age. Only treat it as a stale leftover when the printer clearly
  4458. # shows a different, freshly-started print: near-0% progress on an
  4459. # archive far too old to still be at 0%. Unknown progress (printer
  4460. # not connected) never cancels — resuming is the safe default.
  4461. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  4462. live_status = printer_manager.get_status(printer_id)
  4463. live_progress = getattr(live_status, "progress", None) if live_status else None
  4464. looks_stale = (
  4465. live_progress is not None and live_progress < 1.0 and archive_age.total_seconds() > 2 * 60 * 60
  4466. )
  4467. # Two subtask ids are two prints, however young the archive: one
  4468. # whose completion was missed must not swallow the next print of
  4469. # the same file. Except Bambuddy's own reprint, which reuses the
  4470. # row and mints a fresh id (#1807): the id it last sent says so,
  4471. # and after a restart, which forgets it, this printer's queue job
  4472. # running the archive.
  4473. if (
  4474. not looks_stale
  4475. and subtask_id
  4476. and existing_archive.subtask_id
  4477. and existing_archive.subtask_id != subtask_id
  4478. ):
  4479. _client = printer_manager.get_client(printer_id)
  4480. _dispatched = str(getattr(_client, "last_dispatch_subtask_id", None) or "").strip()
  4481. if _dispatched:
  4482. looks_stale = _dispatched != subtask_id
  4483. else:
  4484. from backend.app.models.print_queue import PrintQueueItem as _PQI
  4485. queue_run = await db.scalar(
  4486. select(_PQI.id)
  4487. .where(_PQI.archive_id == existing_archive.id)
  4488. .where(_PQI.printer_id == printer_id)
  4489. .where(_PQI.status == "printing")
  4490. .limit(1)
  4491. )
  4492. looks_stale = queue_run is None
  4493. if looks_stale:
  4494. logger.warning(
  4495. "Found stale 'printing' archive %s (age: %s, printer progress %s%%, subtask %s, printer reports %s)"
  4496. " — marking cancelled and creating new archive",
  4497. existing_archive.id,
  4498. archive_age,
  4499. live_progress,
  4500. existing_archive.subtask_id,
  4501. subtask_id,
  4502. )
  4503. existing_archive.status = "cancelled"
  4504. # Canonical key, not a sentence (issue #2974). "No status update
  4505. # received" is what both stale paths actually observed; which of
  4506. # the two it was is already carried by ``status`` -- cancelled
  4507. # here, the reconciled outcome at the reconnect site -- so one
  4508. # key loses no information and gives the Statistics breakdown a
  4509. # single bucket instead of two untranslatable prose strings.
  4510. existing_archive.failure_reason = "noStatusUpdate"
  4511. await db.commit()
  4512. # Its print keys go with it; the new archive registers its own.
  4513. for _key in [k for k, v in _active_prints.items() if v == existing_archive.id]:
  4514. del _active_prints[_key]
  4515. # Fall through to create new archive (don't return)
  4516. else:
  4517. logger.info(
  4518. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  4519. )
  4520. # Track this as the active print
  4521. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  4522. # Attach subtask_id retroactively so future restarts can resume.
  4523. # Compare for inequality (not "is empty") to also pick up reprint
  4524. # dispatches that mint a fresh id — see #1807 for the bogus
  4525. # "Print Stopped" the strict-empty guard caused on reconnect.
  4526. if subtask_id and existing_archive.subtask_id != subtask_id:
  4527. existing_archive.subtask_id = subtask_id
  4528. await db.commit()
  4529. # Also set up energy tracking if not already tracked (#941: persisted column)
  4530. if existing_archive.energy_start_kwh is None:
  4531. await _record_energy_start(existing_archive, printer_id, db, context="existing-printing")
  4532. # Send notification with archive data (existing archive)
  4533. if not notification_sent:
  4534. archive_data = {
  4535. "print_time_seconds": existing_archive.print_time_seconds,
  4536. "created_by_id": existing_archive.created_by_id,
  4537. }
  4538. await _send_print_start_notification(printer_id, data, archive_data, logger)
  4539. # Extract printable objects from the archived 3MF file
  4540. _load_objects_from_archive(existing_archive, printer_id, logger)
  4541. return
  4542. # Build list of possible 3MF filenames to try
  4543. possible_names = []
  4544. # Bambu printers typically store files as "Name.gcode.3mf"
  4545. # The subtask_name is usually the best source for the filename
  4546. if subtask_name:
  4547. if _subtask_is_the_file(subtask_name, filename):
  4548. # A print started from the printer's own screen reports the
  4549. # file's full name, extension included. That is the file, so
  4550. # no extension is appended to it (#3009).
  4551. possible_names.append(subtask_name)
  4552. else:
  4553. # Try common Bambu naming patterns
  4554. possible_names.append(f"{subtask_name}.gcode.3mf")
  4555. possible_names.append(f"{subtask_name}.3mf")
  4556. # Try original filename with .3mf extension
  4557. if filename:
  4558. # Extract just the filename part, not the full path
  4559. fname = filename.split("/")[-1] if "/" in filename else filename
  4560. if fname.endswith(".3mf"):
  4561. possible_names.append(fname)
  4562. elif fname.endswith(".gcode"):
  4563. base = fname.rsplit(".", 1)[0]
  4564. possible_names.append(f"{base}.gcode.3mf")
  4565. possible_names.append(f"{base}.3mf")
  4566. else:
  4567. possible_names.append(f"{fname}.gcode.3mf")
  4568. possible_names.append(f"{fname}.3mf")
  4569. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  4570. space_variants = []
  4571. for name in possible_names:
  4572. if " " in name:
  4573. space_variants.append(name.replace(" ", "_"))
  4574. possible_names.extend(space_variants)
  4575. # Remove duplicates while preserving order
  4576. seen = set()
  4577. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  4578. logger.info("Trying filenames: %s", possible_names)
  4579. # Release the pooled DB connection before the 3MF FTP download. Reaching
  4580. # here means none of the expected-/existing-archive write branches ran
  4581. # (they all return earlier) — only SELECTs have executed on this path, so
  4582. # this commit persists nothing; it ends the read transaction so the
  4583. # connection returns to the pool during the download. That download tries
  4584. # up to five remote paths per candidate filename with retry/backoff and
  4585. # can run for minutes under FTP contention; holding the session across it
  4586. # pinned one pooled connection idle-in-transaction (issue #2572). No DB
  4587. # work runs during the download — the new-archive writes below re-acquire
  4588. # a fresh connection, and expire_on_commit=False keeps printer.* readable.
  4589. await db.commit()
  4590. # Try to find and download the 3MF file
  4591. temp_path = None
  4592. downloaded_filename = None
  4593. # Cache check: cover endpoint may have already pulled this 3MF during
  4594. # the print (frontend opens the card and shows the thumbnail) — reuse
  4595. # that file instead of re-downloading 36MB over the same FTP link that
  4596. # just served it (#972). The cache keys on a normalized filename so
  4597. # variants like "X", "X.3mf", "X.gcode.3mf" all collapse to one entry.
  4598. for try_filename in possible_names:
  4599. if not try_filename.endswith(".3mf"):
  4600. continue
  4601. cached = get_cached_3mf(printer_id, try_filename)
  4602. if cached:
  4603. logger.info("Reusing cached 3MF from %s (avoided duplicate FTP)", cached)
  4604. temp_path = cached
  4605. downloaded_filename = try_filename
  4606. break
  4607. # Does this printer keep the sliced file somewhere FTPS can reach? On
  4608. # H2-series and P2S the answer is routinely no — the file stays on
  4609. # internal eMMC and port 990 only ever serves external storage — and
  4610. # then the whole sweep below (six filenames x five directories x four
  4611. # retries, then the directory walk) is ~110 connections that cannot
  4612. # succeed. Skip it and say why (#2780).
  4613. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  4614. # Set when a lookup is abandoned because the printer's FTPS cool-off is
  4615. # running rather than because the file is somewhere unreachable. The
  4616. # distinction is the whole of #2957: one is permanent, the other clears
  4617. # in minutes with the file still sitting on the printer.
  4618. blocked_by_ftps_cooloff = False
  4619. # Set when a probe reached the printer and still came back without the
  4620. # file -- a timeout mid-transfer, a refused connection, anything that is
  4621. # not a clean "not here". A 550 raises FileNotOnPrinterError and is
  4622. # caught by name below, so a file that genuinely is not on the card
  4623. # leaves this False and schedules nothing. Anything else means the
  4624. # transfer, not the file, is what failed, and that does not last (#3063).
  4625. ftp_transfer_failed = False
  4626. # The print's name, for a fallback archive whose `subtask_name` the
  4627. # plate guard below had to disown. Display only, and deliberately kept
  4628. # apart from `subtask_name`: that variable is what every file lookup
  4629. # here is built from, and once a name has been shown to fetch another
  4630. # plate's 3MF it must not key `_active_prints` either, or the cover
  4631. # endpoint hands the same contradicted file to
  4632. # `_recover_fallback_archive` and fills the row in with it (#3126).
  4633. display_name_after_plate_reject: str | None = None
  4634. # Get FTP retry settings
  4635. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  4636. # ...but "the printer put it on eMMC" is where it went, not whether we
  4637. # can read it. An H2D with a card in mirrors the job to /cache and
  4638. # serves it happily, and skipping on the URL alone cost that reporter
  4639. # every archive for two days (#2856). So ask the printer instead of
  4640. # guessing: the dispatch named the exact file, which is one connection
  4641. # walking five paths rather than the sweep's ~110. Only when the probe
  4642. # comes back empty does the verdict's reason stand.
  4643. if not storage.reachable and not downloaded_filename and storage.probe_filename:
  4644. if ftps_handshake_blocked(printer.ip_address):
  4645. # Deliberately NOT recorded as a cool-off give-up. This branch
  4646. # only runs on an unreachable verdict, and that verdict is the
  4647. # honest, permanent reason the archive is empty — the probe was
  4648. # a long shot on top of it. Blaming the cool-off here would
  4649. # schedule a retry for a file sitting on internal eMMC, which is
  4650. # the sweep #2780 removed (#2957).
  4651. logger.debug(
  4652. "Not probing for %s on printer %s: its file service is not answering over TLS",
  4653. storage.probe_filename,
  4654. printer_id,
  4655. )
  4656. else:
  4657. probe_path = app_settings.archive_dir / "temp" / storage.probe_filename
  4658. probe_path.parent.mkdir(parents=True, exist_ok=True)
  4659. try:
  4660. probe_hit = await download_file_try_paths_async(
  4661. printer.ip_address,
  4662. printer.access_code,
  4663. ftp_probe_paths(storage.probe_filename),
  4664. probe_path,
  4665. socket_timeout=ftp_timeout,
  4666. printer_model=printer.model,
  4667. )
  4668. except Exception as e:
  4669. logger.debug("3MF probe for %s failed: %s", storage.probe_filename, e)
  4670. probe_hit = False
  4671. if probe_hit:
  4672. downloaded_filename = storage.probe_filename
  4673. temp_path = probe_path
  4674. cache_3mf_download(printer_id, downloaded_filename, probe_path)
  4675. # Naming the path, not just the file: a printer that keeps
  4676. # uploads around for weeks can serve a same-named copy of an
  4677. # earlier slice, and without the directory in the log that
  4678. # mismatch is invisible rather than merely rare (#1820).
  4679. logger.info(
  4680. "Found %s at %s over FTPS for printer %s even though the printer reported %s",
  4681. downloaded_filename,
  4682. probe_hit,
  4683. printer_id,
  4684. storage.reason,
  4685. )
  4686. if not storage.reachable and not downloaded_filename:
  4687. # Same opening words whether or not a probe ran, because that is
  4688. # the phrase support asks people to grep for — only the tail says
  4689. # which of the two happened.
  4690. logger.info(
  4691. "Skipping the 3MF lookup for printer %s: %s — %s",
  4692. printer_id,
  4693. storage.reason,
  4694. "no copy of it on external storage either"
  4695. if storage.probe_filename
  4696. else "the print file is not on storage Bambuddy can read over FTPS, so no path would find it",
  4697. )
  4698. for try_filename in possible_names if not downloaded_filename and storage.reachable else []:
  4699. if not try_filename.endswith(".3mf"):
  4700. continue
  4701. # Root (/) is where BambuStudio/OrcaSlicer uploads land on A1/P1-series
  4702. # printers, so try it first — deferring it to last cost #972's reporter
  4703. # ~48 minutes of retries on /cache//model//data//data/Metadata before
  4704. # landing on the path that actually had the file.
  4705. remote_paths = [
  4706. f"/{try_filename}",
  4707. f"/cache/{try_filename}",
  4708. f"/model/{try_filename}",
  4709. f"/data/{try_filename}",
  4710. f"/data/Metadata/{try_filename}",
  4711. ]
  4712. temp_path = app_settings.archive_dir / "temp" / try_filename
  4713. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4714. for remote_path in remote_paths:
  4715. if ftps_handshake_blocked(printer.ip_address):
  4716. # The printer's FTPS service is not completing a TLS
  4717. # handshake, so it has no path we could reach — walking the
  4718. # remaining candidates only re-runs the same failure
  4719. # (#2780). Fall through to the no-3MF archive now.
  4720. #
  4721. # Remember *why*, though. This is the one give-up that is
  4722. # temporary: the cool-off clears in minutes and the file was
  4723. # on the printer the whole time. The fallback archive is
  4724. # stamped with it so a retry can be scheduled, and so the
  4725. # Archives banner stops blaming storage (#2957).
  4726. blocked_by_ftps_cooloff = True
  4727. logger.warning(
  4728. "Giving up on the 3MF for printer %s: its file service is not answering over TLS",
  4729. printer_id,
  4730. )
  4731. break
  4732. logger.debug("Trying FTP download: %s", remote_path)
  4733. try:
  4734. if ftp_retry_enabled:
  4735. downloaded = await with_ftp_retry(
  4736. download_file_async,
  4737. printer.ip_address,
  4738. printer.access_code,
  4739. remote_path,
  4740. temp_path,
  4741. timeout=ftp_timeout,
  4742. socket_timeout=ftp_timeout,
  4743. printer_model=printer.model,
  4744. max_retries=ftp_retry_count,
  4745. retry_delay=ftp_retry_delay,
  4746. operation_name=f"Download 3MF from {remote_path}",
  4747. cooloff_ip=printer.ip_address,
  4748. non_retry_exceptions=(FileNotOnPrinterError,),
  4749. )
  4750. else:
  4751. downloaded = await download_file_async(
  4752. printer.ip_address,
  4753. printer.access_code,
  4754. remote_path,
  4755. temp_path,
  4756. timeout=ftp_timeout,
  4757. socket_timeout=ftp_timeout,
  4758. printer_model=printer.model,
  4759. )
  4760. if downloaded:
  4761. downloaded_filename = try_filename
  4762. logger.info("Downloaded: %s", remote_path)
  4763. # Populate shared cache so the cover endpoint (if it
  4764. # runs next) doesn't refetch the same 36MB over FTP.
  4765. cache_3mf_download(printer_id, try_filename, temp_path)
  4766. break
  4767. # with_ftp_retry returns None once it has spent its budget,
  4768. # and download_file_async returns False on a timeout, so an
  4769. # exhausted transfer arrives here rather than as an
  4770. # exception (#3063).
  4771. ftp_transfer_failed = True
  4772. except FileNotOnPrinterError:
  4773. # 550 — file isn't at this path. Advance to next candidate
  4774. # without burning the retry budget.
  4775. logger.debug("3MF not at %s (550), trying next path", remote_path)
  4776. except Exception as e:
  4777. ftp_transfer_failed = True
  4778. logger.debug("FTP download failed for %s: %s", remote_path, e)
  4779. if downloaded_filename or ftps_handshake_blocked(printer.ip_address):
  4780. break
  4781. # If still not found, try listing directories to find matching file
  4782. # Different printer models use different directory structures. Skipped
  4783. # when the printer's FTPS handshake is failing — the directory walk is
  4784. # five more connections that cannot get further than the download did.
  4785. if (
  4786. not downloaded_filename
  4787. and storage.reachable
  4788. and (filename or subtask_name)
  4789. and not ftps_handshake_blocked(printer.ip_address)
  4790. ):
  4791. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  4792. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  4793. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  4794. for search_dir in search_dirs:
  4795. if downloaded_filename:
  4796. break
  4797. try:
  4798. dir_files = await list_files_async(
  4799. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  4800. )
  4801. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  4802. if threemf_files:
  4803. logger.info(
  4804. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  4805. )
  4806. for f in dir_files:
  4807. if f.get("is_directory"):
  4808. continue
  4809. fname = f.get("name", "")
  4810. # Normalize both for comparison (spaces and underscores are equivalent)
  4811. fname_normalized = fname.lower().replace(" ", "_")
  4812. search_normalized = search_term.replace(" ", "_")
  4813. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  4814. logger.info("Found matching file in %s: %s", search_dir, fname)
  4815. temp_path = app_settings.archive_dir / "temp" / fname
  4816. temp_path.parent.mkdir(parents=True, exist_ok=True)
  4817. remote_full_path = posixpath.join(search_dir, fname)
  4818. if ftp_retry_enabled:
  4819. downloaded = await with_ftp_retry(
  4820. download_file_async,
  4821. printer.ip_address,
  4822. printer.access_code,
  4823. remote_full_path,
  4824. temp_path,
  4825. timeout=ftp_timeout,
  4826. socket_timeout=ftp_timeout,
  4827. printer_model=printer.model,
  4828. max_retries=ftp_retry_count,
  4829. retry_delay=ftp_retry_delay,
  4830. operation_name=f"Download 3MF from {remote_full_path}",
  4831. cooloff_ip=printer.ip_address,
  4832. )
  4833. else:
  4834. downloaded = await download_file_async(
  4835. printer.ip_address,
  4836. printer.access_code,
  4837. remote_full_path,
  4838. temp_path,
  4839. timeout=ftp_timeout,
  4840. socket_timeout=ftp_timeout,
  4841. printer_model=printer.model,
  4842. )
  4843. if downloaded:
  4844. downloaded_filename = fname
  4845. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  4846. cache_3mf_download(printer_id, fname, temp_path)
  4847. break
  4848. # The listing named the file, so it is on the card;
  4849. # only the transfer failed (#3063).
  4850. ftp_transfer_failed = True
  4851. except Exception as e:
  4852. logger.debug("Failed to list %s: %s", search_dir, e)
  4853. # Validate the downloaded 3MF actually matches the plate that's running
  4854. # (#1204): subtask_name lags across consecutive plates of the same model,
  4855. # so the first FTP candidate (built from subtask_name) can land on the
  4856. # previous plate's still-resident upload. Cross-check the slice_info
  4857. # plate index against the plate parsed from gcode_file (always fresh —
  4858. # it's the field whose change triggered this callback).
  4859. if downloaded_filename and temp_path:
  4860. expected_plate = parse_plate_id(filename)
  4861. actual_plate = peek_plate_index_in_3mf(temp_path) if expected_plate is not None else None
  4862. if expected_plate is not None and actual_plate is not None and actual_plate != expected_plate:
  4863. logger.warning(
  4864. "[CALLBACK] 3MF plate mismatch: downloaded %s reports plate %s but printer is "
  4865. "running plate %s — subtask_name=%r appears stale, retrying with corrected name",
  4866. downloaded_filename,
  4867. actual_plate,
  4868. expected_plate,
  4869. subtask_name,
  4870. )
  4871. corrected_subtask = swap_plate_suffix(subtask_name, expected_plate)
  4872. retry_succeeded = False
  4873. if corrected_subtask and corrected_subtask != subtask_name:
  4874. for try_filename in (f"{corrected_subtask}.gcode.3mf", f"{corrected_subtask}.3mf"):
  4875. retry_temp_path = app_settings.archive_dir / "temp" / try_filename
  4876. retry_temp_path.parent.mkdir(parents=True, exist_ok=True)
  4877. for remote_path in (
  4878. f"/{try_filename}",
  4879. f"/cache/{try_filename}",
  4880. f"/model/{try_filename}",
  4881. f"/data/{try_filename}",
  4882. f"/data/Metadata/{try_filename}",
  4883. ):
  4884. try:
  4885. if ftp_retry_enabled:
  4886. downloaded = await with_ftp_retry(
  4887. download_file_async,
  4888. printer.ip_address,
  4889. printer.access_code,
  4890. remote_path,
  4891. retry_temp_path,
  4892. timeout=ftp_timeout,
  4893. socket_timeout=ftp_timeout,
  4894. printer_model=printer.model,
  4895. max_retries=ftp_retry_count,
  4896. retry_delay=ftp_retry_delay,
  4897. operation_name=f"Re-download 3MF from {remote_path}",
  4898. cooloff_ip=printer.ip_address,
  4899. non_retry_exceptions=(FileNotOnPrinterError,),
  4900. )
  4901. else:
  4902. downloaded = await download_file_async(
  4903. printer.ip_address,
  4904. printer.access_code,
  4905. remote_path,
  4906. retry_temp_path,
  4907. timeout=ftp_timeout,
  4908. socket_timeout=ftp_timeout,
  4909. printer_model=printer.model,
  4910. )
  4911. if downloaded and peek_plate_index_in_3mf(retry_temp_path) == expected_plate:
  4912. logger.info(
  4913. "[CALLBACK] Re-download succeeded with corrected name %s "
  4914. "(plate %s) — replacing wrong file",
  4915. try_filename,
  4916. expected_plate,
  4917. )
  4918. try:
  4919. temp_path.unlink(missing_ok=True)
  4920. except OSError:
  4921. pass
  4922. temp_path = retry_temp_path
  4923. downloaded_filename = try_filename
  4924. subtask_name = corrected_subtask
  4925. cache_3mf_download(printer_id, try_filename, temp_path)
  4926. retry_succeeded = True
  4927. break
  4928. elif downloaded:
  4929. # Wrong plate again — discard and keep trying
  4930. try:
  4931. retry_temp_path.unlink(missing_ok=True)
  4932. except OSError:
  4933. pass
  4934. except FileNotOnPrinterError:
  4935. continue
  4936. except Exception as e:
  4937. logger.debug("Re-download failed for %s: %s", remote_path, e)
  4938. if retry_succeeded:
  4939. break
  4940. # If the retry didn't find a matching file, drop the wrong 3MF
  4941. # so the no-3MF fallback below creates an archive whose name
  4942. # at least reflects the right plate.
  4943. if not retry_succeeded:
  4944. logger.warning(
  4945. "[CALLBACK] Could not re-download correct plate %s — falling back to no-3MF archive",
  4946. expected_plate,
  4947. )
  4948. try:
  4949. temp_path.unlink(missing_ok=True)
  4950. except OSError:
  4951. pass
  4952. temp_path = None
  4953. downloaded_filename = None
  4954. # Whatever the sweep's transport did earlier, it is not why
  4955. # this archive ends up empty: a 3MF downloaded fine, it was
  4956. # just the wrong plate. Retrying would re-fetch that same
  4957. # contradicted file under the same stale names and hand it
  4958. # to _recover_fallback_archive, which checks that a
  4959. # candidate is a readable 3MF but not which plate it is --
  4960. # so the row would be filled in with another plate's
  4961. # filament and cost, the exact swap #2957 removed (#3063).
  4962. ftp_transfer_failed = False
  4963. # Disown the name for *lookups*: it has just been shown to
  4964. # fetch another plate's 3MF, and it keys `_active_prints`
  4965. # below, where the cover endpoint's own download of that
  4966. # same name would find this archive and fill it in with the
  4967. # file we are discarding here.
  4968. #
  4969. # Keep it for the *title*, which is a separate question.
  4970. # ``swap_plate_suffix`` returns None both for a name that
  4971. # carries no "- Plate N" / "_plate_N" suffix and for no
  4972. # name at all, and those are not the same situation: a name
  4973. # without a suffix holds no stale plate number to be wrong
  4974. # about. Blanking both uses at once dropped the project
  4975. # name too, and the row fell through to the gcode_file path
  4976. # titled "plate_1" though the real name was in hand.
  4977. # #1204's own premise is consecutive plates *of the same
  4978. # model*, so the project part is right either way (#3126).
  4979. display_name_after_plate_reject = corrected_subtask or subtask_name or None
  4980. subtask_name = corrected_subtask or ""
  4981. # Deleted while the 3MF was being fetched (that can take minutes): no
  4982. # archive, timelapse or tracking for a printer that will never report
  4983. # the print's end. forget_printer again: the download registered its
  4984. # 3MF cache entry after the delete cleared the id. (A delete committing
  4985. # while the archive is written is caught after its commit.)
  4986. if await _printer_gone(db, printer_id):
  4987. logger.info("Printer %s was deleted during the print-start download; not archiving", printer_id)
  4988. await forget_printer(printer_id)
  4989. return
  4990. if not downloaded_filename or not temp_path:
  4991. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  4992. # Create a fallback archive without 3MF data so the print is still tracked
  4993. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  4994. try:
  4995. from backend.app.models.archive import PrintArchive
  4996. # Why the card is empty. The two temporary causes outrank the
  4997. # storage verdict because they say the sweep never got a fair
  4998. # answer: a cool-off skipped it at the transport, and a failed
  4999. # transfer reached the printer but never finished. Either way
  5000. # the file is still on the card, so reporting where the printer
  5001. # files its jobs would describe a setting that is not the
  5002. # problem (#2957, #3063).
  5003. if blocked_by_ftps_cooloff:
  5004. no_3mf_reason = REASON_FTPS_COOLOFF
  5005. elif storage.reachable and ftp_transfer_failed:
  5006. no_3mf_reason = REASON_FTP_TRANSFER_FAILED
  5007. else:
  5008. no_3mf_reason = storage.reason
  5009. # Derive print name from subtask_name or filename. The
  5010. # plate guard's disowned name comes second: it is a real name
  5011. # for a real print, and only the gcode_file path is left
  5012. # otherwise -- which titles the row "plate_1" (#3126).
  5013. print_name = subtask_name or display_name_after_plate_reject or filename
  5014. if print_name:
  5015. # Clean up the name (remove extensions, path parts)
  5016. print_name = print_name.split("/")[-1]
  5017. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  5018. else:
  5019. print_name = "Unknown Print"
  5020. # Recover estimated print time from MQTT (best-effort for notifications)
  5021. fallback_print_time = None
  5022. mqtt_remaining = data.get("remaining_time")
  5023. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  5024. fallback_print_time = int(mqtt_remaining)
  5025. if fallback_print_time is None:
  5026. mc_remaining = (data.get("raw_data") or {}).get("mc_remaining_time")
  5027. if mc_remaining and isinstance(mc_remaining, (int, float)) and mc_remaining > 0:
  5028. fallback_print_time = int(mc_remaining * 60)
  5029. # Best-effort filament metadata from MQTT — see
  5030. # _extract_filament_data_from_mqtt. Without this the fallback
  5031. # archive's filament fields stayed NULL even though the AMS
  5032. # state at print start was sitting right there in `data`.
  5033. # The slicer's ams_mapping (when present) narrows the result
  5034. # to slots actually used by the print (#1533).
  5035. mqtt_filament_meta = _extract_filament_data_from_mqtt(data, _get_start_ams_mapping(data, None))
  5036. # Create minimal archive entry
  5037. fallback_archive = PrintArchive(
  5038. printer_id=printer_id,
  5039. filename=filename or f"{print_name}.3mf",
  5040. file_path="", # Empty - no 3MF file available
  5041. file_size=0,
  5042. print_name=print_name,
  5043. print_time_seconds=fallback_print_time,
  5044. status="printing",
  5045. started_at=datetime.now(timezone.utc),
  5046. subtask_id=subtask_id,
  5047. confirm_requested=await _ask_outcome_for_external_print(db, printer_id, subtask_name),
  5048. filament_type=mqtt_filament_meta.get("filament_type"),
  5049. filament_color=mqtt_filament_meta.get("filament_color"),
  5050. extra_data={
  5051. "no_3mf_available": True,
  5052. # Why the card is empty, when we know -- see above. The
  5053. # banner reads this to stop telling H2/P2 owners to
  5054. # switch on a setting that is already on and would not
  5055. # have helped (#2780).
  5056. "no_3mf_reason": no_3mf_reason,
  5057. "original_subtask": subtask_name or display_name_after_plate_reject or "",
  5058. "_print_data": data,
  5059. },
  5060. )
  5061. db.add(fallback_archive)
  5062. try:
  5063. await db.commit()
  5064. except IntegrityError:
  5065. # Not "Failed to create fallback archive" below, and no
  5066. # start notification for a printer that is gone.
  5067. if await _refused_for_deleted_printer(db, printer_id, "its fallback archive was written"):
  5068. return
  5069. raise
  5070. await db.refresh(fallback_archive)
  5071. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  5072. if await _drop_archive_of_deleted_printer(db, printer_id, fallback_archive.id):
  5073. return
  5074. _maybe_start_layer_timelapse(printer, printer_id, fallback_archive.id)
  5075. # Track as active print
  5076. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  5077. if filename:
  5078. _active_prints[(printer_id, filename)] = fallback_archive.id
  5079. if subtask_name:
  5080. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  5081. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  5082. # Record starting energy if smart plug available (#941: persisted column)
  5083. await _record_energy_start(fallback_archive, printer_id, db, context="fallback")
  5084. # Send WebSocket notification
  5085. await ws_manager.send_archive_created(
  5086. {
  5087. "id": fallback_archive.id,
  5088. "printer_id": fallback_archive.printer_id,
  5089. "filename": fallback_archive.filename,
  5090. "print_name": fallback_archive.print_name,
  5091. "status": fallback_archive.status,
  5092. }
  5093. )
  5094. # MQTT relay - publish archive created
  5095. try:
  5096. await mqtt_relay.on_archive_created(
  5097. archive_id=fallback_archive.id,
  5098. print_name=fallback_archive.print_name,
  5099. printer_name=printer.name,
  5100. status=fallback_archive.status,
  5101. )
  5102. except Exception:
  5103. pass # Don't fail if MQTT fails
  5104. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  5105. try:
  5106. await _store_spoolman_print_data(
  5107. printer_id,
  5108. fallback_archive.id,
  5109. fallback_archive.file_path,
  5110. db,
  5111. printer_manager,
  5112. ams_mapping=_get_start_ams_mapping(data, fallback_archive.id),
  5113. plate_id=_get_start_plate_id(fallback_archive.id),
  5114. )
  5115. except Exception as e:
  5116. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  5117. # Both temporary give-ups are worth coming back for, and for
  5118. # the same reason: the file is on the printer and the last look
  5119. # failed at the transport rather than finding nothing. One waits
  5120. # out the handshake block (#2957), the other waits for the
  5121. # printer to stop being busy (#3063). Deliberately not scheduled
  5122. # for a storage verdict: a file on internal eMMC will not appear
  5123. # at any FTPS path however long we wait, and retrying it is
  5124. # exactly the sweep #2780 removed.
  5125. if no_3mf_reason in (REASON_FTPS_COOLOFF, REASON_FTP_TRANSFER_FAILED) and possible_names:
  5126. # `possible_names`, not the raw MQTT strings: it is the exact
  5127. # list this flow just tried, already stripped of any path
  5128. # (`filename` arrives as "/data/Metadata/plate_1.gcode" on
  5129. # some firmware) and deduped.
  5130. _schedule_fallback_3mf_retry(
  5131. printer_id=printer_id,
  5132. archive_id=fallback_archive.id,
  5133. filenames=list(possible_names),
  5134. reason=no_3mf_reason,
  5135. )
  5136. # Send notification without archive data (file not found)
  5137. if not notification_sent:
  5138. await _send_print_start_notification(printer_id, data, logger=logger)
  5139. # The same baseline the other two on_print_start branches take
  5140. # (#2704), and last for the same reason they are: it lists the
  5141. # printer's timelapse directory, so a slow card must not delay
  5142. # the _active_prints registration, the energy reading, the
  5143. # archive-created event or the start notification above it.
  5144. #
  5145. # This branch never took one, so every no-3MF archive reached
  5146. # completion with no baseline in memory and none on the row, and
  5147. # the completion scan fell into its "snapshot now" fallback --
  5148. # which runs after the printer has written the video, so the new
  5149. # file landed inside the baseline and no diff ever matched
  5150. # (#2957 follow-up).
  5151. #
  5152. # Skipped when the FTPS cool-off is what produced this fallback:
  5153. # the listing needs the same connection that just failed, so it
  5154. # could only record that the card was unreadable. The scan
  5155. # handles that case by refusing to choose between candidates.
  5156. if not blocked_by_ftps_cooloff:
  5157. await _capture_timelapse_baseline_at_start(
  5158. printer, printer_id, logger, archive_id=fallback_archive.id
  5159. )
  5160. await _forget_if_printer_gone(printer_id)
  5161. return
  5162. except Exception as e:
  5163. logger.error("Failed to create fallback archive: %s", e)
  5164. # Send notification without archive data (file not found)
  5165. if not notification_sent:
  5166. await _send_print_start_notification(printer_id, data, logger=logger)
  5167. return
  5168. try:
  5169. # Archive the file with status "printing"
  5170. service = ArchiveService(db)
  5171. try:
  5172. archive = await service.archive_print(
  5173. printer_id=printer_id,
  5174. source_file=temp_path,
  5175. print_data={**data, "status": "printing"},
  5176. subtask_id=subtask_id,
  5177. )
  5178. except IntegrityError:
  5179. # archive_print removed the folder it had copied the 3MF into.
  5180. if await _refused_for_deleted_printer(db, printer_id, "its archive was written"):
  5181. return
  5182. raise
  5183. if archive:
  5184. # Ask-for-outcome for a print Bambuddy did not dispatch (#1898).
  5185. # Set on the row rather than passed to archive_print, which also
  5186. # serves the queue dispatcher — there the queue item decides.
  5187. # Guarded because this branch has no ``except``: an unhandled
  5188. # write error would take the _active_prints registration, the
  5189. # start notification, the energy reading and the timelapse
  5190. # baseline below it with it, and a missing prompt is by far the
  5191. # cheaper failure.
  5192. archive_id = archive.id
  5193. try:
  5194. if await _ask_outcome_for_external_print(db, printer_id, subtask_name):
  5195. archive.confirm_requested = True
  5196. await db.commit()
  5197. except Exception as e:
  5198. logger.warning("Could not flag archive %s for the outcome prompt: %s", archive_id, e)
  5199. # The rollback expires every loaded object, and on an async
  5200. # session reading one afterwards raises instead of
  5201. # reloading, so the two this branch goes on to use are
  5202. # fetched again. The archive itself was committed by
  5203. # archive_print; only the flag is lost.
  5204. try:
  5205. await db.rollback()
  5206. archive = await db.get(PrintArchive, archive_id)
  5207. printer = await db.get(Printer, printer_id)
  5208. except Exception as reload_error:
  5209. logger.warning(
  5210. "Could not reload archive %s after the failed flag write: %s", archive_id, reload_error
  5211. )
  5212. if await _drop_archive_of_deleted_printer(db, printer_id, archive_id):
  5213. return
  5214. # Track this active print (use both original filename and downloaded filename)
  5215. _active_prints[(printer_id, downloaded_filename)] = archive.id
  5216. if filename and filename != downloaded_filename:
  5217. _active_prints[(printer_id, filename)] = archive.id
  5218. if subtask_name:
  5219. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  5220. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  5221. _maybe_start_layer_timelapse(printer, printer_id, archive.id)
  5222. # Record starting energy from smart plug if available (#941: persisted column)
  5223. await _record_energy_start(archive, printer_id, db, context="auto-archive")
  5224. await ws_manager.send_archive_created(
  5225. {
  5226. "id": archive.id,
  5227. "printer_id": archive.printer_id,
  5228. "filename": archive.filename,
  5229. "print_name": archive.print_name,
  5230. "status": archive.status,
  5231. }
  5232. )
  5233. # MQTT relay - publish archive created
  5234. try:
  5235. await mqtt_relay.on_archive_created(
  5236. archive_id=archive.id,
  5237. print_name=archive.print_name,
  5238. printer_name=printer.name,
  5239. status=archive.status,
  5240. )
  5241. except Exception:
  5242. pass # Don't fail if MQTT fails
  5243. # Send notification with archive data (new archive created)
  5244. if not notification_sent:
  5245. archive_data = {
  5246. "print_time_seconds": archive.print_time_seconds,
  5247. "created_by_id": archive.created_by_id,
  5248. }
  5249. await _send_print_start_notification(printer_id, data, archive_data, logger)
  5250. # Extract printable objects for skip object functionality
  5251. try:
  5252. from backend.app.services.archive import extract_printable_objects_from_3mf
  5253. client = printer_manager.get_client(printer_id)
  5254. if client:
  5255. with open(temp_path, "rb") as f:
  5256. threemf_data = f.read()
  5257. # Extract with positions for UI overlay, scoped to the
  5258. # plate that is printing — an all-plates 3MF carries
  5259. # every plate's objects (#2522).
  5260. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  5261. threemf_data,
  5262. plate_number=resolve_plate_id(client.state),
  5263. include_positions=True,
  5264. )
  5265. if printable_objects:
  5266. # Store objects in printer state
  5267. client.state.printable_objects = printable_objects
  5268. client.state.printable_objects_bbox_all = bbox_all
  5269. client.state.skipped_objects = [] # Reset skipped objects for new print
  5270. logger.info(
  5271. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  5272. )
  5273. except Exception as e:
  5274. logger.debug("Failed to extract printable objects: %s", e)
  5275. # Store Spoolman tracking data for per-filament usage reporting
  5276. try:
  5277. await _store_spoolman_print_data(
  5278. printer_id,
  5279. archive.id,
  5280. archive.file_path,
  5281. db,
  5282. printer_manager,
  5283. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5284. plate_id=_get_start_plate_id(archive.id),
  5285. )
  5286. except Exception as e:
  5287. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  5288. # Price the print from its spools now rather than only at completion (#3261)
  5289. _schedule_archive_cost_estimate(
  5290. printer_id,
  5291. archive.id,
  5292. printer_manager,
  5293. ams_mapping=_get_start_ams_mapping(data, archive.id),
  5294. plate_id=_get_start_plate_id(archive.id),
  5295. session_factory=async_session,
  5296. )
  5297. # Capture timelapse file baseline for snapshot-diff on completion
  5298. await _capture_timelapse_baseline_at_start(printer, printer_id, logger, archive_id=archive.id)
  5299. await _forget_if_printer_gone(printer_id)
  5300. finally:
  5301. # Keep temp_path around until print completes so the cover endpoint
  5302. # can reuse it (#972). Cache eviction in on_print_complete deletes
  5303. # the file. If the cache entry was evicted early (file vanished),
  5304. # clean up any stragglers here to avoid leaking disk on retries.
  5305. cached_now = get_cached_3mf(printer_id, downloaded_filename) if downloaded_filename else None
  5306. if temp_path and temp_path.exists() and cached_now != temp_path:
  5307. temp_path.unlink()
  5308. _TIMELAPSE_VIDEO_EXTENSIONS = (".mp4", ".avi")
  5309. # Poll schedule for the post-print timelapse scan (#2704). Module-level so
  5310. # tests can shrink them without waiting out real delays.
  5311. #
  5312. # This replaced a fixed [5, 10, 20, 30] retry ladder, i.e. roughly 65 s of
  5313. # looking. Across 247 support bundles the attempt that found the video was #1
  5314. # 272 times, then 17 / 13 / 13 — a flat tail against the cutoff rather than a
  5315. # decaying one, which is the signature of a budget that expires while files are
  5316. # still arriving. 457 scans were scheduled and only 262 ever attached. Big
  5317. # prints make big videos and the printer writes them after the print ends, so
  5318. # the poll now runs for minutes and costs one FTP LIST per round.
  5319. _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS: float = 5.0
  5320. _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS: float = 30.0
  5321. _TIMELAPSE_SCAN_TIMEOUT_SECONDS: float = 900.0
  5322. def _timelapse_scan_max_attempts() -> int:
  5323. """Round cap for the poll, derived from the wall-clock budget.
  5324. The deadline alone is not a sufficient bound: it assumes each round really
  5325. waits, which stops being true the moment ``asyncio.sleep`` is patched out,
  5326. and an FTP list that fails immediately would otherwise spin against the
  5327. printer at full speed for the whole window. Whichever bound is reached
  5328. first ends the poll.
  5329. """
  5330. if _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS <= 0:
  5331. # A zero interval makes the wall-clock budget meaningless; fall back to
  5332. # the round count the production interval would have given.
  5333. return 32
  5334. return max(1, int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS // _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS) + 1)
  5335. async def _claimed_timelapse_names(db, printer_id: int, exclude_archive_id: int) -> set[str]:
  5336. """Video filenames already attached to some other archive of this printer.
  5337. Used to disambiguate when more than one file is new since the baseline —
  5338. which happens when a previous print's video landed after this print's
  5339. baseline was taken. Ordering the candidates would be the obvious fix and is
  5340. the wrong one: it can only be done on mtime or on the filename timestamp,
  5341. both of which come from the printer's own clock, and a LAN-only printer
  5342. can't reach Bambu's NTP server. Exclusion needs no clock at all.
  5343. ``attach_timelapse`` saves the video into the archive directory under the
  5344. printer's original filename, and the later MP4 conversion keeps the stem,
  5345. so the stem of ``timelapse_path`` recovers what was claimed.
  5346. """
  5347. from backend.app.models.archive import PrintArchive
  5348. rows = await db.execute(
  5349. select(PrintArchive.timelapse_path).where(
  5350. PrintArchive.printer_id == printer_id,
  5351. PrintArchive.id != exclude_archive_id,
  5352. PrintArchive.timelapse_path.is_not(None),
  5353. )
  5354. )
  5355. return {Path(p).stem for p in rows.scalars().all() if p}
  5356. def _timelapse_listing_is_trustworthy(printer) -> bool:
  5357. """Whether an *empty* timelapse listing for *printer* can be believed.
  5358. ``list_files_async`` answers ``[]`` when its connect fails rather than
  5359. raising, so a card behind the FTPS handshake cool-off is indistinguishable
  5360. from one holding no videos. Everywhere that only wants to know "is there a
  5361. video yet" the difference does not matter — both mean "not yet, retry".
  5362. It matters where an empty listing is recorded as a *baseline*. Recording
  5363. "the card held nothing" for a card that was never read means every video on
  5364. it counts as new once the cool-off expires, and the completion scan then
  5365. attaches a stale video to this print and deletes it from the printer
  5366. (#2957 follow-up). Those two callers ask this first.
  5367. """
  5368. from backend.app.services.bambu_ftp import ftps_handshake_blocked
  5369. ip_address = getattr(printer, "ip_address", None)
  5370. if not ip_address:
  5371. return True
  5372. return not ftps_handshake_blocked(ip_address)
  5373. async def _list_timelapse_videos(printer) -> tuple[list[dict], str | None]:
  5374. """List video files from printer's timelapse directory.
  5375. Finds MP4 (X1/A1 series) and AVI (P1 series) timelapse files.
  5376. Returns (video_files, found_path) where video_files is a list of file dicts
  5377. and found_path is the directory where they were found, or ([], None).
  5378. An empty return does not distinguish "no videos" from "could not read the
  5379. card" — see :func:`_timelapse_listing_is_trustworthy`, which the two
  5380. baseline callers consult before believing one.
  5381. """
  5382. from backend.app.services.bambu_ftp import list_files_async
  5383. logger = logging.getLogger(__name__)
  5384. # No card in the slot means no /timelapse to walk — four connections that
  5385. # can only fail, on a path whose failures are swallowed and so would go on
  5386. # costing time silently forever (#2780).
  5387. #
  5388. # ``getattr`` rather than ``printer.id``: every dereference below happens
  5389. # inside the loop's own try/except, so a caller that passed something
  5390. # unexpected used to get an empty listing rather than an exception. Keep
  5391. # that, instead of making this gate the first thing that can raise here.
  5392. printer_id = getattr(printer, "id", None)
  5393. if printer_id is not None and not external_storage_present(printer_manager.get_status(printer_id)):
  5394. logger.debug("[TIMELAPSE] Skipping the scan for printer %s: it reports no external storage", printer_id)
  5395. return [], None
  5396. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  5397. try:
  5398. found_files = await list_files_async(
  5399. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  5400. )
  5401. if found_files:
  5402. video_files = [
  5403. f
  5404. for f in found_files
  5405. if not f.get("is_directory") and f.get("name", "").lower().endswith(_TIMELAPSE_VIDEO_EXTENSIONS)
  5406. ]
  5407. if video_files:
  5408. return video_files, timelapse_path
  5409. except Exception as e:
  5410. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  5411. continue
  5412. return [], None
  5413. async def _capture_timelapse_baseline_at_start(
  5414. printer, printer_id: int, logger: logging.Logger, archive_id: int | None = None
  5415. ) -> None:
  5416. """Snapshot the printer's timelapse directory at print start so the
  5417. completion-time scan can pick the new file by set-difference.
  5418. Must be called from every on_print_start path that proceeds to a real
  5419. print — both the new-archive branch and the expected-archive branch (which
  5420. queue / VP-dispatched prints take). Without a baseline,
  5421. _scan_for_timelapse_with_retries falls into its "take baseline now"
  5422. fallback that runs AFTER the new MP4 has already landed on the SD card,
  5423. so the new file ends up in the "baseline" set and no diff ever matches.
  5424. Bambu printers in LAN-only mode don't sync NTP, so mtime ordering is
  5425. unreliable — the snapshot-diff approach sidesteps that entirely.
  5426. When ``archive_id`` is known the baseline is also written to the archive
  5427. row, so it survives a restart and the manual "Scan for Timelapse" button
  5428. can run the same diff instead of falling back to clock-based matching
  5429. (#2704). Only baselines taken at print start are persisted — one taken at
  5430. completion already contains the new video and would poison a later scan.
  5431. """
  5432. names: set[str] | None = None
  5433. try:
  5434. if not _timelapse_listing_is_trustworthy(printer):
  5435. # Recorded anyway, deliberately. An empty baseline taken off a card
  5436. # we could not read is not authoritative, but it is still the right
  5437. # *default*: Bambuddy deletes each video from the printer once it is
  5438. # attached, so the usual card holds exactly one video at completion
  5439. # and an empty baseline resolves it correctly. Persisting NULL
  5440. # instead would send completion to take its own snapshot, by which
  5441. # point this print's video is on the card and would be swallowed by
  5442. # it. The ambiguity is handled where it actually bites — see
  5443. # ``require_unambiguous`` in the scan (#2957 follow-up).
  5444. logger.warning(
  5445. "[TIMELAPSE] Baseline for printer %s taken while its file service is in the FTPS "
  5446. "handshake cool-off, so the card could not be read — treating it as empty",
  5447. printer_id,
  5448. )
  5449. baseline_files, _ = await _list_timelapse_videos(printer)
  5450. names = {f.get("name", "") for f in baseline_files}
  5451. _timelapse_baselines[printer_id] = names
  5452. logger.info(
  5453. "[TIMELAPSE] Baseline at print start: %s video files for printer %s",
  5454. len(names),
  5455. printer_id,
  5456. )
  5457. except Exception as e:
  5458. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  5459. if archive_id is None:
  5460. return
  5461. try:
  5462. async with async_session() as db:
  5463. from backend.app.models.archive import PrintArchive
  5464. archive = await db.get(PrintArchive, archive_id)
  5465. if archive is not None:
  5466. # Written even when the listing failed, and then as NULL. A
  5467. # reprint reuses the archive row, so leaving the previous run's
  5468. # baseline in place would have the scan diff this print against
  5469. # the state of the printer before the *last* one — and a stale
  5470. # baseline reads as authoritative, where NULL correctly falls
  5471. # back to a fresh snapshot.
  5472. archive.timelapse_baseline = sorted(names) if names is not None else None
  5473. await db.commit()
  5474. except Exception as e:
  5475. # In-memory baseline still covers the normal completion path.
  5476. logger.warning("[TIMELAPSE] Failed to persist baseline for archive %s: %s", archive_id, e)
  5477. async def _scan_for_timelapse_with_retries(
  5478. archive_id: int, baseline_names: set[str] | None = None, *, plate_id: int | None = None
  5479. ):
  5480. """Poll the printer for this print's timelapse and attach it.
  5481. Snapshot diff, not timestamp matching: a printer in LAN-only mode cannot
  5482. reach Bambu's NTP server, so the clock behind both the filename and the FTP
  5483. mtime is arbitrarily wrong — one reporter's P1S was six and a half days out
  5484. (#2704). Comparing the current listing against the set of filenames that
  5485. existed when the print started needs no clock at all, because the printer
  5486. writes the video only once the print has ended.
  5487. Baseline precedence: the caller's in-memory set, then the one persisted on
  5488. the archive at print start, then a snapshot taken now. The last of those is
  5489. a poor substitute — by completion the new video may already be on the card,
  5490. in which case it lands in the "baseline" and no diff can ever match — but it
  5491. is all that is available for a print that began before Bambuddy started.
  5492. On success the video is deleted from the printer, which keeps ``/timelapse``
  5493. down to the unclaimed files and makes the next diff unambiguous.
  5494. """
  5495. logger = logging.getLogger(__name__)
  5496. # Cleared when the baseline had to be taken off a card we could not read, so
  5497. # the attach step refuses to choose between several candidates (#2957).
  5498. baseline_trusted = True
  5499. # --- Phase 1: establish the baseline -------------------------------------
  5500. try:
  5501. async with async_session() as db:
  5502. from backend.app.models.printer import Printer
  5503. service = ArchiveService(db)
  5504. archive = await service.get_archive(archive_id)
  5505. if not archive:
  5506. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  5507. return
  5508. if archive.timelapse_path:
  5509. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  5510. return
  5511. if not archive.printer_id:
  5512. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  5513. return
  5514. if baseline_names is not None:
  5515. logger.info(
  5516. "[TIMELAPSE] Using print-start baseline: %s existing video files for archive %s",
  5517. len(baseline_names),
  5518. archive_id,
  5519. )
  5520. elif archive.timelapse_baseline is not None:
  5521. # Persisted at print start — survives a restart mid-print.
  5522. baseline_names = set(archive.timelapse_baseline)
  5523. logger.info(
  5524. "[TIMELAPSE] Using stored baseline: %s existing video files for archive %s",
  5525. len(baseline_names),
  5526. archive_id,
  5527. )
  5528. else:
  5529. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5530. printer = result.scalar_one_or_none()
  5531. if not printer:
  5532. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  5533. return
  5534. if not _timelapse_listing_is_trustworthy(printer):
  5535. # The card is unreadable at the one moment a baseline has to
  5536. # be taken, so the empty listing below means "we never
  5537. # looked", not "these are all new". Carry on with it anyway
  5538. # — the usual card holds exactly one video, which resolves
  5539. # correctly — but stop the poll from *choosing* between
  5540. # several, which is how a stale video got attached to this
  5541. # print and then deleted off the printer (#2957 follow-up).
  5542. baseline_trusted = False
  5543. logger.warning(
  5544. "[TIMELAPSE] Baseline for archive %s taken while printer %s is in the FTPS "
  5545. "handshake cool-off. A single new video still resolves; several will not be "
  5546. "guessed between — use Scan for Timelapse to pick one by hand",
  5547. archive_id,
  5548. archive.printer_id,
  5549. )
  5550. baseline_files, _ = await _list_timelapse_videos(printer)
  5551. baseline_names = {f.get("name", "") for f in baseline_files}
  5552. logger.info(
  5553. "[TIMELAPSE] Baseline snapshot (fallback): %s existing video files for archive %s",
  5554. len(baseline_names),
  5555. archive_id,
  5556. )
  5557. except Exception as e:
  5558. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  5559. return
  5560. # --- Phase 2: poll for a file that was not there when the print began -----
  5561. deadline = time.monotonic() + _TIMELAPSE_SCAN_TIMEOUT_SECONDS
  5562. max_attempts = _timelapse_scan_max_attempts()
  5563. seen_names: set[str] = set()
  5564. delay = _TIMELAPSE_SCAN_FIRST_DELAY_SECONDS
  5565. attempt = 0
  5566. while True:
  5567. await asyncio.sleep(delay)
  5568. delay = _TIMELAPSE_SCAN_POLL_INTERVAL_SECONDS
  5569. attempt += 1
  5570. try:
  5571. from backend.app.models.printer import Printer
  5572. # Read phase: fetch archive + printer in a short session and release
  5573. # the pooled connection BEFORE the FTP list/download below. Holding it
  5574. # across the FTP round-trips left one connection idle-in-transaction per
  5575. # in-flight scan (issue #2572).
  5576. async with async_session() as db:
  5577. service = ArchiveService(db)
  5578. archive = await service.get_archive(archive_id)
  5579. if not archive:
  5580. logger.warning("[TIMELAPSE] Archive %s not found, stopping poll", archive_id)
  5581. return
  5582. if archive.timelapse_path:
  5583. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping poll", archive_id)
  5584. return
  5585. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  5586. printer = result.scalar_one_or_none()
  5587. if not printer:
  5588. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping poll", archive_id)
  5589. return
  5590. claimed = await _claimed_timelapse_names(db, archive.printer_id, archive_id)
  5591. # I/O phase (no DB connection held): FTP list + download.
  5592. video_files, found_path = await _list_timelapse_videos(printer)
  5593. # The poll can run for dozens of rounds, so only narrate a round
  5594. # that saw something change. Repeating the whole listing every 30 s
  5595. # would bury the one interesting line in the support bundle.
  5596. names_now = {f.get("name", "") for f in video_files}
  5597. changed = attempt == 1 or names_now != seen_names
  5598. seen_names = names_now
  5599. speak = logger.info if changed else logger.debug
  5600. if video_files:
  5601. speak("[TIMELAPSE] Attempt %s: Found %s video files in %s", attempt, len(video_files), found_path)
  5602. if changed:
  5603. for f in video_files[:5]:
  5604. logger.info("[TIMELAPSE] - %s", f.get("name"))
  5605. attached = await _attach_first_unclaimed_timelapse(
  5606. archive_id,
  5607. printer,
  5608. video_files,
  5609. baseline_names,
  5610. claimed,
  5611. attempt,
  5612. logger,
  5613. quiet=not changed,
  5614. require_unambiguous=not baseline_trusted,
  5615. plate_id=plate_id,
  5616. )
  5617. if attached:
  5618. return
  5619. else:
  5620. speak("[TIMELAPSE] Attempt %s: No video files found, will retry", attempt)
  5621. except Exception as e:
  5622. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  5623. if attempt >= max_attempts or time.monotonic() >= deadline:
  5624. break
  5625. # No name-match fallback: it compared the print name against the filename,
  5626. # and Bambu firmware only ever writes "video_<timestamp>". Across 247 support
  5627. # bundles it fired 159 times and matched zero times, so all it added was a
  5628. # misleading log line before giving up.
  5629. logger.warning(
  5630. "[TIMELAPSE] No new video appeared for archive %s within %ss, giving up",
  5631. archive_id,
  5632. int(_TIMELAPSE_SCAN_TIMEOUT_SECONDS),
  5633. )
  5634. async def _attach_first_unclaimed_timelapse(
  5635. archive_id: int,
  5636. printer,
  5637. video_files: list[dict],
  5638. baseline_names: set[str],
  5639. claimed: set[str],
  5640. attempt: int,
  5641. logger: logging.Logger,
  5642. *,
  5643. quiet: bool = False,
  5644. require_unambiguous: bool = False,
  5645. plate_id: int | None = None,
  5646. ) -> bool:
  5647. """Download and attach the one video that belongs to this print.
  5648. A candidate is any file absent from the print-start baseline. More than one
  5649. can qualify when a previous print's video landed late, after this print's
  5650. baseline was taken — those are filtered out by name, because they are
  5651. already attached to another archive. Sorting the candidates instead would
  5652. mean sorting on mtime or on the filename timestamp, both of which come from
  5653. the printer's unsynced clock.
  5654. Returns True once a video is attached. The printer's copy is deleted only
  5655. after the attach succeeds on bytes whose length matched the listing.
  5656. ``quiet`` downgrades the "nothing yet" lines to DEBUG when the caller has
  5657. already seen this exact listing — the poll runs for many rounds and only the
  5658. rounds where something changed are worth an INFO line.
  5659. """
  5660. from backend.app.services.bambu_ftp import (
  5661. delete_archived_timelapse,
  5662. download_file_bytes_async,
  5663. remote_file_settled,
  5664. )
  5665. speak = logger.debug if quiet else logger.info
  5666. new_files = [f for f in video_files if f.get("name", "") not in baseline_names]
  5667. if not new_files:
  5668. speak("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  5669. return False
  5670. candidates = [f for f in new_files if Path(f.get("name", "")).stem not in claimed]
  5671. if not candidates:
  5672. speak(
  5673. "[TIMELAPSE] Attempt %s: %s new file(s), all already attached to other archives, will retry",
  5674. attempt,
  5675. len(new_files),
  5676. )
  5677. return False
  5678. if len(candidates) > 1:
  5679. if require_unambiguous:
  5680. # The baseline is not evidence -- it was taken off a card that could
  5681. # not be read -- so "new since the baseline" does not narrow these
  5682. # down at all. Taking the first would attach an arbitrary video to
  5683. # this print and then delete it from the printer.
  5684. logger.warning(
  5685. "[TIMELAPSE] Attempt %s: %s unclaimed videos (%s) and no baseline to tell them apart — "
  5686. "leaving all of them on the printer for manual selection",
  5687. attempt,
  5688. len(candidates),
  5689. ", ".join(str(f.get("name")) for f in candidates),
  5690. )
  5691. return False
  5692. logger.warning(
  5693. "[TIMELAPSE] Attempt %s: %s unclaimed new files (%s) — taking the first; "
  5694. "the rest stay on the printer for manual selection",
  5695. attempt,
  5696. len(candidates),
  5697. ", ".join(str(f.get("name")) for f in candidates),
  5698. )
  5699. target = candidates[0]
  5700. file_name = target.get("name")
  5701. remote_path = target.get("path") or f"/timelapse/{file_name}"
  5702. logger.info(
  5703. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  5704. attempt,
  5705. file_name,
  5706. archive_id,
  5707. )
  5708. # The listing always carries a size (`list_files` skips entries it can't
  5709. # parse), but read it explicitly: the delete below is destructive and must
  5710. # depend on a size we actually had, not on one we hoped was there.
  5711. expected_size = target.get("size")
  5712. timelapse_data = await download_file_bytes_async(
  5713. printer.ip_address,
  5714. printer.access_code,
  5715. remote_path,
  5716. printer_model=printer.model,
  5717. expected_size=expected_size,
  5718. )
  5719. if not timelapse_data:
  5720. # Short or failed transfer. The printer keeps its copy, so the next
  5721. # round can try again — which is exactly why the delete below is
  5722. # gated on a verified download.
  5723. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  5724. return False
  5725. # The length check above proves we got what the listing said, not that the
  5726. # printer had finished writing. A video still being written can be listed
  5727. # short, served short, and pass — so confirm it has stopped growing before
  5728. # committing to it and deleting the original (#2704).
  5729. if not await remote_file_settled(
  5730. printer.ip_address,
  5731. printer.access_code,
  5732. remote_path,
  5733. len(timelapse_data),
  5734. printer_model=printer.model,
  5735. ):
  5736. return False
  5737. # Write phase: attach in a fresh short-lived session.
  5738. async with async_session() as db:
  5739. success = await ArchiveService(db).attach_timelapse(archive_id, timelapse_data, file_name, plate_id=plate_id)
  5740. if not success:
  5741. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  5742. return False
  5743. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  5744. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  5745. await delete_archived_timelapse(
  5746. printer.ip_address,
  5747. printer.access_code,
  5748. remote_path,
  5749. verified=expected_size is not None,
  5750. printer_model=printer.model,
  5751. printer_name=printer.name,
  5752. )
  5753. return True
  5754. # Defaults for the finish-photo-from-timelapse polling loop (#1397). These are
  5755. # module-level so tests can monkeypatch them down to ~0 without timing out.
  5756. _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS: float = 3.0
  5757. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS: float = 60.0
  5758. # How long the *background* upgrade keeps waiting after the notification has
  5759. # already gone out (#2704 follow-up). The short bound above exists so a slow
  5760. # printer can't hold up the print-complete notification; this one exists so the
  5761. # archive still ends up with the better frame afterwards.
  5762. #
  5763. # Measured across 261 attaches in the support bundles, the video lands a median
  5764. # 13s after the print ends — but the P1 series writes MJPEG AVI rather than
  5765. # H.264 MP4 and serves it slowly, so its p90 is 167s and the worst observed case
  5766. # was 546s. Every other model was inside 26s. The long budget is therefore
  5767. # almost entirely for P1-series users; on everything else the short wait already
  5768. # wins and this task never runs.
  5769. _FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS: float = 900.0
  5770. async def _capture_finish_photo_from_timelapse(
  5771. archive_id: int,
  5772. archive_dir: Path,
  5773. timeout: float | None = None,
  5774. rotation: int = 0,
  5775. ) -> tuple[str | None, bool]:
  5776. """Wait for the per-print timelapse to land on the archive and extract its
  5777. last frame as the finish photo (#1397).
  5778. Bambu firmware stops timelapse recording after the toolhead parks but
  5779. before the bed-drop end-gcode runs, so the last frame frames the finished
  5780. print correctly. A live camera grab at gcode_state=FINISH captures the
  5781. bed already lowered.
  5782. ``_scan_for_timelapse_with_retries`` runs in parallel and writes
  5783. ``archive.timelapse_path`` when the file lands. This function polls for
  5784. that field.
  5785. Returns ``(filename, still_pending)``. ``still_pending`` is True only when
  5786. the wait ran out with no video on the archive yet — i.e. the video may
  5787. still be coming and a later attempt could succeed. It is False when the
  5788. video landed (whether or not extraction worked), because in that case
  5789. waiting longer changes nothing. The caller uses that to decide between
  5790. falling back permanently and scheduling a background upgrade.
  5791. ``rotation`` is the printer's camera_rotation, applied to the extracted
  5792. still (#2708) so this source agrees with every other finish-photo source.
  5793. The archived video itself is the printer's own file and is left alone —
  5794. rotating it would mean re-encoding it.
  5795. """
  5796. import uuid
  5797. from backend.app.models.archive import PrintArchive
  5798. from backend.app.services.camera import apply_camera_rotation_to_file, extract_video_last_frame
  5799. logger = logging.getLogger(__name__)
  5800. budget = _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS if timeout is None else timeout
  5801. deadline = asyncio.get_event_loop().time() + budget
  5802. poll_interval = _FINISH_PHOTO_TIMELAPSE_POLL_INTERVAL_SECONDS
  5803. while True:
  5804. async with async_session() as db:
  5805. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  5806. archive = result.scalar_one_or_none()
  5807. timelapse_relpath = archive.timelapse_path if archive else None
  5808. if timelapse_relpath:
  5809. video_path = app_settings.base_dir / timelapse_relpath
  5810. if video_path.exists() and video_path.stat().st_size > 0:
  5811. photos_dir = archive_dir / "photos"
  5812. photos_dir.mkdir(parents=True, exist_ok=True)
  5813. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  5814. filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  5815. output_path = photos_dir / filename
  5816. if await extract_video_last_frame(video_path, output_path):
  5817. await apply_camera_rotation_to_file(output_path, rotation, logger)
  5818. logger.info(
  5819. "[PHOTO-BG] Extracted finish photo from timelapse %s for archive %s",
  5820. video_path.name,
  5821. archive_id,
  5822. )
  5823. return filename, False
  5824. logger.warning(
  5825. "[PHOTO-BG] Timelapse %s landed but last-frame extraction failed for archive %s; falling back",
  5826. video_path.name,
  5827. archive_id,
  5828. )
  5829. return None, False
  5830. if asyncio.get_event_loop().time() >= deadline:
  5831. logger.info(
  5832. "[PHOTO-BG] Timelapse for archive %s didn't land within %.0fs; falling back to live camera",
  5833. archive_id,
  5834. budget,
  5835. )
  5836. return None, True
  5837. await asyncio.sleep(poll_interval)
  5838. async def _upgrade_finish_photo_from_timelapse(archive_id: int, archive_dir: Path, rotation: int = 0) -> None:
  5839. """Add the timelapse's last frame to an archive after the fact (#2704).
  5840. The print-complete notification waits only ~60s for the video, because
  5841. holding a notification for minutes is worse than sending it with a live
  5842. camera grab. On a P1-series printer the video often lands well after that,
  5843. so the archive used to be stuck with the live grab — which is taken at
  5844. ``gcode_state=FINISH``, after the end G-code has dropped the bed, and is
  5845. the worse photo of the two.
  5846. This keeps waiting in the background and, when the video arrives, extracts
  5847. the frame and puts it *first* in the archive's photo list, so opening the
  5848. gallery shows it. The live grab is deliberately kept: the notification that
  5849. already went out links to that exact file, and deleting it would leave a
  5850. broken image in Discord or Telegram.
  5851. """
  5852. logger = logging.getLogger(__name__)
  5853. filename, _ = await _capture_finish_photo_from_timelapse(
  5854. archive_id, archive_dir, timeout=_FINISH_PHOTO_UPGRADE_TIMEOUT_SECONDS, rotation=rotation
  5855. )
  5856. if not filename:
  5857. logger.info("[PHOTO-UPGRADE] No timelapse frame for archive %s; keeping the live grab", archive_id)
  5858. return
  5859. try:
  5860. async with async_session() as db:
  5861. from backend.app.models.archive import PrintArchive
  5862. archive = await db.get(PrintArchive, archive_id)
  5863. if archive is None:
  5864. return
  5865. photos = list(archive.photos or [])
  5866. if filename in photos:
  5867. return
  5868. # Front of the list: PhotoGalleryModal opens at index 0.
  5869. archive.photos = [filename, *photos]
  5870. await db.commit()
  5871. except Exception as e:
  5872. logger.warning("[PHOTO-UPGRADE] Failed to attach upgraded photo to archive %s: %s", archive_id, e)
  5873. return
  5874. logger.info("[PHOTO-UPGRADE] Archive %s now leads with the timelapse frame %s", archive_id, filename)
  5875. await ws_manager.send_archive_updated({"id": archive_id, "photo_added": filename})
  5876. async def _restore_usage_tracking_session(printer_id: int, state, db, logger) -> None:
  5877. """Put the filament-attribution context back after a restart mid-print.
  5878. ``usage_tracker._active_sessions`` and ``PrinterState.tray_change_log``
  5879. both die with the process. The print keeps running, so at completion the
  5880. tracker would fall back to whatever the printer reports *now* — and AMS
  5881. filament backup makes "now" the substitute tray, charging the whole print
  5882. to the spool that only finished it.
  5883. The persisted row is only trusted when its print name still matches what
  5884. the printer says it is running: a row left behind by a completion we never
  5885. saw must not attach itself to the next print.
  5886. """
  5887. try:
  5888. from backend.app.api.routes.settings import get_setting
  5889. from backend.app.services.usage_tracker import (
  5890. clear_persisted_session,
  5891. get_persisted_print_name,
  5892. restore_session,
  5893. )
  5894. persisted_name = await get_persisted_print_name(db, printer_id)
  5895. current_name = (state.subtask_name or "").strip()
  5896. if persisted_name and current_name and persisted_name.strip() != current_name:
  5897. logger.info(
  5898. "[RESTART] Discarding stale print session for printer %s (%r != running %r)",
  5899. printer_id,
  5900. persisted_name,
  5901. current_name,
  5902. )
  5903. await clear_persisted_session(db, printer_id)
  5904. # Fall through to seeding: the print on the printer is real, it just
  5905. # isn't the one the row described.
  5906. persisted_log = None
  5907. else:
  5908. # Spoolman users get the tray-change log back but no in-memory
  5909. # session — see ``on_print_start`` on why that dict is load-bearing
  5910. # for the remain%-sync guard.
  5911. _spoolman_on = await get_setting(db, "spoolman_enabled")
  5912. persisted_log = await restore_session(
  5913. db,
  5914. printer_id,
  5915. register_active=not (bool(_spoolman_on) and _spoolman_on.lower() == "true"),
  5916. )
  5917. if persisted_log:
  5918. restored = [tuple(entry) for entry in persisted_log if isinstance(entry, (list, tuple)) and len(entry) == 2]
  5919. # Anything this process already observed goes after the persisted
  5920. # history — the log is ordered by layer, and a fresh process can
  5921. # only have seen changes from later in the print.
  5922. for entry in state.tray_change_log or []:
  5923. if tuple(entry) not in restored:
  5924. restored.append(tuple(entry))
  5925. state.tray_change_log = restored
  5926. tray_now = state.tray_now
  5927. if 0 <= tray_now <= 254:
  5928. if not state.tray_change_log:
  5929. # No persisted history — a print that started before this build,
  5930. # or before the row existed. Seed with the tray feeding right
  5931. # now so the remainder of the print is at least attributable to
  5932. # the right spool.
  5933. state.tray_change_log = [(tray_now, state.layer_num)]
  5934. logger.info(
  5935. "[RESTART] Seeded tray change log for printer %s: tray=%d at layer=%d",
  5936. printer_id,
  5937. tray_now,
  5938. state.layer_num,
  5939. )
  5940. # The tray handler updates ``last_loaded_tray`` on every push
  5941. # regardless of whether it logged a change, so re-align it to avoid
  5942. # a duplicate entry on the next push. Only ever with a real tray:
  5943. # ``last_loaded_tray`` is the "survives the end-of-print retract to
  5944. # 255" fallback, and writing 255 into it would defeat that.
  5945. state.last_loaded_tray = tray_now
  5946. except Exception:
  5947. # Never let attribution recovery cost the caller its timelapse
  5948. # baseline — that capture has to happen before the printer uploads
  5949. # the in-flight MP4 and there is no second chance at it.
  5950. logger.exception("[RESTART] Failed to restore usage-tracking session for printer %s", printer_id)
  5951. async def on_print_running_observed(printer_id: int, data: dict):
  5952. """Restart-recovery for a print that started before Bambuddy came up.
  5953. bambu_mqtt.py suppresses ``on_print_start`` on the first RUNNING push
  5954. after Bambuddy startup (#1304 guard, prevents duplicate archive
  5955. creation). This hook restores the persisted archive into ``_active_prints``
  5956. and captures the timelapse baseline that normally hangs off print start.
  5957. Fires once per session, in lieu of on_print_start when restart-recovery
  5958. kicks in. The printer doesn't upload the timelapse until after PRINT
  5959. COMPLETE, so a baseline captured any time during the print is still
  5960. pre-upload.
  5961. """
  5962. logger = logging.getLogger(__name__)
  5963. async with async_session() as db:
  5964. from backend.app.models.printer import Printer
  5965. state = printer_manager.get_status(printer_id)
  5966. if state is not None:
  5967. authorization = await _is_bambuddy_authorized_print(printer_id, state, db)
  5968. if authorization is True:
  5969. logger.info("[RESTART] Restored active Bambuddy print for printer %s", printer_id)
  5970. await _restore_usage_tracking_session(printer_id, state, db, logger)
  5971. await _restore_printable_objects(printer_id, state, db, logger)
  5972. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  5973. printer = result.scalar_one_or_none()
  5974. if not printer:
  5975. logger.warning(
  5976. "[TIMELAPSE] on_print_running_observed: printer %s not found in DB, skipping baseline",
  5977. printer_id,
  5978. )
  5979. return
  5980. # Avoid double-capture: ownership reconciliation above must still run when
  5981. # a baseline already exists, but the camera work itself is one-shot.
  5982. if printer_id in _timelapse_baselines:
  5983. logger.debug(
  5984. "[TIMELAPSE] on_print_running_observed: baseline already present for printer %s, skipping",
  5985. printer_id,
  5986. )
  5987. return
  5988. await _capture_timelapse_baseline_at_start(printer, printer_id, logger)
  5989. def _is_active_archive_stale(archive, state) -> tuple[bool, str]:
  5990. """Return ``(is_stale, reason)`` for an archive in ``status="printing"``
  5991. against the printer's current MQTT state.
  5992. Reconciliation triggers (#1542 follow-up — recovers from missed PRINT
  5993. COMPLETE events, typically a print finishing during an MQTT disconnect
  5994. window followed by a smart-plug power cycle):
  5995. 1. Printer state is terminal (IDLE / FINISH / FAILED). The print is
  5996. provably not running anymore — only branch that should fire under
  5997. normal disconnect-then-reconnect timing.
  5998. 2. Printer has a different ``subtask_id`` than the archive. Bambu
  5999. firmware mints a fresh ``subtask_id`` for each print, including the
  6000. ghost replay it runs after a power cycle from a leftover SD file —
  6001. so a mismatch unambiguously means the in-DB archive is no longer
  6002. the print on the printer.
  6003. 3. Printer is running but ``subtask_name`` is empty. The printer
  6004. doesn't know what it's running; the archive's reference to it is
  6005. already broken.
  6006. Conservative on purpose: PAUSE / PREPARE / SLICING and any RUNNING state
  6007. with matching subtask_id+subtask_name is left alone. The cost of a false
  6008. positive is a duplicate archive on the next real PRINT COMPLETE — the
  6009. reactive handler uses ``_active_prints`` for lookup, which the reconcile
  6010. clears on synthesis, so the real completion creates a fresh row instead
  6011. of overwriting the synthesised one (#1679). The cost of a false negative
  6012. is the ghost-print loop in #1542.
  6013. Pre-push guard (#1679): when ``state.state`` is empty or ``"unknown"``,
  6014. MQTT has connected but the first ``push_status`` response hasn't been
  6015. applied yet — ``PrinterState`` is sitting on its construction defaults.
  6016. The reconcile caller in ``on_printer_status_change`` is already gated
  6017. on a real ``state.state``, so in normal operation this branch is
  6018. unreachable; it's kept as belt-and-braces for future callers and for
  6019. the narrow window where a partial state update could arrive
  6020. (``state.state`` set but ``subtask_name`` not yet populated). Returning
  6021. ``not stale`` on degenerate input is strictly conservative: a real
  6022. stale archive will still be caught by the next push_status arriving
  6023. with terminal state.
  6024. """
  6025. current_state = (state.state or "").upper()
  6026. if current_state in ("", "UNKNOWN"):
  6027. # No real push_status yet — PrinterState defaults are not evidence.
  6028. return False, ""
  6029. if current_state in ("IDLE", "FINISH", "FAILED"):
  6030. return True, f"printer state {current_state}"
  6031. # Below here the printer is in a running / pre-running state (RUNNING /
  6032. # PAUSE / PREPARE / SLICING / etc.) — decide based on subtask identity.
  6033. current_subtask_id = (state.subtask_id or "").strip()
  6034. if archive.subtask_id and current_subtask_id and archive.subtask_id != current_subtask_id:
  6035. return True, f"subtask_id changed ({archive.subtask_id!r} → {current_subtask_id!r})"
  6036. current_subtask_name = (state.subtask_name or "").strip()
  6037. if not current_subtask_name:
  6038. return True, "printer subtask_name empty"
  6039. return False, ""
  6040. async def prime_kprofile_table(printer_id: int) -> int:
  6041. """Read the printer's calibration table once per connection.
  6042. The AMS slot card shows a K value per slot (#2854). On the printers whose
  6043. trays carry no ``k`` field of their own -- the whole H2 series, whose trays
  6044. report ``cali_idx`` and nothing else -- that number can only come from
  6045. ``state.kprofiles``, and nothing used to fill it on connect. It arrived by
  6046. luck: someone opening the Profiles page or Configure Slot, a nightly GitHub
  6047. backup, or the printer answering a query BambuStudio made on the report
  6048. topic we share. A Bambuddy that nobody visited showed a card with no K
  6049. values at all.
  6050. Only the diameters actually fitted are asked for, which is one request on a
  6051. single-nozzle printer and two on a dual. Probing the four sizes blind is
  6052. what the backup does, and it is both wasteful and the thing that used to
  6053. blank the table.
  6054. Returns the number of nozzles whose table was read.
  6055. """
  6056. client = printer_manager.get_client(printer_id)
  6057. state = printer_manager.get_status(printer_id)
  6058. if client is None or state is None or not state.connected:
  6059. return 0
  6060. # Deduplicated, order preserved: a dual-nozzle printer with two 0.4s should
  6061. # ask once, and both entries are empty until the first push_status lands.
  6062. diameters = list(dict.fromkeys(n.nozzle_diameter for n in (state.nozzles or []) if n.nozzle_diameter))
  6063. if not diameters:
  6064. logging.getLogger(__name__).debug(
  6065. "[Printer %s] No nozzle diameter reported yet; leaving the K-profile table to the next reader",
  6066. printer_id,
  6067. )
  6068. return 0
  6069. primed = 0
  6070. for diameter in diameters:
  6071. try:
  6072. profiles = await client.get_kprofiles(nozzle_diameter=diameter, max_retries=2)
  6073. except Exception as exc: # noqa: BLE001
  6074. # A printer that won't answer costs the card its K values, nothing
  6075. # more — never the connection this runs on the back of.
  6076. logging.getLogger(__name__).warning(
  6077. "[Printer %s] Could not read the K-profile table for nozzle %s: %s", printer_id, diameter, exc
  6078. )
  6079. continue
  6080. primed += 1
  6081. logging.getLogger(__name__).info(
  6082. "[Printer %s] Primed K-profile table for nozzle %s: %d profiles", printer_id, diameter, len(profiles)
  6083. )
  6084. return primed
  6085. def _sd_files_in_use(state) -> set[str]:
  6086. """Names of the SD-card files the printer may be printing right now (#3009).
  6087. The post-print cleanup works out what to delete from the finished archive,
  6088. not from the printer. When reconciliation closes an old archive because the
  6089. printer has moved on to a new job, and that job is the same file reprinted
  6090. from the printer's screen, the cleanup would delete the file mid-print.
  6091. Empty unless the printer is busy: on an ordinary completion the state is
  6092. FINISH or FAILED and nothing is held back. ``gcode_file`` arrives as a bare
  6093. name, a path or a URL depending on firmware, and some report only the
  6094. plate's G-code, so the job name is matched as well, in the same spellings
  6095. the cleanup tries. Names are lower-cased; the card's FAT filesystem
  6096. ignores case.
  6097. """
  6098. def _text(value) -> str:
  6099. return value.strip() if isinstance(value, str) else ""
  6100. if state is None:
  6101. return set()
  6102. current_state = _text(getattr(state, "state", None)).upper()
  6103. if current_state in ("", "UNKNOWN", "IDLE", "FINISH", "FAILED"):
  6104. return set()
  6105. in_use: set[str] = set()
  6106. gcode_file = _text(getattr(state, "gcode_file", None))
  6107. if gcode_file:
  6108. # Drop a scheme by hand: urlparse would cut a name at "#" or "?",
  6109. # both legal in a file name, and raises on some inputs.
  6110. name = PurePosixPath(gcode_file.split("://", 1)[-1]).name
  6111. if name:
  6112. in_use.add(name.lower())
  6113. subtask_name = _text(getattr(state, "subtask_name", None))
  6114. if subtask_name:
  6115. for name in (subtask_name, subtask_name.replace(" ", "_")):
  6116. for ext in (".3mf", ".gcode"):
  6117. in_use.add(f"{name}{ext}".lower())
  6118. return in_use
  6119. async def reconcile_stale_active_prints(printer_id: int) -> int:
  6120. """Synthesise ``on_print_complete`` for archives whose print can't be
  6121. running on the printer anymore.
  6122. Called once per MQTT (re)connection (from on_printer_status_change when
  6123. the connected edge flips False → True) and at Bambuddy startup (from
  6124. the FastAPI lifespan). Without this, a print that completes during a
  6125. disconnect window — followed by a smart-plug-driven power cycle — leaves
  6126. the ``.3mf`` on the SD card, the firmware auto-replays it on next boot,
  6127. and Bambuddy fires a fresh PRINT START for the ghost rather than the
  6128. SD cleanup that PRINT COMPLETE was supposed to run. Repeats every
  6129. power cycle until the operator notices (#1542 follow-up). Reconciliation
  6130. closes the loop by faking the missed PRINT COMPLETE — the existing
  6131. cleanup chain handles SD-file deletion, status updates, usage tracking,
  6132. and notifications.
  6133. Synthesised ``status="aborted"`` is the conservative label: we have no
  6134. proof the print finished successfully (and no progress evidence to
  6135. promote to ``"completed"``). The real PRINT COMPLETE callback, if it
  6136. fires later, overwrites the status with the correct value.
  6137. Returns the number of archives reconciled.
  6138. """
  6139. state = printer_manager.get_status(printer_id)
  6140. if not state:
  6141. return 0
  6142. # Don't reconcile while disconnected — we'd be making a decision against
  6143. # stale cached state. The connected → reconcile edge handles this.
  6144. if not state.connected:
  6145. return 0
  6146. from backend.app.models.archive import PrintArchive
  6147. reconciled = 0
  6148. async with async_session() as db:
  6149. result = await db.execute(
  6150. select(PrintArchive).where(
  6151. PrintArchive.printer_id == printer_id,
  6152. PrintArchive.status == "printing",
  6153. )
  6154. )
  6155. active = list(result.scalars().all())
  6156. if not active:
  6157. return 0
  6158. logger = logging.getLogger(__name__)
  6159. for archive in active:
  6160. is_stale, reason = _is_active_archive_stale(archive, state)
  6161. if not is_stale:
  6162. continue
  6163. logger.info(
  6164. "[RECONCILE] Printer %s: synthesising missed PRINT COMPLETE for archive %s (%s) — %s",
  6165. printer_id,
  6166. archive.id,
  6167. archive.filename,
  6168. reason,
  6169. )
  6170. # Synthesised payload: minimal fields the on_print_complete chain
  6171. # needs. `_reconciled` marker lets downstream code distinguish this
  6172. # from a real MQTT-driven completion if it ever needs to (e.g. for
  6173. # metrics / debug logging). raw_data is the live printer state so
  6174. # the usage tracker can compare end-of-print remain% against the
  6175. # captured start values.
  6176. try:
  6177. await on_print_complete(
  6178. printer_id,
  6179. {
  6180. "status": "aborted",
  6181. "filename": archive.filename,
  6182. "subtask_name": archive.print_name or "",
  6183. "subtask_id": archive.subtask_id or "",
  6184. "raw_data": state.raw_data or {},
  6185. "_reconciled": True,
  6186. },
  6187. )
  6188. reconciled += 1
  6189. except Exception as e:
  6190. # Catch-all: a reconciliation failure must not block the
  6191. # printer's normal status flow. The archive stays in
  6192. # ``status="printing"`` and the next reconnect retries.
  6193. logger.warning(
  6194. "[RECONCILE] on_print_complete synthesis failed for archive %s: %s",
  6195. archive.id,
  6196. e,
  6197. )
  6198. return reconciled
  6199. # #2547: clearance left between the nozzle and the top of the print when the
  6200. # plate is commanded back into camera framing. The nozzle is parked away from
  6201. # the part by then, so this is belt-and-braces against a max_z_height that
  6202. # under-reports (e.g. a slicer that excludes a final Z hop).
  6203. _PLATE_RESTORE_CLEARANCE_MM = 10.0
  6204. # How far below the restored position to drop the plate again afterwards, so
  6205. # the print is as reachable as Bambu's own end G-code leaves it. Matches the
  6206. # stock `G1 Z{max_layer_z + 100}`; the firmware clamps it to the travel limit
  6207. # on machines with less headroom.
  6208. _PLATE_PARK_DROP_MM = 100.0
  6209. # Feedrate for both moves. F600 is exactly what Bambu's own end G-code uses on
  6210. # this axis, so it is a proven-safe speed for the full travel.
  6211. _PLATE_RESTORE_FEEDRATE = 600
  6212. # Time allowed for the plate to reach the restored position before the camera
  6213. # grab. Sized for the ~100 mm the stock end G-code drops at F600 (10 mm/s).
  6214. _PLATE_RESTORE_SETTLE_SECONDS = 12.0
  6215. # How long `_background_finish_photo` waits for this producer. Must cover the
  6216. # settle window plus a worst-case RTSP grab (15s), and stay below the
  6217. # notification path's own photo wait so a slow producer degrades to a
  6218. # photo-less notification rather than a missed one. The chamber light's
  6219. # snapshot delay (#1655) spends from the spare 8 seconds, which is why
  6220. # camera_light.MAX_DELAY_SECONDS stays below it.
  6221. _FINISH_PHOTO_PRODUCER_WAIT_SECONDS = _PLATE_RESTORE_SETTLE_SECONDS + 23.0
  6222. def _completion_print_keys(printer_id: int, filename: str, subtask_name: str) -> list[tuple[int, str]]:
  6223. """The ``_active_prints`` keys a finished print may be registered under.
  6224. Matching how they were registered in on_print_start. Shared by
  6225. ``on_print_complete`` and the finish-photo plate restore (#3240), which has
  6226. to find the same binding.
  6227. """
  6228. possible_keys = []
  6229. # Try subtask_name variations first (most reliable for matching)
  6230. if subtask_name:
  6231. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  6232. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  6233. possible_keys.append((printer_id, subtask_name))
  6234. # Try filename variations
  6235. if filename:
  6236. # Extract just the filename if it's a path
  6237. fname = filename.split("/")[-1] if "/" in filename else filename
  6238. if fname.endswith(".3mf"):
  6239. possible_keys.append((printer_id, fname))
  6240. elif fname.endswith(".gcode"):
  6241. base_name = fname.rsplit(".", 1)[0]
  6242. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  6243. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6244. possible_keys.append((printer_id, fname))
  6245. else:
  6246. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  6247. possible_keys.append((printer_id, f"{fname}.3mf"))
  6248. possible_keys.append((printer_id, fname))
  6249. # Also try full path versions
  6250. if filename.endswith(".3mf"):
  6251. possible_keys.append((printer_id, filename))
  6252. elif filename.endswith(".gcode"):
  6253. base_name = filename.rsplit(".", 1)[0]
  6254. possible_keys.append((printer_id, f"{base_name}.3mf"))
  6255. possible_keys.append((printer_id, filename))
  6256. else:
  6257. possible_keys.append((printer_id, f"{filename}.3mf"))
  6258. possible_keys.append((printer_id, filename))
  6259. return possible_keys
  6260. def _archive_name_forms(archive) -> set[str]:
  6261. """The names an archive could be echoed back as, in normalised form (#3240).
  6262. Its print name, and its filename with and without the 3MF extension.
  6263. """
  6264. forms = set()
  6265. if archive.print_name:
  6266. forms.add(_normalise_subtask_name(archive.print_name))
  6267. if archive.filename:
  6268. forms.add(_normalise_subtask_name(archive.filename))
  6269. for suffix in (".gcode.3mf", ".3mf"):
  6270. if archive.filename.lower().endswith(suffix):
  6271. forms.add(_normalise_subtask_name(archive.filename[: -len(suffix)]))
  6272. forms.discard("")
  6273. return forms
  6274. def _bound_print(printer_id: int, data: dict) -> tuple[int | None, int | None]:
  6275. """The archive and plate Bambuddy bound to the print ending on ``printer_id`` (#3240).
  6276. Read from ``_active_prints`` with the keys ``on_print_complete`` tries, and
  6277. from the plate recorded when the job was dispatched. Neither is touched:
  6278. ``on_print_complete`` pops both, which is why the finish-photo producer
  6279. calls this before its first await, while they are still there.
  6280. ``(None, None)`` for a print Bambuddy did not bind -- one it failed to
  6281. archive, or that it only knows by a name -- and on any error: the producer
  6282. calls this before the ``try`` that always releases the photo consumer, so
  6283. it must not raise.
  6284. """
  6285. try:
  6286. keys = _completion_print_keys(printer_id, str(data.get("filename") or ""), str(data.get("subtask_name") or ""))
  6287. archive_id = next((_active_prints[key] for key in keys if key in _active_prints), None)
  6288. if archive_id is None:
  6289. return None, None
  6290. return archive_id, _print_plate_ids.get(archive_id)
  6291. except Exception:
  6292. logging.getLogger(__name__).debug("Could not read the print binding for printer %s", printer_id, exc_info=True)
  6293. return None, None
  6294. async def _max_z_for_current_print(
  6295. printer_id: int,
  6296. data: dict,
  6297. logger,
  6298. archive_id: int | None,
  6299. plate_id: int | None = None,
  6300. ) -> float | None:
  6301. """Height of the print that just finished on ``printer_id``, or None (#2547).
  6302. This number becomes the target of a real Z move, so every step here refuses
  6303. rather than guesses. A height belonging to some *other* print is the one
  6304. failure that could drive the nozzle into the model: 20 mm carried onto a
  6305. 200 mm print would command the plate up through the part.
  6306. Three independent things therefore have to agree before a height is
  6307. returned:
  6308. 1. **Binding.** ``archive_id`` is the archive Bambuddy bound to this print
  6309. when it started (see ``_bound_print``), never one found by name. A name
  6310. is not an identity: every plate of a multi-plate file shares one, and a
  6311. reprint reuses its archive row, so the newest archive with the right
  6312. name can be another plate of the same file. Support bundles show the
  6313. old name lookup doing exactly that (archive 288 for a print bound to
  6314. 169, 313 layers against 125), stopped only by the layer check below.
  6315. No binding, no move.
  6316. 2. **Identity.** The bound archive's name still has to be the finished
  6317. print's ``subtask_name``, compared in ``_normalise_subtask_name`` form
  6318. because the printer echoes spaces as underscores (#3240). Exact: not a
  6319. substring, and not the completion check's tolerance for a truncated
  6320. echo.
  6321. 3. **Corroboration.** The archive's layer count (parsed from the 3MF) has to
  6322. match the layer count the printer itself reported over MQTT for the print
  6323. that just ended. These come from genuinely different sources, so a
  6324. mismatch means the row is not this print, whatever its name says.
  6325. ``plate_id`` is the plate the job was dispatched with; a reprint of one
  6326. plate of a multi-plate file reuses the archive row without updating its
  6327. ``plate_id``. ``completed`` is accepted alongside ``printing`` only because
  6328. ``on_print_complete`` may already have flipped the status by the time we
  6329. run.
  6330. """
  6331. subtask_name = (data.get("subtask_name") or "").strip()
  6332. if not subtask_name:
  6333. # Nothing to identify the print by — refuse rather than fall back to
  6334. # "whatever ran last on this printer".
  6335. logger.info("[PLATE-RESTORE] printer %s: print has no name to match on — skipping", printer_id)
  6336. return None
  6337. if archive_id is None:
  6338. logger.info(
  6339. "[PLATE-RESTORE] printer %s: %r is not bound to an archive — skipping",
  6340. printer_id,
  6341. subtask_name,
  6342. )
  6343. return None
  6344. try:
  6345. from backend.app.models.archive import PrintArchive
  6346. from backend.app.utils.threemf_tools import extract_max_z_height_from_3mf
  6347. async with async_session() as db:
  6348. result = await db.execute(
  6349. select(PrintArchive).where(
  6350. PrintArchive.id == archive_id,
  6351. PrintArchive.printer_id == printer_id,
  6352. PrintArchive.status.in_(("printing", "completed")),
  6353. PrintArchive.deleted_at.is_(None),
  6354. )
  6355. )
  6356. archive = result.scalar_one_or_none()
  6357. if archive is None or not archive.file_path:
  6358. logger.info("[PLATE-RESTORE] printer %s: archive %s has no usable file — skipping", printer_id, archive_id)
  6359. return None
  6360. if _normalise_subtask_name(subtask_name) not in _archive_name_forms(archive):
  6361. logger.warning(
  6362. "[PLATE-RESTORE] printer %s: archive %s is not named %r — refusing to move the plate",
  6363. printer_id,
  6364. archive_id,
  6365. subtask_name,
  6366. )
  6367. return None
  6368. client = printer_manager.get_client(printer_id)
  6369. reported_layers = getattr(getattr(client, "state", None), "total_layers", None)
  6370. if reported_layers and archive.total_layers and reported_layers != archive.total_layers:
  6371. logger.warning(
  6372. "[PLATE-RESTORE] printer %s: archive %s says %s layers but the printer reported %s "
  6373. "— refusing to move the plate on a height that may not be this print's",
  6374. printer_id,
  6375. archive.id,
  6376. archive.total_layers,
  6377. reported_layers,
  6378. )
  6379. return None
  6380. # Stored relative to the data directory, like every other archive path
  6381. # (#3240: this read a `data_dir` setting that does not exist).
  6382. path = app_settings.base_dir / archive.file_path
  6383. plate = plate_id or archive.plate_id or 1
  6384. return await asyncio.to_thread(extract_max_z_height_from_3mf, path, plate)
  6385. except Exception as e:
  6386. logger.debug("[PLATE-RESTORE] printer %s: no usable print height: %s", printer_id, e)
  6387. return None
  6388. async def _restore_plate_for_finish_photo(printer_id: int, max_z_height: float, logger) -> bool:
  6389. """Raise the plate back into camera framing before the finish photo (#2547).
  6390. Bambu's end G-code drops the plate ~100 mm as the last thing it does, so by
  6391. the time ``gcode_state`` reaches FINISH the finished print sits far below
  6392. the camera's natural framing — the complaint behind #1145, #1397 and #1565.
  6393. This commands an absolute ``G1 Z`` back to just above the last printed
  6394. layer.
  6395. Absolute, not relative, is the whole safety argument. ``max_z_height +
  6396. clearance`` is a height the toolhead was physically at seconds earlier, so
  6397. it is inside the travel limits by construction and leaves the nozzle above
  6398. the part. It is also unambiguous across model families: Z is the
  6399. nozzle-to-bed gap whether the bed moves (X1/P1/H2) or the toolhead does
  6400. (A1), so unlike the relative bed-jog path (#1334) there is no sign to get
  6401. wrong. ``M211`` is never touched — see the bed-jog docstring for why
  6402. (#2579).
  6403. Returns True if the move was sent and waited out, False if it was skipped.
  6404. """
  6405. client = printer_manager.get_client(printer_id)
  6406. if client is None:
  6407. return False
  6408. # Re-read state immediately before commanding motion. If the queue has
  6409. # already started the next print, the printer is no longer ours to move.
  6410. state = getattr(client, "state", None)
  6411. if state is None or state.state != "FINISH":
  6412. logger.info(
  6413. "[PLATE-RESTORE] printer %s is in state %s, not FINISH — skipping",
  6414. printer_id,
  6415. getattr(state, "state", "unknown"),
  6416. )
  6417. return False
  6418. target_z = max_z_height + _PLATE_RESTORE_CLEARANCE_MM
  6419. if not client.send_gcode(f"G90\nG1 Z{target_z:.2f} F{_PLATE_RESTORE_FEEDRATE}"):
  6420. logger.warning("[PLATE-RESTORE] printer %s: send failed — capturing where it is", printer_id)
  6421. return False
  6422. logger.info(
  6423. "[PLATE-RESTORE] printer %s: plate to Z%.2f (print top %.2f + %.1f clearance), settling %.0fs",
  6424. printer_id,
  6425. target_z,
  6426. max_z_height,
  6427. _PLATE_RESTORE_CLEARANCE_MM,
  6428. _PLATE_RESTORE_SETTLE_SECONDS,
  6429. )
  6430. await asyncio.sleep(_PLATE_RESTORE_SETTLE_SECONDS)
  6431. return True
  6432. def _park_plate_after_finish_photo(printer_id: int, max_z_height: float, logger) -> None:
  6433. """Drop the plate again after the finish photo (#2547).
  6434. Without this the user walks up to a finished print sitting just under the
  6435. nozzle, which is exactly the position Bambu's end G-code goes out of its way
  6436. to avoid — awkward to lift the plate out, and easy to knock the toolhead.
  6437. Fire-and-forget: if it doesn't land, the plate is merely high, and the next
  6438. print homes anyway.
  6439. """
  6440. client = printer_manager.get_client(printer_id)
  6441. state = getattr(client, "state", None) if client else None
  6442. if client is None or state is None or state.state != "FINISH":
  6443. return
  6444. client.send_gcode(f"G90\nG1 Z{max_z_height + _PLATE_PARK_DROP_MM:.2f} F{_PLATE_RESTORE_FEEDRATE}")
  6445. logger.debug("[PLATE-RESTORE] printer %s: plate returned to unload height", printer_id)
  6446. async def _plate_restore_is_blocked_by_queue(printer_id: int) -> bool:
  6447. """True if a queue item is about to take this printer (#2547).
  6448. The scheduler dispatches the next job the moment a print completes, and a
  6449. plate move interleaved with a print start is not a race worth having. The
  6450. state re-check in ``_restore_plate_for_finish_photo`` closes the tail of
  6451. this window; this closes the head of it.
  6452. """
  6453. try:
  6454. from backend.app.models.print_queue import PrintQueueItem
  6455. async with async_session() as db:
  6456. result = await db.execute(
  6457. select(PrintQueueItem.id)
  6458. .where(
  6459. PrintQueueItem.printer_id == printer_id,
  6460. PrintQueueItem.status.in_(("pending", "printing")),
  6461. )
  6462. .limit(1)
  6463. )
  6464. return result.scalar_one_or_none() is not None
  6465. except Exception as e:
  6466. # Fail closed: if we can't tell, don't move the plate.
  6467. logging.getLogger(__name__).debug(
  6468. "[PLATE-RESTORE] queue check failed for printer %s: %s — skipping restore", printer_id, e
  6469. )
  6470. return True
  6471. async def on_finish_photo_moment(printer_id: int, data: dict):
  6472. """Pre-capture a finish photo when the printer enters stage 22 / FINISH (#1721).
  6473. Fires either at the stage-22 ("Filament unloading") edge — toolhead
  6474. parked, bed not yet dropped, optimal framing — or as a FINISH-state
  6475. fallback for prints that skip stage 22 (cancel, external-spool-only,
  6476. HMS halt, firmware variants). Grabs one frame via the same
  6477. external-camera / RTSP path the post-completion fallback uses, stores
  6478. the JPEG bytes in ``_stage22_finish_frames[printer_id]``, and lets
  6479. ``_background_finish_photo`` consume the cached bytes when it runs.
  6480. Replaces the #1397 "force timelapse on at dispatch" mechanism, which
  6481. caused per-layer nozzle parking on slicer profiles with Timelapse Type
  6482. set to Smooth (#1721). No force-on now means the user's explicit
  6483. timelapse=off in the slicer send dialog is respected.
  6484. """
  6485. logger = logging.getLogger(__name__)
  6486. trigger = data.get("trigger", "unknown")
  6487. timelapse_was_active = bool(data.get("timelapse_was_active"))
  6488. logger.info(
  6489. "[FINISH-PHOTO-MOMENT] printer=%s trigger=%s timelapse_active=%s",
  6490. printer_id,
  6491. trigger,
  6492. timelapse_was_active,
  6493. )
  6494. # If a timelapse is actively recording, skip the pre-capture — the
  6495. # post-completion path will extract the last frame from the recorded
  6496. # video, which still provides the best framing (toolhead parked,
  6497. # before bed drop) without the per-layer parking side effects.
  6498. if timelapse_was_active:
  6499. logger.info(
  6500. "[FINISH-PHOTO-MOMENT] timelapse active for printer %s — skipping pre-capture (last-frame extraction will run post-completion)",
  6501. printer_id,
  6502. )
  6503. return
  6504. # #1790: register the producer-done event BEFORE the first await so the
  6505. # consumer in `_background_finish_photo` — which is dispatched back-to-back
  6506. # with us on the FINISH-state fallback path — sees it as soon as it polls.
  6507. # The `finally` below guarantees `set()` runs on every exit, including
  6508. # early returns and exceptions, so the consumer's bounded wait can't hang.
  6509. producer_done = asyncio.Event()
  6510. _stage22_finish_in_flight[printer_id] = producer_done
  6511. # #3240: also before the first await. On the FINISH-state path
  6512. # `on_print_complete` is dispatched right behind us and pops both the
  6513. # print's archive binding and its plate; read here, they are still there.
  6514. bound_archive_id, bound_plate_id = _bound_print(printer_id, data)
  6515. # #2547: set once the plate has actually been raised, and read by the
  6516. # `finally` below. Declared out here so a failure anywhere after the move —
  6517. # a camera timeout, a DB error — still lowers the plate again.
  6518. restore_max_z: float | None = None
  6519. try:
  6520. async with async_session() as db:
  6521. from backend.app.api.routes.settings import get_setting
  6522. from backend.app.models.printer import Printer
  6523. capture_setting = await get_setting(db, "capture_finish_photo")
  6524. if capture_setting is not None and capture_setting.lower() != "true":
  6525. logger.info("[FINISH-PHOTO-MOMENT] capture_finish_photo disabled — skipping pre-capture")
  6526. return
  6527. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  6528. restore_plate_enabled = restore_setting is None or restore_setting.lower() == "true"
  6529. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6530. printer = result.scalar_one_or_none()
  6531. if printer is None:
  6532. logger.warning(
  6533. "[FINISH-PHOTO-MOMENT] printer %s not found in DB",
  6534. printer_id,
  6535. )
  6536. return
  6537. frame_bytes: bytes | None = None
  6538. # #2708: the banked frame arrives already rotated — it comes from
  6539. # `_capture_snapshot_for_notification`, which rotates before returning.
  6540. # Every other source below is a raw grab. Tracking which lets us store
  6541. # exactly one rotation in `_stage22_finish_frames` either way.
  6542. frame_already_rotated = False
  6543. # On the FINISH-state path the End G-code has already run, and two very
  6544. # different situations arrive here needing opposite answers.
  6545. #
  6546. # #1867: if Bambuddy injected End G-code into this print, a SwapMod
  6547. # snippet may have ejected the plate — the scene in front of the camera
  6548. # is no longer the finished print, and no amount of moving the plate
  6549. # brings it back. Use the banked in-print frame instead.
  6550. #
  6551. # #2547: otherwise the print is still sitting there, just ~100 mm lower
  6552. # than the camera frames well, and the toolhead is parked out of the
  6553. # way. That is the *best* moment available on firmware that never emits
  6554. # stage 22 (H2C, A1 Mini) — so capture live, after putting the plate
  6555. # back. Preferring the bank here unconditionally, as this code used to,
  6556. # is what shipped a mid-print photo with the toolhead over the part.
  6557. if trigger == "finish_state" and print_dispatch_context.end_gcode_injected(printer_id):
  6558. banked = _inprint_frame_bank.get(printer_id)
  6559. if banked:
  6560. frame_bytes = banked
  6561. frame_already_rotated = True
  6562. logger.info(
  6563. "[FINISH-PHOTO-MOMENT] End G-code was injected — using banked in-print "
  6564. "frame (%d bytes) instead of a post-swap live grab",
  6565. len(banked),
  6566. )
  6567. else:
  6568. logger.warning(
  6569. "[FINISH-PHOTO-MOMENT] End G-code was injected for printer %s but the "
  6570. "in-print bank is empty — falling back to a live grab, which may show a "
  6571. "swapped or empty plate",
  6572. printer_id,
  6573. )
  6574. # `restore_max_z` is set only once the plate is actually up, because the
  6575. # `finally` reads it to decide whether it owes a move back down.
  6576. #
  6577. # Never on a print whose End G-code Bambuddy injected, even when the bank
  6578. # came up empty above: that machine may have just ejected its plate, and
  6579. # driving Z into whatever a swap mechanism is doing is not a risk worth
  6580. # taking for a photo of a bed we already know may be bare.
  6581. if (
  6582. frame_bytes is None
  6583. and trigger == "finish_state"
  6584. and restore_plate_enabled
  6585. and not print_dispatch_context.end_gcode_injected(printer_id)
  6586. ):
  6587. wants_restore = await _max_z_for_current_print(printer_id, data, logger, bound_archive_id, bound_plate_id)
  6588. if wants_restore is None:
  6589. logger.info(
  6590. "[PLATE-RESTORE] printer %s: print height unknown — capturing without restore",
  6591. printer_id,
  6592. )
  6593. elif await _plate_restore_is_blocked_by_queue(printer_id):
  6594. logger.info(
  6595. "[PLATE-RESTORE] printer %s has queued work — skipping plate restore",
  6596. printer_id,
  6597. )
  6598. elif await _restore_plate_for_finish_photo(printer_id, wants_restore, logger):
  6599. restore_max_z = wants_restore
  6600. # Chamber light for the live capture below (#1655). The banked frame
  6601. # above was taken without it, like every in-print bank.
  6602. async with camera_light(printer if frame_bytes is None else None):
  6603. if frame_bytes is None and printer.external_camera_enabled and printer.external_camera_url:
  6604. from backend.app.api.routes.camera import live_frame_for_capture
  6605. from backend.app.services.external_camera import capture_frame
  6606. # #2707: this used to collide with the live view and fail, which is
  6607. # how finish-photo notifications went out with no image attached.
  6608. # Leaving frame_bytes None keeps the rest of the fallback chain.
  6609. defer, buffered = live_frame_for_capture(printer_id)
  6610. if defer:
  6611. frame_bytes = buffered
  6612. else:
  6613. frame_bytes = await capture_frame(
  6614. printer.external_camera_url,
  6615. printer.external_camera_type or "mjpeg",
  6616. snapshot_url=printer.external_camera_snapshot_url,
  6617. )
  6618. if frame_bytes:
  6619. logger.info(
  6620. "[FINISH-PHOTO-MOMENT] captured external-camera frame (%d bytes)",
  6621. len(frame_bytes),
  6622. )
  6623. elif frame_bytes is None:
  6624. from backend.app.api.routes.camera import get_buffered_frame
  6625. buffered = get_buffered_frame(printer_id)
  6626. if buffered:
  6627. frame_bytes = buffered
  6628. logger.info(
  6629. "[FINISH-PHOTO-MOMENT] used buffered RTSP frame (%d bytes)",
  6630. len(frame_bytes),
  6631. )
  6632. else:
  6633. from backend.app.services.camera import capture_camera_frame_bytes
  6634. frame_bytes = await capture_camera_frame_bytes(
  6635. ip_address=printer.ip_address,
  6636. access_code=printer.access_code,
  6637. model=printer.model,
  6638. timeout=15,
  6639. )
  6640. if frame_bytes:
  6641. logger.info(
  6642. "[FINISH-PHOTO-MOMENT] captured RTSP frame (%d bytes)",
  6643. len(frame_bytes),
  6644. )
  6645. if frame_bytes:
  6646. if not frame_already_rotated:
  6647. frame_bytes = _apply_camera_rotation(frame_bytes, printer, logger)
  6648. _stage22_finish_frames[printer_id] = frame_bytes
  6649. else:
  6650. logger.warning(
  6651. "[FINISH-PHOTO-MOMENT] no frame captured for printer %s — post-completion fallback will retry",
  6652. printer_id,
  6653. )
  6654. except Exception as e:
  6655. logger.warning(
  6656. "[FINISH-PHOTO-MOMENT] pre-capture failed for printer %s: %s",
  6657. printer_id,
  6658. e,
  6659. )
  6660. finally:
  6661. # #2547: we raised the plate, so we own lowering it — including when the
  6662. # capture above failed or threw partway through.
  6663. if restore_max_z is not None:
  6664. try:
  6665. _park_plate_after_finish_photo(printer_id, restore_max_z, logger)
  6666. except Exception as e:
  6667. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  6668. # #1790: always unblock the consumer's bounded wait — whether we stored
  6669. # a frame, gave up, or hit an exception. Local ref means cleanup of the
  6670. # dict entry by the consumer doesn't affect signalling.
  6671. producer_done.set()
  6672. def _subtask_name_from_filename(filename: str) -> str:
  6673. """Recover the subtask name a print command would have carried for *filename*.
  6674. The dispatcher derives the printer-facing subtask name from the archive's
  6675. file name, so stripping the extensions back off gives the value MQTT echoes
  6676. on completion. Only the two extensions Bambuddy actually stores are removed,
  6677. and in the order they nest (``.gcode.3mf``), so a model whose own name
  6678. contains a dot -- ``My.Model.3mf`` -- keeps it.
  6679. """
  6680. name = PurePosixPath(filename).name
  6681. for suffix in (".3mf", ".gcode"):
  6682. if name.lower().endswith(suffix):
  6683. name = name[: -len(suffix)]
  6684. return name
  6685. def _subtask_is_the_file(subtask_name: str, filename: str) -> bool:
  6686. """Whether the subtask name is the printed 3MF's own file name.
  6687. A print started from the printer's screen reports the same full name, with
  6688. its extension, as both subtask and file (#3009). A dispatched print reports
  6689. a bare subtask name; one that merely ends in ".3mf" can be a model named
  6690. that, whose file is ``Foo.3mf.gcode.3mf``, so it does not count.
  6691. """
  6692. if not subtask_name or not subtask_name.lower().endswith(".3mf"):
  6693. return False
  6694. return PurePosixPath((filename or "").split("://", 1)[-1]).name == subtask_name
  6695. # How the printer marks a subtask name it had to cut short. Observed on real
  6696. # hardware at ~100 characters, but the cut-off is not a fixed character count
  6697. # (a name with multibyte characters came back at 98), so match the marker
  6698. # rather than a length.
  6699. _SUBTASK_TRUNCATION_MARKER = "..."
  6700. def _normalise_subtask_name(name: str) -> str:
  6701. """Canonical form for comparing a dispatched name against MQTT's echo.
  6702. The printer does not echo the name back verbatim: it substitutes
  6703. underscores for spaces. ``H2D_Carbon_Filter_(V2)_Body & Solid Lid`` is
  6704. dispatched and ``H2D_Carbon_Filter_(V2)_Body_&_Solid_Lid`` comes back.
  6705. The 3MF lookup in this module has always known that -- it builds
  6706. space-to-underscore variants of every candidate filename, and its
  6707. directory search normalises both sides before comparing. This exists so
  6708. the completion check reads the same rule from the same place instead of
  6709. growing its own, which is exactly how it came to disagree (#2829).
  6710. A space at either end is substituted too: ``Part .gcode.3mf`` is
  6711. dispatched as ``Part `` and echoed as ``Part_``. Underscores at the ends
  6712. are dropped after the substitution so both sides agree (#3241).
  6713. """
  6714. return name.strip().replace(" ", "_").strip("_").casefold()
  6715. def _subtask_names_match(expected: str, observed: str) -> bool:
  6716. """Whether two subtask names describe the same print.
  6717. Beyond the space/underscore substitution, the printer truncates long names
  6718. and marks the cut with ``...``. A truncated echo has to count as a match or
  6719. every print with a long name strands its queue item the same way.
  6720. """
  6721. expected_n = _normalise_subtask_name(expected)
  6722. observed_n = _normalise_subtask_name(observed)
  6723. if expected_n == observed_n:
  6724. return True
  6725. # Either side can be the truncated one: the printer truncates what it
  6726. # echoes, and an archive whose own filename was recorded from a previous
  6727. # truncated echo carries the marker too.
  6728. for full, cut in ((expected_n, observed_n), (observed_n, expected_n)):
  6729. if not cut.endswith(_SUBTASK_TRUNCATION_MARKER):
  6730. continue
  6731. # The full side has lost its edge underscores; a cut that lands right
  6732. # after one keeps it, so drop it here too (#3241). Nothing left before
  6733. # the marker is no evidence of anything, and must not match every name.
  6734. kept = cut[: -len(_SUBTASK_TRUNCATION_MARKER)].rstrip("_")
  6735. if kept and full.startswith(kept):
  6736. return True
  6737. return False
  6738. async def _queue_item_dispatched_name(db, item) -> str:
  6739. """The subtask name *item* was dispatched under, or "" when unknowable.
  6740. A row with no archive, or an archive with no file name, is unverifiable
  6741. rather than wrong; every caller answers that with its permissive branch.
  6742. """
  6743. if item.archive_id is None:
  6744. return ""
  6745. from backend.app.models.archive import PrintArchive
  6746. archive = await db.get(PrintArchive, item.archive_id)
  6747. if archive is None or not archive.filename:
  6748. return ""
  6749. return _subtask_name_from_filename(archive.filename)
  6750. async def _completion_belongs_to_queue_item(db, item, data: dict) -> bool:
  6751. """Whether this completion event is plausibly about *item*'s print.
  6752. The caller finds its queue row by printer and ``status='printing'`` alone,
  6753. which is all a completion event gives it -- there is no run identifier in
  6754. the MQTT payload to match on. That makes the lookup indiscriminate: any
  6755. completion delivered for this printer closes whichever row happens to be
  6756. printing, however unrelated. Comparing the subtask name against the archive
  6757. the row was dispatched with costs one primary-key load and rules that out.
  6758. Deliberately permissive: it answers False only on a positive disagreement
  6759. between two names we actually have. A row with no archive, an archive with
  6760. no file name, or an event with no subtask name is unverifiable rather than
  6761. wrong, and refusing those would strand the item in ``printing`` and wedge
  6762. the printer's queue -- a worse failure than the one being prevented.
  6763. """
  6764. observed = (data.get("subtask_name") or "").strip()
  6765. if not observed or item.archive_id is None:
  6766. return True
  6767. from backend.app.models.archive import PrintArchive
  6768. archive = await db.get(PrintArchive, item.archive_id)
  6769. if archive is None or not archive.filename:
  6770. return True
  6771. expected = _subtask_name_from_filename(archive.filename)
  6772. if not expected or _subtask_names_match(expected, observed):
  6773. return True
  6774. logging.getLogger(__name__).warning(
  6775. "Ignoring print completion for queue item %s: it was dispatched as %r "
  6776. "(archive %s, %s) but the completion reports subtask %r. Leaving the item "
  6777. "printing rather than closing a run this event is not about.",
  6778. item.id,
  6779. expected,
  6780. archive.id,
  6781. archive.filename,
  6782. observed,
  6783. )
  6784. return False
  6785. async def _recover_fallback_from_cache_before_eviction(printer_id: int, data: dict) -> None:
  6786. """Spend the 3MF download cache on a still-empty fallback archive.
  6787. ``on_print_complete`` drops the cache as its first act, which deletes the
  6788. file. If the cover endpoint (or anything else) pulled the 3MF while the
  6789. print ran and the archive never got one, this is the last moment those bytes
  6790. exist (#2957).
  6791. """
  6792. logger = logging.getLogger(__name__)
  6793. names = [
  6794. n
  6795. for n in (data.get("filename"), data.get("subtask_name"), (data.get("raw_data") or {}).get("subtask_name"))
  6796. if n
  6797. ]
  6798. for name in names:
  6799. try:
  6800. cached = get_cached_3mf(printer_id, name)
  6801. if cached and await try_recover_fallback_archive(printer_id, name, cached):
  6802. return
  6803. except Exception as e:
  6804. logger.debug("[RECOVER] Pre-eviction recovery for %s failed: %s", name, e)
  6805. async def _cleanup_sd_card_after_print(
  6806. printer_id: int, subtask_name: str | None, archive_id: int | None, logger
  6807. ) -> None:
  6808. """Delete a finished print's file from the printer's SD card."""
  6809. # Cleanup: delete uploaded file from printer SD card to prevent phantom prints (Issue #374, #1542)
  6810. # The print scheduler uploads files to the SD card root (/). Some printers (e.g. P1S, A1)
  6811. # auto-start files found in root on power cycle, causing ghost prints.
  6812. # Must run before the archive_id early-return so it executes even when archiving is disabled.
  6813. try:
  6814. if subtask_name:
  6815. archive_filename: str | None = None
  6816. async with async_session() as db:
  6817. from backend.app.models.archive import PrintArchive
  6818. from backend.app.models.printer import Printer
  6819. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  6820. printer = result.scalar_one_or_none()
  6821. if archive_id:
  6822. archive_row = await db.execute(select(PrintArchive.filename).where(PrintArchive.id == archive_id))
  6823. archive_filename = archive_row.scalar_one_or_none()
  6824. if printer:
  6825. from backend.app.services.bambu_ftp import DeleteResult, delete_file_async
  6826. from backend.app.utils.filename import derive_remote_filename
  6827. # Primary candidate: the exact path the dispatcher uploaded to
  6828. # (derived from archive.filename via the same rule as upload).
  6829. # Without it, a library row that ended up with a doubled
  6830. # .gcode.3mf (#1542) leaves the real file behind because the
  6831. # subtask_name + ext fallbacks below don't match what's on the
  6832. # SD card. Fallbacks remain for archive-less prints (subtask
  6833. # never resolved to an archive) and for older naming variants.
  6834. candidate_paths: list[str] = []
  6835. if archive_filename:
  6836. candidate_paths.append(f"/{derive_remote_filename(archive_filename)}")
  6837. for ext in (".3mf", ".gcode"):
  6838. fallback = f"/{subtask_name}{ext}"
  6839. if fallback not in candidate_paths:
  6840. candidate_paths.append(fallback)
  6841. # Three outcomes track across all candidates so the final log
  6842. # line reflects what actually happened. The A1 in #1721 always
  6843. # ends here with ``any_not_found=True`` and the others False
  6844. # — its firmware auto-cleans the SD card before our cleanup
  6845. # runs, every candidate FTP-DELE returns 550, and the old
  6846. # code burned 3 retries × 2 s × 3 candidates per print
  6847. # logging a misleading "may linger" WARNING on a successful
  6848. # print.
  6849. any_deleted = False
  6850. any_real_failure = False
  6851. any_not_found = False
  6852. files_in_use = _sd_files_in_use(printer_manager.get_status(printer_id))
  6853. for remote_path in candidate_paths:
  6854. if PurePosixPath(remote_path).name.lower() in files_in_use:
  6855. logger.info(
  6856. "SD card cleanup: keeping %s on printer %s, which is printing it now",
  6857. remote_path,
  6858. printer.name,
  6859. )
  6860. continue
  6861. # Retry only the FAILED case — 550 NOT_FOUND will never
  6862. # recover by waiting, so a "file isn't here" answer
  6863. # advances immediately to the next candidate without
  6864. # consuming the retry budget.
  6865. for attempt in range(1, 4):
  6866. try:
  6867. delete_result = await delete_file_async(
  6868. printer.ip_address,
  6869. printer.access_code,
  6870. remote_path,
  6871. printer_model=printer.model,
  6872. )
  6873. except Exception as e:
  6874. delete_result = DeleteResult.FAILED
  6875. logger.warning(
  6876. "SD card cleanup attempt %d/3 raised for %s: %s",
  6877. attempt,
  6878. remote_path,
  6879. e,
  6880. )
  6881. if delete_result == DeleteResult.DELETED:
  6882. any_deleted = True
  6883. logger.info("Deleted %s from printer %s SD card", remote_path, printer.name)
  6884. break
  6885. if delete_result == DeleteResult.NOT_FOUND:
  6886. any_not_found = True
  6887. break # 550 will not recover; try next candidate
  6888. # FAILED: real error — retry with backoff, then give up
  6889. if attempt < 3:
  6890. await asyncio.sleep(2)
  6891. else:
  6892. any_real_failure = True
  6893. logger.warning(
  6894. "SD card cleanup failed after 3 attempts for %s "
  6895. "(network/auth/transient error — file may linger on SD card)",
  6896. remote_path,
  6897. )
  6898. if not any_deleted and not any_real_failure and any_not_found:
  6899. # Every candidate said "not here." Either the printer
  6900. # firmware swept the SD card itself (common on A1) or the
  6901. # dispatcher's upload path doesn't match our candidate
  6902. # rule. Either way: nothing to clean up, no warning.
  6903. logger.debug(
  6904. "SD card cleanup: nothing to delete on %s — every candidate returned 550 "
  6905. "(printer likely self-cleaned)",
  6906. printer.name,
  6907. )
  6908. except Exception as e:
  6909. logger.warning("SD card file cleanup failed for printer %s: %s", printer_id, e)
  6910. async def on_print_complete(printer_id: int, data: dict):
  6911. """Handle print completion - update the archive status."""
  6912. import time
  6913. logger = logging.getLogger(__name__)
  6914. start_time = time.time()
  6915. def log_timing(section: str):
  6916. elapsed = time.time() - start_time
  6917. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  6918. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  6919. # A kill-switch stop sends its provider notification immediately. Keep the
  6920. # task so the later notification path can await it and avoid a duplicate;
  6921. # if that immediate attempt failed, the regular completion path retries.
  6922. kill_switch_notification_task = _kill_switch_notification_tasks.pop(printer_id, None)
  6923. # Last chance before the bytes go: if this print's archive is still an empty
  6924. # fallback and something downloaded the 3MF while it ran, fill the archive in
  6925. # now. The cover endpoint's copy lives in exactly this cache, and clearing it
  6926. # below deletes the file (#2957).
  6927. await _recover_fallback_from_cache_before_eviction(printer_id, data)
  6928. # A pending cool-off retry has nothing left to recover for — the cache is
  6929. # about to be dropped and the print is over.
  6930. retry_task = _fallback_3mf_retry_tasks.pop(printer_id, None)
  6931. if retry_task and not retry_task.done():
  6932. retry_task.cancel()
  6933. # Drop the 3MF download cache for this printer (#972). The print is over,
  6934. # nothing else legitimately needs the bytes; keeping them would only risk
  6935. # handing a stale file to the next print if it reuses the same name.
  6936. clear_3mf_cache(printer_id)
  6937. try:
  6938. ws_data = {
  6939. "status": data.get("status"),
  6940. "filename": data.get("filename"),
  6941. "subtask_name": data.get("subtask_name"),
  6942. "timelapse_was_active": data.get("timelapse_was_active"),
  6943. }
  6944. await ws_manager.send_print_complete(printer_id, ws_data)
  6945. log_timing("WebSocket send_print_complete")
  6946. except Exception as e:
  6947. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  6948. # Capture user info before clearing (needed for print log entry)
  6949. _print_user_info = printer_manager.get_current_print_user(printer_id)
  6950. # Clear current print user tracking (Issue #206)
  6951. printer_manager.clear_current_print_user(printer_id)
  6952. # If the user explicitly stopped this print from the queue UI the printer will
  6953. # report "failed" or "aborted" via MQTT. Override that to "cancelled" so the
  6954. # correct "print stopped" notification/email is sent instead of a failure alert.
  6955. _raw_status = data.get("status", "completed")
  6956. if printer_id in _user_stopped_printers and _raw_status in ("failed", "aborted"):
  6957. logger.info(
  6958. "[CALLBACK] Overriding status '%s' -> 'cancelled' for printer %s (print was stopped from queue by user)",
  6959. _raw_status,
  6960. printer_id,
  6961. )
  6962. data = {**data, "status": "cancelled"}
  6963. _user_stopped_printers.discard(printer_id)
  6964. # Raise the plate-clear gate for queued dispatch (#961). Any terminal status
  6965. # may have left material on the bed: a user can cancel ten hours into a
  6966. # twelve-hour print, a printer can self-abort mid-job after a clog, and a
  6967. # touchscreen-stop reports `aborted` rather than `cancelled` because
  6968. # `_user_stopped_printers` is only populated when the user stops via the
  6969. # Bambuddy queue UI. Earlier code raised the flag only for completed/failed,
  6970. # which auto-dispatched the next queued print onto a fouled bed two seconds
  6971. # after a touchscreen-abort (#1171). Persisted to DB so the gate survives
  6972. # Auto Off power cycles and Bambuddy restarts.
  6973. try:
  6974. notify_live_activities.print_finished(printer_id, data)
  6975. except Exception:
  6976. logger.exception("Notify Live Activity completion hook failed for printer %s", printer_id)
  6977. _final_status = data.get("status", "completed")
  6978. if _final_status in ("completed", "failed", "aborted", "cancelled"):
  6979. printer_manager.set_awaiting_plate_clear(printer_id, True)
  6980. # MQTT relay - publish print complete
  6981. try:
  6982. printer_info = printer_manager.get_printer(printer_id)
  6983. if printer_info:
  6984. await mqtt_relay.on_print_complete(
  6985. printer_id,
  6986. printer_info.name,
  6987. printer_info.serial_number,
  6988. data.get("filename", ""),
  6989. data.get("subtask_name", ""),
  6990. data.get("status", "completed"),
  6991. )
  6992. except Exception:
  6993. pass # Don't fail print complete callback if MQTT fails
  6994. filename = data.get("filename", "")
  6995. subtask_name = data.get("subtask_name", "")
  6996. if not filename and not subtask_name:
  6997. logger.warning("Print complete without filename or subtask_name")
  6998. return
  6999. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  7000. # Build list of possible keys to try (matching how they were registered in on_print_start)
  7001. possible_keys = _completion_print_keys(printer_id, filename, subtask_name)
  7002. # Find the archive for this print
  7003. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  7004. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  7005. archive_id = None
  7006. for key in possible_keys:
  7007. archive_id = _active_prints.pop(key, None)
  7008. if archive_id:
  7009. logger.info("Found archive %s with key %s", archive_id, key)
  7010. # Also clean up any other keys pointing to this archive
  7011. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  7012. for k in keys_to_remove:
  7013. _active_prints.pop(k, None)
  7014. break
  7015. # The archive bound when the print started, before the name search below.
  7016. # Only this one may give the finish-photo plate restore a height (#3240):
  7017. # the search matches names by substring.
  7018. bound_archive_id = archive_id
  7019. if not archive_id:
  7020. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  7021. async with async_session() as db:
  7022. from backend.app.models.archive import PrintArchive
  7023. # Try matching by subtask_name (stored as print_name) first
  7024. if subtask_name:
  7025. result = await db.execute(
  7026. select(PrintArchive)
  7027. .where(PrintArchive.printer_id == printer_id)
  7028. .where(PrintArchive.status == "printing")
  7029. .where(
  7030. or_(
  7031. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  7032. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  7033. )
  7034. )
  7035. .order_by(PrintArchive.created_at.desc())
  7036. .limit(1)
  7037. )
  7038. archive = result.scalar_one_or_none()
  7039. if archive:
  7040. archive_id = archive.id
  7041. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  7042. # Also try by filename
  7043. if not archive_id and filename:
  7044. result = await db.execute(
  7045. select(PrintArchive)
  7046. .where(PrintArchive.printer_id == printer_id)
  7047. .where(PrintArchive.filename == filename)
  7048. .where(PrintArchive.status == "printing")
  7049. .order_by(PrintArchive.created_at.desc())
  7050. .limit(1)
  7051. )
  7052. archive = result.scalar_one_or_none()
  7053. if archive:
  7054. archive_id = archive.id
  7055. await _cleanup_sd_card_after_print(printer_id, subtask_name, archive_id, logger)
  7056. log_timing("SD card cleanup")
  7057. # Update queue item status early — must run before the archive_id early-return
  7058. # so queue items don't get stuck in "printing" when archive lookup fails.
  7059. # Uses run_with_retry to handle SQLite "database is locked" errors (#897).
  7060. queue_item_id = None
  7061. billing_run_id: str | None = None
  7062. billing_user_id: int | None = None
  7063. billing_cost_center_id: int | None = None
  7064. billing_plate_id: int | None = None
  7065. queue_status = None
  7066. queue_auto_off = False
  7067. try:
  7068. from backend.app.core.database import run_with_retry
  7069. from backend.app.models.print_queue import PrintQueueItem
  7070. async def _update_queue_status(db):
  7071. nonlocal billing_run_id, billing_user_id, billing_cost_center_id, billing_plate_id
  7072. nonlocal queue_item_id, queue_status, queue_auto_off
  7073. result = await db.execute(
  7074. select(PrintQueueItem)
  7075. .where(PrintQueueItem.printer_id == printer_id)
  7076. .where(PrintQueueItem.status == "printing")
  7077. )
  7078. printing_items = list(result.scalars().all())
  7079. if len(printing_items) > 1:
  7080. logger.warning(
  7081. "BUG: Multiple queue items in 'printing' status for printer %s: %s",
  7082. printer_id,
  7083. [(i.id, i.archive_id, i.library_file_id) for i in printing_items],
  7084. )
  7085. item = printing_items[0] if printing_items else None
  7086. if item is not None and not await _completion_belongs_to_queue_item(db, item, data):
  7087. return
  7088. if item:
  7089. queue_status = data.get("status", "completed")
  7090. # MQTT sends "aborted" for cancelled prints; normalise to
  7091. # "cancelled" so it matches the queue schema Literal.
  7092. if queue_status == "aborted":
  7093. queue_status = "cancelled"
  7094. item.status = queue_status
  7095. item.completed_at = datetime.now(timezone.utc)
  7096. if queue_status == "failed" and not item.error_message:
  7097. item.error_message = _format_hms_error_summary(data.get("hms_errors") or [])
  7098. # Bump usage counters on the source library file so admins can
  7099. # sort by "last printed" and (eventually) auto-purge stale
  7100. # files — #1008.
  7101. await _bump_library_file_usage_if_completed(db, item, queue_status)
  7102. await db.commit()
  7103. queue_item_id = item.id
  7104. billing_run_id = item.billing_run_id
  7105. billing_user_id = item.created_by_id
  7106. billing_cost_center_id = item.cost_center_id
  7107. billing_plate_id = item.plate_id
  7108. queue_auto_off = item.auto_off_after
  7109. logger.info("Updated queue item %s status to %s", item.id, queue_status)
  7110. await run_with_retry(_update_queue_status, label="queue status update")
  7111. # Post-commit side effects (notifications, MQTT relay, auto-off) use
  7112. # their own sessions and have their own error handling — no retry needed.
  7113. if queue_item_id is not None:
  7114. # Batch orders (#342): this run may have been the last one an order
  7115. # owed. Re-evaluate here rather than lazily on read, so a finished
  7116. # order reports itself complete without someone opening the page.
  7117. try:
  7118. from backend.app.services.print_batch import refresh_batch_status_for_item
  7119. async with async_session() as db:
  7120. await refresh_batch_status_for_item(db, queue_item_id)
  7121. await db.commit()
  7122. except Exception as e:
  7123. logger.warning("[BATCH] Failed to refresh batch status for queue item %s: %s", queue_item_id, e)
  7124. # MQTT relay - publish queue job completed
  7125. try:
  7126. printer_info = printer_manager.get_printer(printer_id)
  7127. await mqtt_relay.on_queue_job_completed(
  7128. job_id=queue_item_id,
  7129. filename=filename or subtask_name,
  7130. printer_id=printer_id,
  7131. printer_name=printer_info.name if printer_info else "Unknown",
  7132. status=queue_status,
  7133. )
  7134. except Exception:
  7135. pass # Don't fail if MQTT fails
  7136. # Check if queue is now empty and send notification
  7137. try:
  7138. from sqlalchemy import func as sa_func
  7139. async with async_session() as db:
  7140. count_result = await db.execute(
  7141. select(sa_func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  7142. )
  7143. pending_count = count_result.scalar() or 0
  7144. if pending_count == 0:
  7145. today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
  7146. completed_result = await db.execute(
  7147. select(sa_func.count(PrintQueueItem.id)).where(
  7148. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  7149. PrintQueueItem.completed_at >= today_start,
  7150. )
  7151. )
  7152. completed_count = completed_result.scalar() or 1
  7153. await notification_service.on_queue_completed(
  7154. completed_count=completed_count,
  7155. db=db,
  7156. )
  7157. except Exception:
  7158. pass # Don't fail if notification fails
  7159. # Handle auto_off_after - power off printer if the queue item opted
  7160. # in. Delegates to the smart-plug manager so the off honours each
  7161. # plug's configured strategy (time delay or temperature threshold),
  7162. # is cancelled if the printer starts printing again, and never cuts
  7163. # power on a loaded print (#1890). Previously an inline block here
  7164. # hardcoded a 50°C / 600s cooldown wait and powered off on the
  7165. # timeout regardless of print state — cutting a touchscreen reprint.
  7166. if queue_auto_off:
  7167. try:
  7168. async with async_session() as db:
  7169. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  7170. except Exception as e:
  7171. logger.warning("Failed to schedule queue auto-off for printer %s: %s", printer_id, e)
  7172. except Exception as e:
  7173. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  7174. log_timing("Queue item update")
  7175. # Register bed cooldown waiter (event-driven via on_bed_temp_update callback).
  7176. # Must run before archive_id early-return so it fires for all prints (including
  7177. # prints started from BambuStudio/touchscreen that have no archive).
  7178. if data.get("status") == "completed":
  7179. try:
  7180. from backend.app.api.routes.settings import get_setting
  7181. async with async_session() as db:
  7182. threshold_str = await get_setting(db, "bed_cooled_threshold")
  7183. threshold = float(threshold_str) if threshold_str else 35.0
  7184. # Check if any provider has on_bed_cooled enabled (skip registration if none)
  7185. async with async_session() as db:
  7186. providers = await notification_service._get_providers_for_event(db, "on_bed_cooled", printer_id)
  7187. if providers:
  7188. _bed_cool_waiters[printer_id] = {
  7189. "threshold": threshold,
  7190. "filename": filename or subtask_name or "",
  7191. "registered_at": time.time(),
  7192. }
  7193. logger.info(
  7194. "[BED-COOL] Registered waiter for printer %s (threshold: %.0f°C)",
  7195. printer_id,
  7196. threshold,
  7197. )
  7198. else:
  7199. logger.debug("[BED-COOL] No providers enabled for bed_cooled on printer %s", printer_id)
  7200. except Exception as e:
  7201. logger.warning("[BED-COOL] Failed to register waiter: %s", e)
  7202. # Capture the slicer estimate before usage tracking runs. The tracker may
  7203. # update archive.cost with this run's measured cost; billing partial runs
  7204. # against that already-partial value would discount the charge twice.
  7205. billing_planned_grams: float | None = None
  7206. billing_base_cost: float | None = None
  7207. if archive_id:
  7208. try:
  7209. async with async_session() as db:
  7210. from backend.app.models.archive import PrintArchive
  7211. billing_archive = await db.get(PrintArchive, archive_id)
  7212. if billing_archive:
  7213. billing_path = (
  7214. app_settings.base_dir / billing_archive.file_path if billing_archive.file_path else None
  7215. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7216. billing_planned_grams, billing_base_cost = _plate_scoped_run_estimate(
  7217. billing_archive,
  7218. billing_path,
  7219. billing_plate_id if billing_plate_id is not None else _get_start_plate_id(archive_id),
  7220. )
  7221. except Exception as e:
  7222. logger.warning("[FINANCE] Failed to capture planned usage for archive %s: %s", archive_id, e)
  7223. # --- Track filament consumption (must run before archive_id early-return so usage
  7224. # is recorded even when auto-archive is disabled) ---
  7225. usage_results: list[dict] = []
  7226. # Prefer ams_mapping captured from MQTT request topic (works for all print sources)
  7227. stored_ams_mapping = data.get("ams_mapping")
  7228. # Fallback to _print_ams_mappings for queue/reprint (set before print starts)
  7229. if not stored_ams_mapping and archive_id:
  7230. stored_ams_mapping = _print_ams_mappings.pop(archive_id, None)
  7231. # Always drain the plate_id register on completion — the session already
  7232. # consumed it at print-start injection; leaving it would leak into the next
  7233. # print on the same archive_id (rare but possible with reprints) (#1697).
  7234. # Capture the popped value so the completion notification can scope the
  7235. # archive-level (summed-across-plates per #1593) filament + time totals
  7236. # down to the single plate that was actually printed (#1785).
  7237. notify_plate_id: int | None = None
  7238. if archive_id:
  7239. notify_plate_id = _print_plate_ids.pop(archive_id, None)
  7240. # Internal inventory: track AMS remain% deltas (skip if Spoolman handles usage)
  7241. try:
  7242. async with async_session() as db:
  7243. from backend.app.api.routes.settings import get_setting
  7244. _spoolman_on = await get_setting(db, "spoolman_enabled")
  7245. if not _spoolman_on or _spoolman_on.lower() != "true":
  7246. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  7247. async with async_session() as db:
  7248. usage_results = await usage_on_print_complete(
  7249. printer_id,
  7250. data,
  7251. printer_manager,
  7252. db,
  7253. archive_id=archive_id,
  7254. ams_mapping=stored_ams_mapping,
  7255. )
  7256. if usage_results:
  7257. await ws_manager.broadcast(
  7258. {
  7259. "type": "spool_usage_logged",
  7260. "printer_id": printer_id,
  7261. "usage": usage_results,
  7262. }
  7263. )
  7264. log_timing("Usage tracker")
  7265. except Exception as e:
  7266. logger.warning("Usage tracker on_print_complete failed: %s", e)
  7267. # Drop the print-start context unconditionally — the Spoolman branch above
  7268. # skips the internal tracker entirely, so nothing else would clear what
  7269. # print start captured, and a row surviving its print would be restored
  7270. # onto the next one after a restart.
  7271. try:
  7272. from backend.app.services.usage_tracker import discard_session
  7273. async with async_session() as db:
  7274. await discard_session(db, printer_id)
  7275. except Exception as e:
  7276. logger.warning("Failed to clear persisted print session for printer %s: %s", printer_id, e)
  7277. # Spoolman: report filament usage (requires archive_id for tracking data lookup)
  7278. # A partial run's cost from the Spoolman spools it was charged to; the
  7279. # built-in inventory's comes in usage_results.
  7280. spoolman_run_cost: float | None = None
  7281. if archive_id:
  7282. if data.get("status") == "completed":
  7283. try:
  7284. await _report_spoolman_usage(printer_id, archive_id)
  7285. log_timing("Spoolman usage report")
  7286. except Exception as e:
  7287. logger.warning("Spoolman usage reporting failed: %s", e)
  7288. else:
  7289. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  7290. try:
  7291. async with async_session() as db:
  7292. spoolman_run_cost = await _cleanup_spoolman_tracking(
  7293. printer_id,
  7294. archive_id,
  7295. db,
  7296. last_layer_num=data.get("last_layer_num"),
  7297. last_progress=data.get("last_progress"),
  7298. )
  7299. except Exception as e:
  7300. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  7301. await _release_archived_spoolman_slots(printer_id)
  7302. log_timing("Filament usage tracking")
  7303. if not archive_id:
  7304. # The printer's own calibration run has no archive by design, so this
  7305. # arrives here every time one finishes. Returning before the no-archive
  7306. # notification keeps a calibration from being announced as a finished
  7307. # print. Everything above this point has already run — the plate-clear
  7308. # gate, the queue reconciliation, the SD-card cleanup — so only the
  7309. # notification is skipped.
  7310. if is_internal_printer_job(filename, subtask_name):
  7311. logger.info(
  7312. "[CALLBACK] Internal printer job completed, no notification: filename=%s, subtask=%s",
  7313. filename,
  7314. subtask_name,
  7315. )
  7316. return
  7317. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  7318. # Still send print-complete/failed/stopped notifications even without an archive.
  7319. # Try to enrich with queue/library-file data so user-specific emails work too.
  7320. async def _notify_no_archive():
  7321. try:
  7322. async with async_session() as db:
  7323. from backend.app.models.library import LibraryFile
  7324. from backend.app.models.print_queue import PrintQueueItem
  7325. from backend.app.models.printer import Printer
  7326. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7327. printer_obj = result.scalar_one_or_none()
  7328. p_name = printer_obj.name if printer_obj else f"Printer {printer_id}"
  7329. # Only the queue item this completion itself closed (the
  7330. # reconciliation above, which checks the run belongs to it).
  7331. # A print started outside Bambuddy closed none, and must not
  7332. # borrow an earlier job's owner, email or times.
  7333. no_archive_data: dict | None = None
  7334. try:
  7335. queue_item = await db.get(PrintQueueItem, queue_item_id) if queue_item_id else None
  7336. if queue_item:
  7337. no_archive_data = {"created_by_id": queue_item.created_by_id}
  7338. # How long it really ran, as the archive path reports it (#1198).
  7339. started = to_naive_utc(queue_item.started_at)
  7340. ended = to_naive_utc(queue_item.completed_at)
  7341. if started and ended and (ended - started).total_seconds() > 0:
  7342. no_archive_data["actual_time_seconds"] = int((ended - started).total_seconds())
  7343. # Estimated time: the queue item caches it from its
  7344. # archive or library file; otherwise read the library
  7345. # file's metadata (LibraryFile has no column for it).
  7346. if queue_item.print_time_seconds:
  7347. no_archive_data["print_time_seconds"] = queue_item.print_time_seconds
  7348. elif queue_item.library_file_id:
  7349. lib_result = await db.execute(
  7350. select(LibraryFile).where(LibraryFile.id == queue_item.library_file_id)
  7351. )
  7352. lib_file = lib_result.scalar_one_or_none()
  7353. estimate = (
  7354. (lib_file.file_metadata or {}).get("print_time_seconds") if lib_file else None
  7355. )
  7356. if estimate:
  7357. no_archive_data["print_time_seconds"] = estimate
  7358. except Exception as lookup_err:
  7359. logger.debug(
  7360. "[NOTIFY-BG] Could not look up queue item for no-archive notification: %s", lookup_err
  7361. )
  7362. # Enrich with usage tracker results (captured in enclosing scope)
  7363. if usage_results:
  7364. if no_archive_data is None:
  7365. no_archive_data = {}
  7366. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  7367. if total_from_usage > 0:
  7368. no_archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  7369. no_archive_data["usage_results"] = usage_results
  7370. # Try MQTT remaining_time for print duration when no queue/library data
  7371. if no_archive_data and not no_archive_data.get("print_time_seconds"):
  7372. mqtt_remaining = data.get("remaining_time")
  7373. if mqtt_remaining and isinstance(mqtt_remaining, (int, float)) and mqtt_remaining > 0:
  7374. no_archive_data["print_time_seconds"] = int(mqtt_remaining)
  7375. ps = data.get("status", "completed")
  7376. logger.info(
  7377. "[NOTIFY-BG] Sending notification without archive: printer=%s, status=%s", printer_id, ps
  7378. )
  7379. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  7380. await notification_service.on_print_complete(
  7381. printer_id, p_name, ps, data, db, archive_data=no_archive_data
  7382. )
  7383. else:
  7384. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  7385. # Send user-specific email if we have a created_by_id
  7386. if no_archive_data and no_archive_data.get("created_by_id"):
  7387. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  7388. await _dispatch_user_print_email(
  7389. ps,
  7390. no_archive_data["created_by_id"],
  7391. p_name,
  7392. raw_filename,
  7393. db,
  7394. )
  7395. logger.info("[NOTIFY-BG] Completed (no-archive path)")
  7396. except Exception as e:
  7397. logger.warning("[NOTIFY-BG] Failed to send notification without archive: %s", e, exc_info=True)
  7398. spawn_background_task(_notify_no_archive(), name="notify-no-archive")
  7399. return
  7400. log_timing("Archive lookup")
  7401. # Update archive status
  7402. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  7403. try:
  7404. async with async_session() as db:
  7405. service = ArchiveService(db)
  7406. status = data.get("status", "completed")
  7407. hms_errors = data.get("hms_errors", []) if status == "failed" else None
  7408. if hms_errors:
  7409. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  7410. failure_reason = derive_failure_reason(status, hms_errors)
  7411. if data.get("_reconciled"):
  7412. # A reconciled completion closes out a stale archive at
  7413. # reconnect — it is not a user action, so don't mislabel it
  7414. # "userCancelled". It shares the stale-cleanup path's key
  7415. # (issue #2974) and records that the real end time is unknown,
  7416. # which is also why its logged duration is 0 (#2592).
  7417. failure_reason = "noStatusUpdate"
  7418. if failure_reason:
  7419. logger.info("[ARCHIVE] failure_reason=%r (status=%s)", failure_reason, status)
  7420. elif status == "failed" and hms_errors:
  7421. logger.info("[ARCHIVE] HMS errors present but none matched a known failure-reason short code")
  7422. await service.update_archive_status(
  7423. archive_id,
  7424. status=status,
  7425. completed_at=(
  7426. datetime.now(timezone.utc) if status in ("completed", "failed", "aborted", "cancelled") else None
  7427. ),
  7428. failure_reason=failure_reason,
  7429. )
  7430. logger.info(
  7431. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  7432. )
  7433. await ws_manager.send_archive_updated(
  7434. {
  7435. "id": archive_id,
  7436. "status": status,
  7437. }
  7438. )
  7439. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  7440. # MQTT relay - publish archive updated
  7441. try:
  7442. await mqtt_relay.on_archive_updated(
  7443. archive_id=archive_id,
  7444. print_name=filename or subtask_name,
  7445. status=status,
  7446. )
  7447. except Exception:
  7448. pass # Don't fail if MQTT fails
  7449. except Exception as e:
  7450. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  7451. # Continue with other operations even if archive update fails
  7452. log_timing("Archive status update")
  7453. # Apply finance wallet charge or release reservations once. For all partial
  7454. # terminal states (failed, aborted at the printer display, or cancelled via
  7455. # Bambuddy) use this run's measured spool delta, falling back to the last
  7456. # valid printer progress. PrintArchive.filament_used_grams is the slicer
  7457. # estimate and therefore cannot represent an interrupted run.
  7458. try:
  7459. if data.get("status") in ("completed", "failed", "aborted", "cancelled"):
  7460. async with async_session() as db:
  7461. from backend.app.models.archive import PrintArchive
  7462. from backend.app.services.finance_billing import apply_print_charge_for_archive
  7463. archive = await db.get(PrintArchive, archive_id)
  7464. if archive and billing_run_id is None:
  7465. billing_run_id = getattr(archive, "billing_run_id", None)
  7466. if archive and archive.created_by_id is None and _print_user_info:
  7467. archive.created_by_id = await _print_user_id_if_still_there(db, _print_user_info)
  7468. await db.flush()
  7469. run_status = data.get("status", "completed")
  7470. last_progress = data.get("last_progress")
  7471. if last_progress is None:
  7472. last_progress = data.get("progress")
  7473. actual_run_grams = _compute_run_filament_grams(
  7474. run_status,
  7475. billing_planned_grams,
  7476. last_progress,
  7477. usage_results,
  7478. )
  7479. filament_usage = (actual_run_grams, billing_planned_grams) if run_status != "completed" else None
  7480. in_memory_cost_center_id = _print_cost_center_ids.pop(archive_id, None)
  7481. charged = await apply_print_charge_for_archive(
  7482. db,
  7483. archive_id,
  7484. charged_user_id=billing_user_id,
  7485. cost_center_id=(
  7486. billing_cost_center_id if billing_cost_center_id is not None else in_memory_cost_center_id
  7487. ),
  7488. print_queue_id=queue_item_id,
  7489. print_run_id=billing_run_id,
  7490. base_cost_override=billing_base_cost,
  7491. filament_usage=filament_usage,
  7492. )
  7493. await db.commit()
  7494. if charged:
  7495. logger.info("[FINANCE] Applied print charge for archive %s", archive_id)
  7496. except Exception as e:
  7497. logger.warning("[FINANCE] Failed to apply print charge for archive %s: %s", archive_id, e)
  7498. printer_info = printer_manager.get_printer(printer_id)
  7499. billing_printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  7500. billing_filename = filename or subtask_name or "Unknown"
  7501. billing_error = str(e)
  7502. try:
  7503. await ws_manager.broadcast(
  7504. {
  7505. "type": "billing_charge_failed",
  7506. "printer_id": printer_id,
  7507. "printer_name": billing_printer_name,
  7508. "filename": billing_filename,
  7509. "archive_id": archive_id,
  7510. }
  7511. )
  7512. except Exception as notification_error:
  7513. logger.error(
  7514. "[FINANCE] Failed to broadcast billing error for archive %s: %s",
  7515. archive_id,
  7516. notification_error,
  7517. )
  7518. async def _notify_billing_charge_failed() -> None:
  7519. try:
  7520. async with async_session() as notification_db:
  7521. await notification_service.on_billing_charge_failed(
  7522. printer_id,
  7523. billing_printer_name,
  7524. billing_filename,
  7525. archive_id,
  7526. billing_error,
  7527. notification_db,
  7528. )
  7529. except Exception as provider_error:
  7530. logger.error(
  7531. "[FINANCE] Failed to send provider billing alert for archive %s: %s",
  7532. archive_id,
  7533. provider_error,
  7534. exc_info=True,
  7535. )
  7536. spawn_background_task(
  7537. _notify_billing_charge_failed(),
  7538. name=f"billing-charge-failed-{archive_id}",
  7539. )
  7540. log_timing("Finance charge update")
  7541. # Write independent print log entry (separate table, never touches archives)
  7542. try:
  7543. async with async_session() as db:
  7544. from backend.app.models.archive import PrintArchive
  7545. from backend.app.services.print_log import record_archive_wear, write_log_entry
  7546. archive = await db.get(PrintArchive, archive_id)
  7547. if archive:
  7548. # Back-fill created_by_id on reprint (#730): reprint reuses the
  7549. # source archive row rather than creating a new one, so an
  7550. # archive that was auto-created from a printer-initiated
  7551. # print (created_by_id=NULL) would otherwise stay unattributed
  7552. # forever. When we have a print-session user AND the archive
  7553. # has no attribution yet, credit the current user. Never
  7554. # overwrite an existing attribution — the original uploader
  7555. # keeps ownership.
  7556. _print_user_id = await _print_user_id_if_still_there(db, _print_user_info)
  7557. if archive.created_by_id is None and _print_user_id is not None:
  7558. archive.created_by_id = _print_user_id
  7559. p_info = printer_manager.get_printer(printer_id)
  7560. # Per-run actuals — written to PrintLogEntry so stats reflect
  7561. # what THIS print actually used, not the source archive's
  7562. # first-run values (#1378). Helper handles the partial-print
  7563. # math (failed / cancelled / stopped get scaled to progress
  7564. # or to tracked spool deltas).
  7565. _run_status = data.get("status", "completed")
  7566. # #2614: scope the per-run estimate to the printed plate. For a
  7567. # multi-plate 3MF dispatched one plate at a time, the archive's
  7568. # filament/cost are the whole-file totals; the PrintLogEntry must
  7569. # reflect only this plate. No effect on single-plate archives (the
  7570. # plate estimate equals the whole-file value) or on the tracker
  7571. # path (measured spool deltas win in _compute_run_filament_grams).
  7572. _est_full_path = (
  7573. app_settings.base_dir / archive.file_path if archive.file_path else None
  7574. ) # SEC-PATH-OK: archive.file_path is DB-stored, internally generated
  7575. # The plate that printed, as billing reads it: a reprint of
  7576. # another plate must not log the archive's first plate.
  7577. _est_grams, _est_cost = _plate_scoped_run_estimate(
  7578. archive,
  7579. _est_full_path,
  7580. billing_plate_id if billing_plate_id is not None else notify_plate_id,
  7581. )
  7582. _run_grams = _compute_run_filament_grams(
  7583. _run_status,
  7584. _est_grams,
  7585. data.get("last_progress", data.get("progress")),
  7586. usage_results,
  7587. )
  7588. # Per-run cost — prefer usage_results sum. For partial prints
  7589. # we deliberately skip the topup-to-estimate logic in
  7590. # usage_tracker (which assumes the print completed); the raw
  7591. # tracked-spool sum is closer to what THIS run actually cost.
  7592. _run_cost: float | None = None
  7593. if usage_results:
  7594. _run_cost = sum(r.get("cost") or 0 for r in usage_results) or None
  7595. if _run_cost is None and _run_status != "completed":
  7596. _run_cost = spoolman_run_cost
  7597. if _run_cost is None and _run_status == "completed":
  7598. _run_cost = _est_cost
  7599. from backend.app.models.printer import Printer as _Printer
  7600. _wear_rate = await db.scalar(select(_Printer.wear_cost_per_hour).where(_Printer.id == printer_id))
  7601. run_entry = await write_log_entry(
  7602. db,
  7603. archive_id=archive.id,
  7604. # Captured by _update_queue_status above; None for
  7605. # printer-initiated prints with no queue row. Batch
  7606. # cost/energy roll-up joins on it (#342).
  7607. queue_item_id=queue_item_id,
  7608. status=_run_status,
  7609. print_name=archive.print_name,
  7610. printer_name=p_info.name if p_info else None,
  7611. printer_id=printer_id,
  7612. started_at=archive.started_at,
  7613. completed_at=archive.completed_at,
  7614. filament_type=archive.filament_type,
  7615. filament_color=archive.filament_color,
  7616. filament_used_grams=_run_grams,
  7617. cost=_run_cost,
  7618. wear_cost_per_hour=_wear_rate,
  7619. failure_reason=archive.failure_reason,
  7620. thumbnail_path=archive.thumbnail_path,
  7621. created_by_id=archive.created_by_id,
  7622. created_by_username=_print_user_info.get("username") if _print_user_info else None,
  7623. # Reconciled completions have an unknown real end time —
  7624. # log 0 duration instead of the whole disconnect gap (#2592).
  7625. reconciled=bool(data.get("_reconciled")),
  7626. )
  7627. await record_archive_wear(db, archive, run_entry)
  7628. await db.commit()
  7629. logger.info("[PRINT_LOG] Log entry written for archive %s", archive_id)
  7630. except Exception as e:
  7631. logger.warning("[PRINT_LOG] Failed to write log entry for archive %s: %s", archive_id, e)
  7632. log_timing("Print log entry")
  7633. # Run slow operations as background tasks to avoid blocking the event loop
  7634. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  7635. async def _background_energy_calculation():
  7636. """Calculate and save energy usage in background.
  7637. Reads the starting kWh from the archive row (#941: persisted so a mid-print
  7638. backend restart no longer loses per-print energy data).
  7639. """
  7640. try:
  7641. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  7642. async with async_session() as db:
  7643. from backend.app.models.archive import PrintArchive
  7644. archive = await db.get(PrintArchive, archive_id)
  7645. if archive is None:
  7646. logger.warning("[ENERGY-BG] Archive %s no longer exists", archive_id)
  7647. return
  7648. starting_kwh = archive.energy_start_kwh
  7649. if starting_kwh is None:
  7650. logger.info("[ENERGY-BG] No start kWh recorded for archive %s", archive_id)
  7651. return
  7652. candidates = await energy_plug_candidates(db, printer_id)
  7653. if not candidates:
  7654. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  7655. return
  7656. # Same ordering as the start reading, so the delta below is
  7657. # against the counter that produced `starting_kwh` (#2859).
  7658. selected = await select_energy_reading(candidates, _get_plug_energy, db)
  7659. if selected is None:
  7660. logger.warning(
  7661. "[ENERGY-BG] No plug on printer %s reports a lifetime energy counter (tried: %s)",
  7662. printer_id,
  7663. ", ".join(plug.name for plug in candidates),
  7664. )
  7665. return
  7666. plug, energy = selected
  7667. logger.info("[ENERGY-BG] Energy response from plug '%s': %s", plug.name, energy)
  7668. energy_used = round(energy["total"] - starting_kwh, 4)
  7669. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  7670. if energy_used < 0:
  7671. logger.warning(
  7672. "[ENERGY-BG] Negative energy delta for archive %s (start=%s, end=%s) — counter reset?",
  7673. archive_id,
  7674. starting_kwh,
  7675. energy["total"],
  7676. )
  7677. return
  7678. from backend.app.services.energy_price import current_price, print_energy_cost, stored_price
  7679. # Each hour of the print at the price of that hour (#1251). If
  7680. # that fails, the last price known, as before, rather than no
  7681. # energy at all. Read first: the session may be unusable after.
  7682. last_price = await stored_price(db)
  7683. try:
  7684. energy_cost_value = round(
  7685. await print_energy_cost(
  7686. db,
  7687. plug_id=archive.energy_start_plug_id,
  7688. start_at=archive.energy_start_at,
  7689. start_kwh=starting_kwh,
  7690. start_price=archive.energy_start_price,
  7691. end_kwh=energy["total"],
  7692. end_plug_id=plug.id,
  7693. price_now=await current_price(db),
  7694. ),
  7695. 3,
  7696. )
  7697. except Exception as e:
  7698. logger.warning("[ENERGY-BG] Hour-by-hour cost failed for archive %s: %s", archive_id, e)
  7699. energy_cost_value = round(energy_used * last_price, 3)
  7700. # First-run-only overwrite of archive.energy_kwh / energy_cost so a
  7701. # reprint doesn't visually clobber the source archive's energy data
  7702. # (#1378). Reprint energy lives in the matching PrintLogEntry below.
  7703. from sqlalchemy import func
  7704. from backend.app.models.print_log import PrintLogEntry
  7705. existing_runs = await db.scalar(
  7706. select(func.count(PrintLogEntry.id)).where(PrintLogEntry.archive_id == archive_id)
  7707. )
  7708. if (existing_runs or 0) <= 1:
  7709. # 0 = legacy archive that pre-dates per-run logging; 1 = the row
  7710. # we just wrote for THIS print. Either way it's the first run.
  7711. archive.energy_kwh = energy_used
  7712. archive.energy_cost = energy_cost_value
  7713. # Backfill the latest PrintLogEntry for this archive with energy
  7714. # (write_log_entry above ran before this background task completed,
  7715. # so energy fields are still NULL on that row).
  7716. latest_run = await db.execute(
  7717. select(PrintLogEntry)
  7718. .where(PrintLogEntry.archive_id == archive_id)
  7719. .order_by(PrintLogEntry.id.desc())
  7720. .limit(1)
  7721. )
  7722. run_row = latest_run.scalar_one_or_none()
  7723. if run_row is not None:
  7724. run_row.energy_kwh = energy_used
  7725. run_row.energy_cost = energy_cost_value
  7726. await db.commit()
  7727. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost_value)
  7728. except Exception as e:
  7729. logger.warning("[ENERGY-BG] Failed: %s", e)
  7730. async def _background_finish_photo() -> str | None:
  7731. """Capture finish photo in background. Returns photo filename if captured."""
  7732. # #2547: set once this function has raised the plate itself (the
  7733. # timelapse path, where the moment producer returned without doing it).
  7734. # Declared out here so the `finally` can lower it again no matter where
  7735. # the capture below fails.
  7736. plate_restored_z: float | None = None
  7737. try:
  7738. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  7739. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  7740. # Read phase: settings + printer + archive in a short session, released
  7741. # BEFORE the capture pipeline below. The capture (timelapse last-frame,
  7742. # stage-22 wait, external-camera grab, or a fresh RTSP shot) can take
  7743. # tens of seconds; holding this session across it pinned one pooled
  7744. # connection idle-in-transaction per finishing print (issue #2572).
  7745. async with async_session() as db:
  7746. from backend.app.api.routes.settings import get_setting
  7747. from backend.app.models.archive import PrintArchive
  7748. from backend.app.models.printer import Printer
  7749. capture_enabled = await get_setting(db, "capture_finish_photo")
  7750. if capture_enabled is not None and capture_enabled.lower() != "true":
  7751. return None
  7752. if not archive_id:
  7753. return None
  7754. printer = (await db.execute(select(Printer).where(Printer.id == printer_id))).scalar_one_or_none()
  7755. archive = (
  7756. await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7757. ).scalar_one_or_none()
  7758. if not printer or not archive:
  7759. return None
  7760. import uuid
  7761. from datetime import datetime
  7762. from backend.app.utils.archive_paths import archive_dir as resolve_archive_dir
  7763. if not archive.file_path:
  7764. logger.warning("[PHOTO-BG] Archive %s has no file_path, using fallback dir", archive_id)
  7765. archive_dir = resolve_archive_dir(archive)
  7766. photo_filename = None
  7767. # Prefer the timelapse last-frame source when a timelapse was
  7768. # recording — it captures the moment after the toolhead parks
  7769. # but before the bed drops, which the live-camera grab below
  7770. # would miss (#1397). Skipped for external cameras (those have
  7771. # their own framing and don't see a Bambu timelapse). Only
  7772. # runs when the USER explicitly enabled timelapse for this
  7773. # print — #1721 removed Bambuddy's force-on at dispatch
  7774. # because it caused per-layer nozzle parking on Smooth-mode
  7775. # slicer profiles.
  7776. prefer_timelapse_source = bool(data.get("timelapse_was_active")) and not (
  7777. printer.external_camera_enabled and printer.external_camera_url
  7778. )
  7779. timelapse_still_pending = False
  7780. if prefer_timelapse_source:
  7781. photo_filename, timelapse_still_pending = await _capture_finish_photo_from_timelapse(
  7782. archive_id=archive_id,
  7783. archive_dir=archive_dir,
  7784. rotation=getattr(printer, "camera_rotation", 0),
  7785. )
  7786. # #1721: replacement framing path — on_finish_photo_moment
  7787. # pre-captured a frame at the stage-22 / FINISH edge (toolhead
  7788. # parked, bed not yet dropped) and cached the JPEG bytes in
  7789. # _stage22_finish_frames. Consume them now so the saved photo
  7790. # has the better framing instead of the post-bed-drop angle
  7791. # the live-camera fallback below would give.
  7792. if not photo_filename:
  7793. # #1790: on the FINISH-state fallback path the producer
  7794. # task is dispatched back-to-back with this consumer, so
  7795. # a bare pop would race past with an empty result and
  7796. # the RTSP fallback below would collide with the
  7797. # producer's still-in-flight grab (single-client RTSP
  7798. # on Bambu printers). Wait for the producer to finish
  7799. # or give up before touching the cache.
  7800. #
  7801. # #2547: 20s was enough when the producer only ever grabbed a
  7802. # frame. It now also raises the plate first, which costs the
  7803. # settle window before the grab even starts — so the budget has
  7804. # to cover settle + a worst-case 15s RTSP timeout, and still sit
  7805. # under the notification's own photo wait below.
  7806. in_flight = _stage22_finish_in_flight.pop(printer_id, None)
  7807. if in_flight is not None:
  7808. try:
  7809. await asyncio.wait_for(in_flight.wait(), timeout=_FINISH_PHOTO_PRODUCER_WAIT_SECONDS)
  7810. except TimeoutError:
  7811. logger.warning(
  7812. "[PHOTO-BG] timed out waiting for stage-22 producer for printer %s — proceeding to fallback",
  7813. printer_id,
  7814. )
  7815. cached_frame = _stage22_finish_frames.pop(printer_id, None)
  7816. if cached_frame:
  7817. # Already rotated by the producer (#2708) — rotating again
  7818. # here would undo the fix on the banked-frame path, whose
  7819. # bytes reach the cache having been rotated once already.
  7820. photos_dir = archive_dir / "photos"
  7821. photos_dir.mkdir(parents=True, exist_ok=True)
  7822. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7823. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7824. photo_path = photos_dir / photo_filename
  7825. await asyncio.to_thread(photo_path.write_bytes, cached_frame)
  7826. logger.info(
  7827. "[PHOTO-BG] Saved stage-22 pre-captured frame: %s (%d bytes)",
  7828. photo_filename,
  7829. len(cached_frame),
  7830. )
  7831. # #2547: the timelapse path reaches the live grab below whenever the
  7832. # video hasn't landed in time — the documented usual outcome on
  7833. # P1-series, where transfers are slowest. `on_finish_photo_moment`
  7834. # returned early for those prints without raising the plate, so
  7835. # without this the photo that actually ships in the notification is
  7836. # of an already-dropped plate: exactly the framing #1145/#1397/#1565
  7837. # asked us to fix. The archive still gets the better video frame
  7838. # later; this is about the image the user is sent.
  7839. #
  7840. # Gated on `timelapse_was_active` precisely because that is the
  7841. # condition under which the producer skipped. On every other path it
  7842. # has already raised and lowered the plate, and repeating that here
  7843. # would be a second pointless round trip.
  7844. if (
  7845. not photo_filename
  7846. and data.get("timelapse_was_active")
  7847. and not print_dispatch_context.end_gcode_injected(printer_id)
  7848. ):
  7849. try:
  7850. async with async_session() as db:
  7851. from backend.app.api.routes.settings import get_setting
  7852. restore_setting = await get_setting(db, "finish_photo_restore_plate")
  7853. if restore_setting is None or restore_setting.lower() == "true":
  7854. max_z = await _max_z_for_current_print(
  7855. printer_id, data, logger, bound_archive_id, notify_plate_id
  7856. )
  7857. if max_z is not None and not await _plate_restore_is_blocked_by_queue(printer_id):
  7858. if await _restore_plate_for_finish_photo(printer_id, max_z, logger):
  7859. plate_restored_z = max_z
  7860. except Exception as e:
  7861. logger.warning("[PLATE-RESTORE] printer %s: restore failed: %s", printer_id, e)
  7862. # Fallback chain: external camera → buffered live frame →
  7863. # fresh RTSP capture. Only runs if the timelapse path above
  7864. # didn't already produce a photo.
  7865. # Chamber light for the live capture below (#1655).
  7866. async with camera_light(printer if not photo_filename else None):
  7867. if not photo_filename:
  7868. if printer.external_camera_enabled and printer.external_camera_url:
  7869. logger.info("[PHOTO-BG] Using external camera")
  7870. from backend.app.api.routes.camera import live_frame_for_capture
  7871. from backend.app.services.external_camera import capture_frame
  7872. # #2707: the second half of the finish-photo failure — the
  7873. # pre-capture and this fallback both collided with the live
  7874. # view. None here continues down the fallback chain.
  7875. defer, buffered = live_frame_for_capture(printer_id)
  7876. if defer:
  7877. frame_data = buffered
  7878. else:
  7879. frame_data = await capture_frame(
  7880. printer.external_camera_url,
  7881. printer.external_camera_type or "mjpeg",
  7882. snapshot_url=printer.external_camera_snapshot_url,
  7883. )
  7884. if frame_data:
  7885. frame_data = _apply_camera_rotation(frame_data, printer, logger)
  7886. photos_dir = archive_dir / "photos"
  7887. photos_dir.mkdir(parents=True, exist_ok=True)
  7888. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7889. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7890. photo_path = photos_dir / photo_filename
  7891. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  7892. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  7893. else:
  7894. # Check if camera stream is active - use buffered frame to avoid freeze
  7895. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  7896. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  7897. active_chamber_for_printer = [
  7898. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  7899. ]
  7900. buffered_frame = get_buffered_frame(printer_id)
  7901. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  7902. # Use frame from active stream
  7903. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  7904. buffered_frame = _apply_camera_rotation(buffered_frame, printer, logger)
  7905. photos_dir = archive_dir / "photos"
  7906. photos_dir.mkdir(parents=True, exist_ok=True)
  7907. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  7908. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  7909. photo_path = photos_dir / photo_filename
  7910. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  7911. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  7912. else:
  7913. # No active stream - capture new frame
  7914. from backend.app.services.camera import capture_finish_photo
  7915. photo_filename = await capture_finish_photo(
  7916. printer_id=printer_id,
  7917. ip_address=printer.ip_address,
  7918. access_code=printer.access_code,
  7919. model=printer.model,
  7920. archive_dir=archive_dir,
  7921. rotation=getattr(printer, "camera_rotation", 0),
  7922. )
  7923. # Write phase: attach the photo in a fresh short-lived session.
  7924. if photo_filename:
  7925. async with async_session() as db:
  7926. from backend.app.models.archive import PrintArchive
  7927. arch = await db.get(PrintArchive, archive_id)
  7928. if arch is not None:
  7929. photos = arch.photos or []
  7930. photos.append(photo_filename)
  7931. arch.photos = photos
  7932. await db.commit()
  7933. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  7934. # The short wait above is bounded so a slow printer can't hold up
  7935. # the print-complete notification, which is what the caller is
  7936. # blocking on. When it ran out with the video still on its way,
  7937. # keep waiting off to the side and add the better frame to the
  7938. # archive once it arrives (#2704 follow-up) — otherwise P1-series
  7939. # users, whose videos routinely take minutes to transfer, never get
  7940. # the pre-bed-drop framing this path exists to provide.
  7941. #
  7942. # Spawned here rather than at the point the wait gave up: both this
  7943. # function and the upgrade do a read-modify-write on `photos`, and
  7944. # the live-camera fallback above can take tens of seconds. Starting
  7945. # the upgrade before that write means the two can interleave and one
  7946. # silently drops the other's entry, leaving a JPEG on disk that the
  7947. # gallery never lists.
  7948. if timelapse_still_pending:
  7949. spawn_background_task(
  7950. _upgrade_finish_photo_from_timelapse(
  7951. archive_id, archive_dir, rotation=getattr(printer, "camera_rotation", 0)
  7952. ),
  7953. name=f"finish-photo-upgrade-{archive_id}",
  7954. )
  7955. return photo_filename
  7956. except Exception as e:
  7957. logger.warning("[PHOTO-BG] Failed: %s", e)
  7958. return None
  7959. finally:
  7960. # #2547: we raised the plate, so we owe the move back down — even if
  7961. # the capture in between threw. Otherwise the user finds the print
  7962. # pinned under the nozzle.
  7963. if plate_restored_z is not None:
  7964. try:
  7965. _park_plate_after_finish_photo(printer_id, plate_restored_z, logger)
  7966. except Exception as e:
  7967. logger.warning("[PLATE-RESTORE] printer %s: could not lower plate: %s", printer_id, e)
  7968. spawn_background_task(_background_energy_calculation(), name="background-energy-calc")
  7969. # Photo capture task - result will be used by notifications
  7970. photo_task = spawn_background_task(_background_finish_photo(), name="background-finish-photo")
  7971. log_timing("Background tasks scheduled (energy, photo)")
  7972. # Also run smart plug, notifications, and maintenance as background tasks
  7973. print_status = data.get("status", "completed")
  7974. async def _background_smart_plug():
  7975. """Handle smart plug automation in background."""
  7976. try:
  7977. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  7978. async with async_session() as db:
  7979. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  7980. logger.info("[AUTO-OFF-BG] Completed")
  7981. except Exception as e:
  7982. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  7983. async def _background_notifications(finish_photo_filename: str | None = None):
  7984. """Send print complete notifications in background."""
  7985. try:
  7986. logger.info(
  7987. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  7988. )
  7989. async with async_session() as db:
  7990. from backend.app.models.archive import PrintArchive
  7991. from backend.app.models.printer import Printer
  7992. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  7993. printer = result.scalar_one_or_none()
  7994. printer_name = printer.name if printer else f"Printer {printer_id}"
  7995. archive_data = None
  7996. if archive_id:
  7997. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  7998. archive = archive_result.scalar_one_or_none()
  7999. if archive:
  8000. # Actual elapsed time from started_at/completed_at when both are
  8001. # populated (every terminal status sets completed_at after #1198).
  8002. # Falls back to None so the notification path can decide whether to
  8003. # render the slicer estimate as a last resort.
  8004. actual_time_seconds = None
  8005. if archive.started_at and archive.completed_at:
  8006. elapsed = (archive.completed_at - archive.started_at).total_seconds()
  8007. if elapsed > 0:
  8008. actual_time_seconds = int(elapsed)
  8009. archive_data = {
  8010. "print_time_seconds": archive.print_time_seconds,
  8011. "actual_time_seconds": actual_time_seconds,
  8012. "actual_filament_grams": archive.filament_used_grams,
  8013. "failure_reason": archive.failure_reason,
  8014. "created_by_id": archive.created_by_id,
  8015. }
  8016. # Scale filament usage for partial prints
  8017. if print_status != "completed" and archive.filament_used_grams:
  8018. progress = data.get("progress") or 0
  8019. scale = _partial_progress_scale(progress)
  8020. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  8021. archive_data["progress"] = progress
  8022. # Pass per-slot data from archive.extra_data
  8023. if archive.extra_data and archive.extra_data.get("filament_slots"):
  8024. slots = archive.extra_data["filament_slots"]
  8025. if print_status != "completed":
  8026. scale = _partial_progress_scale(data.get("progress"))
  8027. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  8028. archive_data["filament_slots"] = slots
  8029. # Scope project-summed totals down to the plate that was
  8030. # actually printed — see _scope_notification_archive_data_to_plate
  8031. # for the why (#1785).
  8032. archive_data = _scope_notification_archive_data_to_plate(
  8033. archive_data,
  8034. archive.file_path,
  8035. notify_plate_id,
  8036. print_status,
  8037. data.get("progress"),
  8038. app_settings.base_dir,
  8039. )
  8040. # Enrich filament_grams from usage_results when archive has no 3MF data
  8041. if not archive_data.get("actual_filament_grams") and usage_results:
  8042. total_from_usage = sum(r.get("weight_used", 0) for r in usage_results)
  8043. if total_from_usage > 0:
  8044. archive_data["actual_filament_grams"] = round(total_from_usage, 1)
  8045. # Pass usage tracker results for AMS slot info in notifications
  8046. if usage_results:
  8047. archive_data["usage_results"] = usage_results
  8048. # Add finish photo URL and image bytes if available
  8049. if finish_photo_filename:
  8050. photo_url, photo_bytes = await _finish_photo_for_notification(
  8051. db, archive, archive_id, finish_photo_filename
  8052. )
  8053. if photo_url:
  8054. archive_data["finish_photo_url"] = photo_url
  8055. if photo_bytes:
  8056. archive_data["image_data"] = photo_bytes
  8057. if not await _kill_switch_notification_already_sent(kill_switch_notification_task):
  8058. await notification_service.on_print_complete(
  8059. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  8060. )
  8061. else:
  8062. logger.info("[NOTIFY-BG] Skipped duplicate kill-switch provider notification")
  8063. # Post-print outcome confirmation (#1898). Runs in this
  8064. # background task so the finish photo fetched above rides
  8065. # along with the prompt.
  8066. if print_status == "completed" and archive_id:
  8067. await _dispatch_outcome_confirmation_safely(
  8068. db, printer_id, printer_name, data, archive_id, archive_data
  8069. )
  8070. # Send user-specific email notification
  8071. if archive_data:
  8072. created_by_id = archive_data.get("created_by_id")
  8073. raw_filename = data.get("subtask_name") or data.get("filename", "Unknown")
  8074. await _dispatch_user_print_email(
  8075. print_status,
  8076. created_by_id,
  8077. printer_name,
  8078. raw_filename,
  8079. db,
  8080. image_data=archive_data.get("image_data"),
  8081. finish_photo_url=archive_data.get("finish_photo_url"),
  8082. )
  8083. logger.info("[NOTIFY-BG] Completed")
  8084. except Exception as e:
  8085. logger.error("[NOTIFY-BG] Failed: %s", e, exc_info=True)
  8086. async def _background_maintenance_check():
  8087. """Check for maintenance due in background."""
  8088. if print_status != "completed":
  8089. return
  8090. try:
  8091. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  8092. async with async_session() as db:
  8093. from backend.app.models.printer import Printer
  8094. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  8095. printer = result.scalar_one_or_none()
  8096. printer_name = printer.name if printer else f"Printer {printer_id}"
  8097. await ensure_default_types(db)
  8098. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  8099. attention = [
  8100. item for item in overview.maintenance_items if item.enabled and (item.is_due or item.is_warning)
  8101. ]
  8102. items_needing_attention = [
  8103. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  8104. for item in attention
  8105. ]
  8106. if items_needing_attention:
  8107. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  8108. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  8109. # MQTT relay - publish maintenance alerts
  8110. for item in attention:
  8111. current_value, threshold, unit = maintenance_alert_values(item)
  8112. try:
  8113. await mqtt_relay.on_maintenance_alert(
  8114. printer_id=printer_id,
  8115. printer_name=printer_name,
  8116. maintenance_type=item.maintenance_type_name,
  8117. current_value=current_value,
  8118. threshold=threshold,
  8119. unit=unit,
  8120. )
  8121. except Exception:
  8122. pass # Don't fail if MQTT fails
  8123. else:
  8124. logger.info("[MAINT-BG] Completed (no items need attention)")
  8125. except Exception as e:
  8126. logger.warning("[MAINT-BG] Failed: %s", e)
  8127. spawn_background_task(_background_smart_plug(), name="background-smart-plug")
  8128. spawn_background_task(_background_maintenance_check(), name="background-maintenance-check")
  8129. # Notification task waits for photo capture to complete first (with timeout).
  8130. # When a timelapse was recording, photo sourcing polls the per-print
  8131. # timelapse for up to 60s (#1397) — extend the budget so the notification
  8132. # carries the correct bed-up photo instead of falling through to the
  8133. # live-cam grab. Adds ~30s of notification latency at worst on slow links.
  8134. #
  8135. # #2547: both budgets now have to cover a plate restore as well.
  8136. #
  8137. # Without timelapse, the wait is on the moment producer, which raises the
  8138. # plate before its grab — so this has to outlast that producer's own budget.
  8139. #
  8140. # With timelapse, the capture polls up to
  8141. # `_FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS` for the video and only then
  8142. # falls back to a live grab, which is the case that raises the plate. At the
  8143. # old flat 75s that fallback was guaranteed to be cut off mid-settle, so the
  8144. # restore would have moved the plate for a photo nobody waited for.
  8145. photo_wait_timeout = (
  8146. _FINISH_PHOTO_TIMELAPSE_POLL_TIMEOUT_SECONDS + _FINISH_PHOTO_PRODUCER_WAIT_SECONDS
  8147. if data.get("timelapse_was_active")
  8148. else _FINISH_PHOTO_PRODUCER_WAIT_SECONDS + 15
  8149. )
  8150. async def _photo_then_notify():
  8151. """Wait for photo capture, then send notification with photo URL."""
  8152. finish_photo = None
  8153. try:
  8154. finish_photo = await asyncio.wait_for(photo_task, timeout=photo_wait_timeout)
  8155. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  8156. except TimeoutError:
  8157. logger.warning(
  8158. "[PHOTO-NOTIFY] Photo capture timed out after %ss, sending notification without photo",
  8159. photo_wait_timeout,
  8160. )
  8161. except Exception as e:
  8162. logger.warning("[PHOTO-NOTIFY] Photo task failed: %s", e)
  8163. try:
  8164. await _background_notifications(finish_photo)
  8165. except Exception as e:
  8166. logger.error("[PHOTO-NOTIFY] Notification sending failed: %s", e, exc_info=True)
  8167. spawn_background_task(_photo_then_notify(), name="photo-then-notify")
  8168. # Stitch external camera layer timelapse if session was active
  8169. print_status = data.get("status", "completed")
  8170. async def _background_layer_timelapse():
  8171. """Stitch layer timelapse and attach to archive."""
  8172. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  8173. try:
  8174. if print_status == "completed":
  8175. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  8176. timelapse_path = await tl_complete(printer_id)
  8177. if timelapse_path and archive_id:
  8178. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  8179. async with async_session() as db:
  8180. service = ArchiveService(db)
  8181. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  8182. await service.attach_timelapse(
  8183. archive_id, timelapse_data, "layer_timelapse.mp4", plate_id=notify_plate_id
  8184. )
  8185. # Clean up the temp file
  8186. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  8187. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  8188. elif timelapse_path:
  8189. # Timelapse created but no archive - just clean up
  8190. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  8191. else:
  8192. # Print failed or cancelled - cancel timelapse session
  8193. cancel_session(printer_id)
  8194. logger.info(
  8195. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  8196. )
  8197. except Exception as e:
  8198. logger.warning("[LAYER-TL] Failed: %s", e)
  8199. # Try to cancel session on error
  8200. try:
  8201. cancel_session(printer_id)
  8202. except Exception:
  8203. pass # Best-effort timelapse session cancellation on error
  8204. spawn_background_task(_background_layer_timelapse(), name="background-layer-timelapse")
  8205. log_timing("All background tasks scheduled")
  8206. # Auto-scan for timelapse if recording was active during the print
  8207. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  8208. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  8209. # Schedule timelapse scan as background task with retries
  8210. # The printer needs time to encode the video after print completion
  8211. baseline = _timelapse_baselines.pop(printer_id, None)
  8212. spawn_background_task(
  8213. _scan_for_timelapse_with_retries(archive_id, baseline, plate_id=notify_plate_id),
  8214. name=f"scan-timelapse-{archive_id}",
  8215. )
  8216. log_timing("Timelapse scan scheduled")
  8217. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  8218. # AMS sensor history recording
  8219. _ams_history_task: asyncio.Task | None = None
  8220. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  8221. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  8222. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  8223. # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  8224. _ams_alarm_cooldown: dict[str, datetime] = {}
  8225. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  8226. # (printer_id, ams_id) already reported as sending the drop index and no
  8227. # percentage. Logged once each so a supported printer that turns out to do this
  8228. # shows up in a support bundle rather than as a user wondering where the
  8229. # humidity reading went -- see the note at the read site below (#3140).
  8230. _ams_index_only_logged: set[tuple[int, int]] = set()
  8231. def _resolve_temp_alarm_threshold(fair_threshold: float, raw_alarm_value: str | None) -> float:
  8232. """Temperature at which the AMS alarm fires, falling back to the display band.
  8233. ``ams_temp_fair`` decides when the AMS card turns amber. It used to decide
  8234. when a notification was sent as well, which is why a room above it made the
  8235. alarm fire once an hour for as long as the weather lasted -- and the only way
  8236. to stop that was to raise the display band and lose the colour that says the
  8237. unit is warm (#2905).
  8238. Unset resolves to the fair threshold, so an install that never sets one is
  8239. unchanged. Settings storage stringifies ``None`` to the literal ``"None"``,
  8240. so that arrives here as a string and is handled by the same branch as any
  8241. other unparseable value -- there is no separate sentinel to keep in sync.
  8242. A non-positive value is refused rather than honoured: zero would alarm
  8243. permanently, and it is far more likely to be a cleared field than a
  8244. deliberate choice.
  8245. """
  8246. if raw_alarm_value is None:
  8247. return fair_threshold
  8248. try:
  8249. value = float(raw_alarm_value)
  8250. except (TypeError, ValueError):
  8251. return fair_threshold
  8252. if not math.isfinite(value) or value <= 0:
  8253. return fair_threshold
  8254. return value
  8255. # Per-AMS "drying was live at" latch that suppresses the high-temperature alarm
  8256. # through a cycle and the cool-down after it (#1802). Stored in the settings
  8257. # table rather than alongside _ams_alarm_cooldown above, because a restart
  8258. # partway through a cool-down would otherwise resume alarming about heat the
  8259. # user asked for — the same internal-timestamp-row pattern as
  8260. # support.py's debug_logging_enabled_at.
  8261. AMS_DRYING_LATCH_KEY = "ams_drying_alarm_latch"
  8262. # Upper bound on that suppression. The latch normally clears as soon as the unit
  8263. # reads at or below the threshold; see utils.ams_drying for why this cap only
  8264. # matters when it never does.
  8265. AMS_DRYING_GRACE_MINUTES = 120
  8266. async def _load_ams_drying_latch(db) -> dict[str, datetime]:
  8267. """Read the persisted per-AMS drying latch, dropping entries out of window.
  8268. Anything older than the grace cap would expire on its next visit anyway, so
  8269. discarding it here costs nothing and stops rows for deleted printers from
  8270. accumulating.
  8271. Stamps ahead of now get two defences, because a box whose clock jumps
  8272. backwards (a Pi with no RTC coming up before NTP) writes them: wildly future
  8273. ones are discarded outright, and the rest are clamped to now. Without the
  8274. clamp the cap would measure from a moment that has not happened yet and hold
  8275. the alarm quiet for the skew on top of the cap. One unnecessary notification
  8276. after a clock jump is a far better failure than an alarm silently disabled
  8277. for hours.
  8278. """
  8279. from backend.app.models.settings import Settings
  8280. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8281. setting = result.scalar_one_or_none()
  8282. if not setting or not setting.value:
  8283. return {}
  8284. try:
  8285. raw = json.loads(setting.value)
  8286. except (ValueError, TypeError):
  8287. return {} # Corrupted row → no latch, alarms behave as they did before
  8288. if not isinstance(raw, dict):
  8289. return {}
  8290. now = datetime.now(timezone.utc)
  8291. window = timedelta(minutes=AMS_DRYING_GRACE_MINUTES)
  8292. latch: dict[str, datetime] = {}
  8293. for key, value in raw.items():
  8294. try:
  8295. stamp = datetime.fromisoformat(str(value))
  8296. except (ValueError, TypeError):
  8297. continue
  8298. if stamp.tzinfo is None:
  8299. stamp = stamp.replace(tzinfo=timezone.utc)
  8300. if not (now - window <= stamp <= now + window):
  8301. continue
  8302. # Nothing may sit in the future: suppression is measured as now minus
  8303. # the stamp, so a stamp ahead of now would extend it by the skew on top
  8304. # of the cap. Clamping the survivors keeps the cap an actual cap.
  8305. latch[str(key)] = min(stamp, now)
  8306. return latch
  8307. async def _save_ams_drying_latch(db, latch: dict[str, datetime]) -> None:
  8308. """Persist the latch, writing only when it actually changed.
  8309. Adds the session change but does not commit — the caller's own commit
  8310. carries it, so the latch lands in the same transaction as the sensor rows
  8311. that produced it.
  8312. """
  8313. from backend.app.models.settings import Settings
  8314. payload = json.dumps({key: stamp.isoformat() for key, stamp in sorted(latch.items())})
  8315. result = await db.execute(select(Settings).where(Settings.key == AMS_DRYING_LATCH_KEY))
  8316. setting = result.scalar_one_or_none()
  8317. if setting is None:
  8318. # Don't create the row on installs that never dry anything.
  8319. if payload != "{}":
  8320. db.add(Settings(key=AMS_DRYING_LATCH_KEY, value=payload))
  8321. elif setting.value != payload:
  8322. setting.value = payload
  8323. def _ams_has_filament(ams_data: dict) -> bool:
  8324. """True if this AMS unit has at least one tray slot holding filament.
  8325. Bambu firmware reports loaded slots via `tray_exist_bits`, a per-AMS hex
  8326. bitmap (one bit per tray slot — bit set = spool present). Empty AMS units
  8327. still report sensor readings, but those readings are ambient and not
  8328. actionable: no filament to dry, no humidity to push down. #1619 — gate
  8329. humidity/temperature alarms on this check so empty units don't generate
  8330. hourly noise. Sensor history still records regardless so the UI charts
  8331. stay continuous.
  8332. Fallback path inspects the `tray` array's `tray_type` fields for setups
  8333. where `tray_exist_bits` is missing (some early-connection pushall shapes).
  8334. """
  8335. bits = ams_data.get("tray_exist_bits")
  8336. if isinstance(bits, str) and bits.strip():
  8337. try:
  8338. return int(bits, 16) > 0
  8339. except ValueError:
  8340. pass
  8341. trays = ams_data.get("tray")
  8342. if isinstance(trays, list):
  8343. return any(
  8344. isinstance(t, dict) and isinstance(t.get("tray_type"), str) and t["tray_type"].strip() for t in trays
  8345. )
  8346. return False
  8347. async def record_ams_history():
  8348. """Background task to record AMS humidity and temperature data."""
  8349. logger = logging.getLogger(__name__)
  8350. # Wait a short time for MQTT connections to establish on startup
  8351. await asyncio.sleep(10)
  8352. while True:
  8353. try:
  8354. from backend.app.models.ams_history import AMSSensorHistory
  8355. from backend.app.models.printer import Printer
  8356. from backend.app.models.settings import Settings
  8357. async with async_session() as db:
  8358. # Get all active printers
  8359. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8360. printers = result.scalars().all()
  8361. # Get alarm thresholds from settings
  8362. humidity_threshold = 60.0 # Default: fair threshold
  8363. temp_fair_threshold = 35.0 # Display band default (ams_temp_fair)
  8364. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  8365. setting = result.scalar_one_or_none()
  8366. if setting:
  8367. try:
  8368. humidity_threshold = float(setting.value)
  8369. except (ValueError, TypeError):
  8370. pass # Keep default threshold if stored value is invalid
  8371. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  8372. setting = result.scalar_one_or_none()
  8373. if setting:
  8374. try:
  8375. temp_fair_threshold = float(setting.value)
  8376. except (ValueError, TypeError):
  8377. pass # Keep default threshold if stored value is invalid
  8378. # The alarm gets its own threshold, seeded from the resolved fair
  8379. # value so an install that has never set one behaves exactly as
  8380. # it did before (#2905). ams_temp_fair decides when the card turns
  8381. # amber; 35 C is a reasonable place to change a colour and not a
  8382. # reasonable place to page someone. A room above it makes the
  8383. # alarm fire once an hour for as long as the weather lasts, and
  8384. # the only way to stop it was to raise the display band and lose
  8385. # the colour that says the unit is warm.
  8386. #
  8387. # An unset value is stored as the literal "None", which the except
  8388. # below swallows the same way it swallows garbage -- so the
  8389. # fallback costs nothing and needs no sentinel of its own.
  8390. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_alarm"))
  8391. setting = result.scalar_one_or_none()
  8392. temp_alarm_threshold = _resolve_temp_alarm_threshold(
  8393. temp_fair_threshold, setting.value if setting else None
  8394. )
  8395. # Per-filament humidity threshold overrides (#1605) — resolved
  8396. # per-AMS below from the loaded tray types. Reuses the same
  8397. # resolver as the auto-drying scheduler so behavior stays in
  8398. # lockstep across both consumers.
  8399. from backend.app.services.print_scheduler import PrintScheduler
  8400. per_type_humidity_thresholds: dict[str, int] = {}
  8401. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  8402. setting = result.scalar_one_or_none()
  8403. if setting and setting.value:
  8404. try:
  8405. raw = json.loads(setting.value)
  8406. if isinstance(raw, dict):
  8407. for k, v in raw.items():
  8408. try:
  8409. per_type_humidity_thresholds[str(k).upper() if k != "default" else "default"] = int(
  8410. v
  8411. )
  8412. except (TypeError, ValueError):
  8413. continue
  8414. except (ValueError, TypeError):
  8415. pass # Invalid JSON → no overrides, fall through to global threshold
  8416. # Per-AMS drying latch (#1802), loaded once per pass and written
  8417. # back below only if a unit changed it.
  8418. drying_latch = await _load_ams_drying_latch(db)
  8419. drying_latch_before = dict(drying_latch)
  8420. recorded_count = 0
  8421. for printer in printers:
  8422. # Get current state from printer manager
  8423. state = printer_manager.get_status(printer.id)
  8424. if not state or not state.connected or not state.raw_data:
  8425. continue # Skip disconnected printers - don't use stale data
  8426. raw_data = state.raw_data
  8427. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  8428. continue
  8429. # Record data for each AMS unit
  8430. for ams_data in raw_data["ams"]:
  8431. ams_id = int(ams_data.get("id", 0))
  8432. # Percentage only. The 1-5 index is inverted, so
  8433. # charting it as a percentage drew the wettest units as
  8434. # the driest (#3140); a unit that reports no percentage
  8435. # leaves a gap in the chart instead. See
  8436. # utils/ams_humidity.
  8437. humidity = ams_humidity_percent(ams_data)
  8438. # No supported printer is known to send the index
  8439. # alone -- the report came from unsupported firmware,
  8440. # and no install has been seen using the old fallback.
  8441. # "Known" is doing work there, so say so once per unit:
  8442. # the alternative is a silent blank card.
  8443. if humidity is None and ams_data.get("humidity") is not None:
  8444. unit_key = (printer.id, ams_id)
  8445. if unit_key not in _ams_index_only_logged:
  8446. _ams_index_only_logged.add(unit_key)
  8447. logger.info(
  8448. "[%s] AMS %d reports the 1-5 humidity index but no usable humidity_raw "
  8449. "percentage. The index is inverted and is not shown as a percentage "
  8450. "(#3140), so this unit has no humidity reading, chart or alarm. "
  8451. "Please report this with the printer and AMS firmware versions.",
  8452. printer.name,
  8453. ams_id,
  8454. )
  8455. # Get temperature
  8456. temperature = None
  8457. temp_str = ams_data.get("temp")
  8458. if temp_str is not None:
  8459. try:
  8460. temperature = float(temp_str)
  8461. except (ValueError, TypeError):
  8462. pass # Skip unparseable temperature value
  8463. # Skip if no data
  8464. if humidity is None and temperature is None:
  8465. continue
  8466. # Record the data point
  8467. history = AMSSensorHistory(
  8468. printer_id=printer.id,
  8469. ams_id=ams_id,
  8470. humidity=humidity,
  8471. # Both columns hold the same reading now that the
  8472. # index can no longer reach ``humidity``. Writing it
  8473. # through the same value also stops a genuine 0%
  8474. # from being stored as NULL, which the old truthiness
  8475. # test did.
  8476. humidity_raw=humidity,
  8477. temperature=temperature,
  8478. )
  8479. db.add(history)
  8480. recorded_count += 1
  8481. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  8482. is_ams_ht = ams_id >= 128
  8483. if is_ams_ht:
  8484. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  8485. else:
  8486. ams_label = f"AMS-{chr(65 + ams_id)}"
  8487. # Skip alarm dispatch for empty AMS units — humidity /
  8488. # temperature readings are ambient with no filament to
  8489. # protect, and the hourly notification just becomes
  8490. # noise. Sensor history was already recorded above so
  8491. # the UI charts stay continuous (#1619). Per-AMS check
  8492. # so a multi-AMS setup with one loaded + one empty
  8493. # still alarms on the loaded unit.
  8494. if not _ams_has_filament(ams_data):
  8495. continue
  8496. # Resolve per-filament humidity threshold for this AMS
  8497. # unit (#1605). Falls back to the global ams_humidity_fair
  8498. # when no per-type overrides are configured.
  8499. trays = ams_data.get("tray", []) or []
  8500. effective_humidity_threshold = float(
  8501. PrintScheduler.resolve_humidity_threshold(
  8502. trays, per_type_humidity_thresholds, int(humidity_threshold)
  8503. )
  8504. )
  8505. # Check humidity alarm (only if above threshold)
  8506. if humidity is not None and humidity > effective_humidity_threshold:
  8507. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  8508. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8509. now = datetime.now(timezone.utc)
  8510. if (
  8511. last_alarm is None
  8512. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8513. ):
  8514. _ams_alarm_cooldown[cooldown_key] = now
  8515. logger.info(
  8516. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {effective_humidity_threshold}%"
  8517. )
  8518. try:
  8519. # Call different notification method based on AMS type
  8520. if is_ams_ht:
  8521. await notification_service.on_ams_ht_humidity_high(
  8522. printer.id,
  8523. printer.name,
  8524. ams_label,
  8525. humidity,
  8526. effective_humidity_threshold,
  8527. db,
  8528. )
  8529. else:
  8530. await notification_service.on_ams_humidity_high(
  8531. printer.id,
  8532. printer.name,
  8533. ams_label,
  8534. humidity,
  8535. effective_humidity_threshold,
  8536. db,
  8537. )
  8538. except Exception as e:
  8539. logger.warning("Failed to send humidity alarm: %s", e)
  8540. # A drying cycle heats the unit far past ams_temp_fair on
  8541. # purpose — 45 C for PLA, 65 C for PETG, 85 C on an
  8542. # AMS-HT, against a 35 C default — so the alarm fired
  8543. # once an hour for the whole cycle and kept firing while
  8544. # the unit cooled back down (#1802). Latch on the
  8545. # firmware's own drying state and hold until the reading
  8546. # returns to normal. Humidity is deliberately left alone:
  8547. # it falls during drying, which is the whole point.
  8548. latch_key = f"{printer.id}:{ams_id}"
  8549. # The latch releases at `threshold`, so it takes the alarm
  8550. # number too. Handing it the display band would strand the
  8551. # latch on any unit that settles back above it -- a room
  8552. # where the AMS rests at 37.7 C never returns under a 35 C
  8553. # band, so the latch could only expire on the grace cap
  8554. # rather than releasing when the unit had actually cooled.
  8555. suppress_temp_alarm, new_latch = temperature_alarm_suppressed(
  8556. drying_active=is_drying_active(ams_data),
  8557. temperature=temperature,
  8558. threshold=temp_alarm_threshold,
  8559. latched_at=drying_latch.get(latch_key),
  8560. now=datetime.now(timezone.utc),
  8561. grace_minutes=AMS_DRYING_GRACE_MINUTES,
  8562. )
  8563. if new_latch is None:
  8564. drying_latch.pop(latch_key, None)
  8565. else:
  8566. drying_latch[latch_key] = new_latch
  8567. # Check temperature alarm (only if above threshold)
  8568. if temperature is not None and temperature > temp_alarm_threshold and not suppress_temp_alarm:
  8569. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  8570. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  8571. now = datetime.now(timezone.utc)
  8572. if (
  8573. last_alarm is None
  8574. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  8575. ):
  8576. _ams_alarm_cooldown[cooldown_key] = now
  8577. logger.info(
  8578. f"Sending temperature alarm for {printer.name} {ams_label}: "
  8579. f"{temperature}°C > {temp_alarm_threshold}°C"
  8580. )
  8581. try:
  8582. # Call different notification method based on AMS type
  8583. if is_ams_ht:
  8584. # The reported threshold has to be the one
  8585. # that fired, or the message says "> 35 °C"
  8586. # while firing at 45.
  8587. await notification_service.on_ams_ht_temperature_high(
  8588. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8589. )
  8590. else:
  8591. await notification_service.on_ams_temperature_high(
  8592. printer.id, printer.name, ams_label, temperature, temp_alarm_threshold, db
  8593. )
  8594. except Exception as e:
  8595. logger.warning("Failed to send temperature alarm: %s", e)
  8596. if drying_latch != drying_latch_before:
  8597. await _save_ams_drying_latch(db, drying_latch)
  8598. await db.commit()
  8599. if recorded_count > 0:
  8600. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  8601. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  8602. global _ams_cleanup_counter
  8603. _ams_cleanup_counter += 1
  8604. if _ams_cleanup_counter >= 288:
  8605. _ams_cleanup_counter = 0
  8606. # Get retention days from settings
  8607. from backend.app.models.settings import Settings
  8608. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  8609. setting = result.scalar_one_or_none()
  8610. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  8611. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8612. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  8613. await db.commit()
  8614. if result.rowcount > 0:
  8615. logger.info(
  8616. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  8617. )
  8618. # Wait until next recording interval
  8619. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  8620. except asyncio.CancelledError:
  8621. break
  8622. except Exception as e:
  8623. logger.warning("AMS history recording failed: %s", e)
  8624. await asyncio.sleep(60) # Wait a bit before retrying
  8625. def start_ams_history_recording():
  8626. """Start the AMS history recording background task."""
  8627. global _ams_history_task
  8628. if _ams_history_task is None:
  8629. _ams_history_task = asyncio.create_task(record_ams_history())
  8630. logging.getLogger(__name__).info("AMS history recording started")
  8631. def stop_ams_history_recording():
  8632. """Stop the AMS history recording background task."""
  8633. global _ams_history_task
  8634. if _ams_history_task:
  8635. _ams_history_task.cancel()
  8636. _ams_history_task = None
  8637. logging.getLogger(__name__).info("AMS history recording stopped")
  8638. # Printer sensor history recording (nozzle / bed / chamber)
  8639. _printer_sensor_history_task: asyncio.Task | None = None
  8640. PRINTER_SENSOR_HISTORY_INTERVAL = 60 # Record every minute — heaters move faster than AMS humidity
  8641. PRINTER_SENSOR_HISTORY_RETENTION_DAYS = 30
  8642. _printer_sensor_cleanup_counter = 0
  8643. # Sensor kinds tracked in state.temperatures — these are the normalised keys the
  8644. # MQTT parser writes, so we don't need to handle per-model field aliases here
  8645. # (nozzle_temper / left_nozzle_temper / right_nozzle_temper / chamber_temper
  8646. # are all collapsed by services/bambu_mqtt.py before they reach this loop).
  8647. _SENSOR_KINDS = ("nozzle", "nozzle_2", "bed", "chamber")
  8648. _SENSOR_TARGET_KEYS = {
  8649. "nozzle": "nozzle_target",
  8650. "nozzle_2": "nozzle_2_target",
  8651. "bed": "bed_target",
  8652. "chamber": "chamber_target",
  8653. }
  8654. async def record_printer_sensor_history():
  8655. """Background task to record nozzle / bed / chamber readings.
  8656. Pulls from `state.temperatures` (already normalised across all printer
  8657. models by the MQTT parser) rather than re-parsing raw_data, so we get
  8658. free coverage of dual-nozzle H2D, sensor-only X1C chamber, etc.
  8659. """
  8660. logger = logging.getLogger(__name__)
  8661. await asyncio.sleep(10)
  8662. while True:
  8663. try:
  8664. from backend.app.models.printer import Printer
  8665. from backend.app.models.printer_sensor_history import PrinterSensorHistory
  8666. from backend.app.models.settings import Settings
  8667. async with async_session() as db:
  8668. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  8669. printers = result.scalars().all()
  8670. recorded_count = 0
  8671. for printer in printers:
  8672. state = printer_manager.get_status(printer.id)
  8673. if not state or not state.connected:
  8674. continue
  8675. temps = getattr(state, "temperatures", None) or {}
  8676. if not isinstance(temps, dict):
  8677. continue
  8678. for kind in _SENSOR_KINDS:
  8679. if kind not in temps:
  8680. continue
  8681. try:
  8682. value = float(temps[kind])
  8683. except (ValueError, TypeError):
  8684. continue
  8685. target_raw = temps.get(_SENSOR_TARGET_KEYS[kind])
  8686. target_val: float | None = None
  8687. if target_raw is not None:
  8688. try:
  8689. target_val = float(target_raw)
  8690. except (ValueError, TypeError):
  8691. target_val = None
  8692. db.add(
  8693. PrinterSensorHistory(
  8694. printer_id=printer.id,
  8695. sensor_kind=kind,
  8696. value=value,
  8697. target=target_val,
  8698. )
  8699. )
  8700. recorded_count += 1
  8701. await db.commit()
  8702. if recorded_count > 0:
  8703. logger.debug("Recorded %s printer sensor history entries", recorded_count)
  8704. # Periodic cleanup — once every ~24h at this interval.
  8705. global _printer_sensor_cleanup_counter
  8706. _printer_sensor_cleanup_counter += 1
  8707. cleanup_every = max(1, (24 * 60 * 60) // PRINTER_SENSOR_HISTORY_INTERVAL)
  8708. if _printer_sensor_cleanup_counter >= cleanup_every:
  8709. _printer_sensor_cleanup_counter = 0
  8710. result = await db.execute(
  8711. select(Settings).where(Settings.key == "printer_sensor_history_retention_days")
  8712. )
  8713. setting = result.scalar_one_or_none()
  8714. retention_days = int(setting.value) if setting else PRINTER_SENSOR_HISTORY_RETENTION_DAYS
  8715. cutoff = utcnow_naive() - timedelta(days=retention_days)
  8716. cleanup = await db.execute(
  8717. delete(PrinterSensorHistory).where(PrinterSensorHistory.recorded_at < cutoff)
  8718. )
  8719. await db.commit()
  8720. if cleanup.rowcount > 0:
  8721. logger.info(
  8722. "Cleaned up %s old printer sensor history entries (older than %s days)",
  8723. cleanup.rowcount,
  8724. retention_days,
  8725. )
  8726. await asyncio.sleep(PRINTER_SENSOR_HISTORY_INTERVAL)
  8727. except asyncio.CancelledError:
  8728. break
  8729. except Exception as e:
  8730. logger.warning("Printer sensor history recording failed: %s", e)
  8731. await asyncio.sleep(60)
  8732. def start_printer_sensor_history_recording():
  8733. global _printer_sensor_history_task
  8734. if _printer_sensor_history_task is None:
  8735. _printer_sensor_history_task = asyncio.create_task(record_printer_sensor_history())
  8736. logging.getLogger(__name__).info("Printer sensor history recording started")
  8737. def stop_printer_sensor_history_recording():
  8738. global _printer_sensor_history_task
  8739. if _printer_sensor_history_task:
  8740. _printer_sensor_history_task.cancel()
  8741. _printer_sensor_history_task = None
  8742. logging.getLogger(__name__).info("Printer sensor history recording stopped")
  8743. # Printer runtime tracking
  8744. _runtime_tracking_task: asyncio.Task | None = None
  8745. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  8746. async def track_printer_runtime():
  8747. """Background task to track printer active runtime (RUNNING state only).
  8748. PAUSE is intentionally excluded — the runtime counter feeds hours-based
  8749. maintenance intervals (rod lubrication, belt checks, nozzle cleaning)
  8750. which track mechanical wear. Pause time has no motion and no wear, so
  8751. counting it inflates maintenance warnings (#1521).
  8752. """
  8753. logger = logging.getLogger(__name__)
  8754. # Wait for MQTT connections to establish on startup
  8755. await asyncio.sleep(15)
  8756. while True:
  8757. try:
  8758. from backend.app.models.printer import Printer
  8759. # Fetch printer IDs in a short-lived read-only session
  8760. async with async_session() as db:
  8761. result = await db.execute(
  8762. select(Printer.id, Printer.name, Printer.runtime_seconds, Printer.last_runtime_update).where(
  8763. Printer.is_active.is_(True)
  8764. )
  8765. )
  8766. printer_rows = result.all()
  8767. now = datetime.now(timezone.utc)
  8768. updated_count = 0
  8769. # Update each printer in its own short session to minimise write-lock
  8770. # hold time and avoid blocking critical commits like queue status
  8771. # updates (#897).
  8772. for pid, pname, runtime_secs, last_update in printer_rows:
  8773. state = printer_manager.get_status(pid)
  8774. if not state:
  8775. logger.debug("[%s] Runtime tracking: no state available", pname)
  8776. continue
  8777. if not state.connected:
  8778. logger.debug("[%s] Runtime tracking: not connected", pname)
  8779. continue
  8780. needs_commit = False
  8781. new_runtime = runtime_secs
  8782. new_last_update = last_update
  8783. if state.state == "RUNNING":
  8784. if last_update:
  8785. lu = last_update if last_update.tzinfo else last_update.replace(tzinfo=timezone.utc)
  8786. elapsed = (now - lu).total_seconds()
  8787. if elapsed > 0:
  8788. new_runtime = runtime_secs + int(elapsed)
  8789. updated_count += 1
  8790. needs_commit = True
  8791. logger.debug(
  8792. f"[{pname}] Runtime tracking: added {int(elapsed)}s, "
  8793. f"total={new_runtime}s ({new_runtime / 3600:.2f}h)"
  8794. )
  8795. else:
  8796. needs_commit = True
  8797. logger.debug("[%s] Runtime tracking: first active detection", pname)
  8798. new_last_update = now
  8799. else:
  8800. if last_update is not None:
  8801. logger.debug(f"[{pname}] Runtime tracking: state={state.state}, clearing last_runtime_update")
  8802. new_last_update = None
  8803. needs_commit = True
  8804. if needs_commit:
  8805. try:
  8806. async with async_session() as db:
  8807. result = await db.execute(select(Printer).where(Printer.id == pid))
  8808. printer = result.scalar_one_or_none()
  8809. if printer:
  8810. printer.runtime_seconds = new_runtime
  8811. printer.last_runtime_update = new_last_update
  8812. await db.commit()
  8813. except Exception as e:
  8814. logger.warning("[%s] Runtime tracking commit failed: %s", pname, e)
  8815. if updated_count > 0:
  8816. logger.debug("Updated runtime for %s printer(s)", updated_count)
  8817. except asyncio.CancelledError:
  8818. logger.info("Runtime tracking cancelled")
  8819. break
  8820. except Exception as e:
  8821. logger.warning("Runtime tracking failed: %s", e)
  8822. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  8823. def start_runtime_tracking():
  8824. """Start the printer runtime tracking background task."""
  8825. global _runtime_tracking_task
  8826. if _runtime_tracking_task is None:
  8827. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  8828. logging.getLogger(__name__).info("Printer runtime tracking started")
  8829. def stop_runtime_tracking():
  8830. """Stop the printer runtime tracking background task."""
  8831. global _runtime_tracking_task
  8832. if _runtime_tracking_task:
  8833. _runtime_tracking_task.cancel()
  8834. _runtime_tracking_task = None
  8835. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  8836. # SpoolBuddy device watchdog
  8837. _spoolbuddy_watchdog_task: asyncio.Task | None = None
  8838. SPOOLBUDDY_WATCHDOG_INTERVAL = 15
  8839. async def _spoolbuddy_watchdog_loop():
  8840. """Periodic check for SpoolBuddy devices that have gone offline."""
  8841. from backend.app.api.routes.spoolbuddy import spoolbuddy_watchdog
  8842. while True:
  8843. try:
  8844. await spoolbuddy_watchdog()
  8845. except asyncio.CancelledError:
  8846. break
  8847. except Exception as e:
  8848. logging.getLogger(__name__).warning("SpoolBuddy watchdog failed: %s", e)
  8849. await asyncio.sleep(SPOOLBUDDY_WATCHDOG_INTERVAL)
  8850. def start_spoolbuddy_watchdog():
  8851. global _spoolbuddy_watchdog_task
  8852. if _spoolbuddy_watchdog_task is None:
  8853. _spoolbuddy_watchdog_task = asyncio.create_task(_spoolbuddy_watchdog_loop())
  8854. logging.getLogger(__name__).info("SpoolBuddy watchdog started")
  8855. def stop_spoolbuddy_watchdog():
  8856. global _spoolbuddy_watchdog_task
  8857. if _spoolbuddy_watchdog_task:
  8858. _spoolbuddy_watchdog_task.cancel()
  8859. _spoolbuddy_watchdog_task = None
  8860. logging.getLogger(__name__).info("SpoolBuddy watchdog stopped")
  8861. # Dead-MQTT-session recovery
  8862. #
  8863. # check_staleness() covers the "connected but silent" half-broken session. It
  8864. # does nothing once ``state.connected`` is False, and paho's own auto-reconnect
  8865. # is the only thing left watching at that point. When paho stops making
  8866. # progress there is no backstop at all: the #2732 bundle has a P1S drop on a
  8867. # keep-alive timeout at 02:19 and not reconnect until 11:24 — nine hours
  8868. # offline with the UI open the whole time, recovered only when something
  8869. # happened to nudge it.
  8870. #
  8871. # This loop is that backstop. It only touches printers that had a working
  8872. # session and lost it, and only when the MQTT port still answers — a printer
  8873. # that is simply switched off is left to paho, since rebuilding a client
  8874. # against an unreachable host achieves nothing and would fill the log every
  8875. # night.
  8876. _connection_watchdog_task: asyncio.Task | None = None
  8877. CONNECTION_WATCHDOG_INTERVAL = 60
  8878. # How long a printer must have been silent before we stop trusting paho.
  8879. # Comfortably above STALE_TIMEOUT (60 s) and the max reconnect backoff (30 s),
  8880. # so a session that is recovering on its own is never interrupted.
  8881. CONNECTION_WATCHDOG_OFFLINE_GRACE = 300
  8882. # Per-printer floor between rebuild attempts.
  8883. CONNECTION_WATCHDOG_RETRY_INTERVAL = 300
  8884. _connection_watchdog_last_attempt: dict[int, float] = {}
  8885. async def _recover_dead_printer_sessions() -> int:
  8886. """Rebuild MQTT clients that have been offline too long to still be trying.
  8887. Returns the number of printers a rebuild was attempted for (for tests and
  8888. for the caller's logging). Never raises: one unreachable printer must not
  8889. stop the sweep for the rest of the farm.
  8890. """
  8891. logger = logging.getLogger(__name__)
  8892. from backend.app.services.printer_diagnostic import PORT_MQTT, check_port
  8893. now = time.monotonic()
  8894. recovered = 0
  8895. for printer_id, client in list(printer_manager._clients.items()):
  8896. try:
  8897. if client.state.connected:
  8898. _connection_watchdog_last_attempt.pop(printer_id, None)
  8899. continue
  8900. # Time since the last inbound message is the age of the last known
  8901. # good session — no extra bookkeeping needed, and it is the same
  8902. # clock is_stale() reads. 0 means this client has never had one:
  8903. # that is the initial-connect path, where paho retrying is the
  8904. # correct and only behaviour, so leave it be.
  8905. last_msg = client._last_message_time
  8906. if not last_msg:
  8907. continue
  8908. offline_for = time.time() - last_msg
  8909. if offline_for < CONNECTION_WATCHDOG_OFFLINE_GRACE:
  8910. continue
  8911. last_attempt = _connection_watchdog_last_attempt.get(printer_id)
  8912. if last_attempt is not None and now - last_attempt < CONNECTION_WATCHDOG_RETRY_INTERVAL:
  8913. continue
  8914. if not await check_port(client.ip_address, PORT_MQTT):
  8915. # Switched off, unplugged, or off the network. Paho's retry is
  8916. # the right handler; say so at debug level and move on.
  8917. logger.debug(
  8918. "[#2732] Printer %s offline for %.0fs and its MQTT port is not answering "
  8919. "— leaving the reconnect to paho",
  8920. printer_id,
  8921. offline_for,
  8922. )
  8923. _connection_watchdog_last_attempt[printer_id] = now
  8924. continue
  8925. _connection_watchdog_last_attempt[printer_id] = now
  8926. recovered += 1
  8927. logger.warning(
  8928. "[#2732] Printer %s has been offline for %.0fs but answers on MQTT port %d — "
  8929. "rebuilding the client with a fresh session (last connect error: %s)",
  8930. printer_id,
  8931. offline_for,
  8932. PORT_MQTT,
  8933. client.last_connect_error or "none recorded",
  8934. )
  8935. # Async context, so this takes the hard-reset path: fresh client_id,
  8936. # paho's QoS 1 queue dropped. That matters — a project_file left
  8937. # unacked on the dead session would otherwise replay into the new
  8938. # one and trip 0500_4003 on the printer (#1136).
  8939. client.force_reconnect_stale_session(f"offline for {offline_for:.0f}s, port still answering")
  8940. except Exception as e:
  8941. logger.warning("[#2732] Connection watchdog failed for printer %s: %s", printer_id, e)
  8942. return recovered
  8943. async def _connection_watchdog_loop():
  8944. logger = logging.getLogger(__name__)
  8945. # Let the initial connects settle before judging anyone offline.
  8946. await asyncio.sleep(CONNECTION_WATCHDOG_OFFLINE_GRACE)
  8947. while True:
  8948. try:
  8949. await _recover_dead_printer_sessions()
  8950. except asyncio.CancelledError:
  8951. break
  8952. except Exception as e:
  8953. logger.warning("Connection watchdog sweep failed: %s", e)
  8954. await asyncio.sleep(CONNECTION_WATCHDOG_INTERVAL)
  8955. def start_connection_watchdog():
  8956. global _connection_watchdog_task
  8957. if _connection_watchdog_task is None:
  8958. _connection_watchdog_task = asyncio.create_task(_connection_watchdog_loop())
  8959. logging.getLogger(__name__).info("Printer connection watchdog started")
  8960. def stop_connection_watchdog():
  8961. global _connection_watchdog_task
  8962. if _connection_watchdog_task:
  8963. _connection_watchdog_task.cancel()
  8964. _connection_watchdog_task = None
  8965. _connection_watchdog_last_attempt.clear()
  8966. logging.getLogger(__name__).info("Printer connection watchdog stopped")
  8967. # Camera stream orphan cleanup
  8968. _camera_cleanup_task: asyncio.Task | None = None
  8969. CAMERA_CLEANUP_INTERVAL = 60
  8970. async def _camera_cleanup_loop():
  8971. """Periodically clean up orphaned ffmpeg processes."""
  8972. from backend.app.api.routes.camera import cleanup_orphaned_streams
  8973. while True:
  8974. try:
  8975. await cleanup_orphaned_streams()
  8976. except asyncio.CancelledError:
  8977. break
  8978. except Exception as e:
  8979. logging.getLogger(__name__).warning("Camera stream cleanup failed: %s", e)
  8980. await asyncio.sleep(CAMERA_CLEANUP_INTERVAL)
  8981. def start_camera_cleanup():
  8982. global _camera_cleanup_task
  8983. if _camera_cleanup_task is None:
  8984. _camera_cleanup_task = asyncio.create_task(_camera_cleanup_loop())
  8985. logging.getLogger(__name__).info("Camera stream cleanup started")
  8986. def stop_camera_cleanup():
  8987. global _camera_cleanup_task
  8988. if _camera_cleanup_task:
  8989. _camera_cleanup_task.cancel()
  8990. _camera_cleanup_task = None
  8991. logging.getLogger(__name__).info("Camera stream cleanup stopped")
  8992. # ---------------------------------------------------------------------------
  8993. # Expected-print TTL eviction
  8994. # ---------------------------------------------------------------------------
  8995. def _evict_stale_expected_prints() -> None:
  8996. """Remove entries from _expected_prints / _expected_print_creators that are
  8997. older than _EXPECTED_PRINT_TTL_SECONDS.
  8998. This prevents unbounded growth when a print is registered (via
  8999. register_expected_print) but on_print_start never fires — e.g. because the
  9000. printer disconnects, the app restarts, or the print is started directly from
  9001. the printer panel without going through the queue.
  9002. """
  9003. # Use monotonic time so the TTL is unaffected by system clock adjustments
  9004. # (e.g. NTP sync, DST changes).
  9005. cutoff = time.monotonic() - _EXPECTED_PRINT_TTL_SECONDS
  9006. stale_keys = [k for k, t in _expected_print_registered_at.items() if t < cutoff]
  9007. if not stale_keys:
  9008. return
  9009. evicted_archive_ids: set[int] = set()
  9010. for key in stale_keys:
  9011. archive_id = _expected_prints.pop(key, None)
  9012. if archive_id is not None:
  9013. evicted_archive_ids.add(archive_id)
  9014. _expected_print_creators.pop(key, None)
  9015. _expected_print_registered_at.pop(key, None)
  9016. # Also clean up _print_ams_mappings and _print_plate_ids for archive_ids
  9017. # that have no remaining live keys in _expected_prints (all variants
  9018. # were just evicted) and are not printing right now. Print start pops
  9019. # only the names the printer reported, so the "<base>.gcode" variant
  9020. # outlives it; without the printing check its eviction two hours after
  9021. # dispatch threw away a running print's plate, AMS mapping and cost
  9022. # centre, which completion still reads (#3275).
  9023. live_archive_ids = set(_expected_prints.values()) | set(_active_prints.values())
  9024. for archive_id in evicted_archive_ids:
  9025. if archive_id not in live_archive_ids:
  9026. _print_ams_mappings.pop(archive_id, None)
  9027. _print_cost_center_ids.pop(archive_id, None)
  9028. _print_plate_ids.pop(archive_id, None)
  9029. logging.getLogger(__name__).info(
  9030. "Evicted %d stale expected-print entries (TTL=%ds)", len(stale_keys), _EXPECTED_PRINT_TTL_SECONDS
  9031. )
  9032. async def _expected_prints_cleanup_loop() -> None:
  9033. """Background task: periodically evict stale expected-print entries."""
  9034. while True:
  9035. try:
  9036. _evict_stale_expected_prints()
  9037. except asyncio.CancelledError:
  9038. raise
  9039. except Exception as e:
  9040. logging.getLogger(__name__).warning("Expected prints cleanup failed: %s", e)
  9041. await asyncio.sleep(_EXPECTED_PRINT_CLEANUP_INTERVAL)
  9042. def start_expected_prints_cleanup() -> None:
  9043. global _expected_prints_cleanup_task
  9044. if _expected_prints_cleanup_task is None:
  9045. _expected_prints_cleanup_task = asyncio.create_task(_expected_prints_cleanup_loop())
  9046. logging.getLogger(__name__).info("Expected prints cleanup started")
  9047. def stop_expected_prints_cleanup() -> None:
  9048. global _expected_prints_cleanup_task
  9049. if _expected_prints_cleanup_task:
  9050. _expected_prints_cleanup_task.cancel()
  9051. _expected_prints_cleanup_task = None
  9052. logging.getLogger(__name__).info("Expected prints cleanup stopped")
  9053. # ---------------------------------------------------------------------------
  9054. # L-2: Periodic auth-token cleanup (stale TOTP + expired revoked JTIs)
  9055. # ---------------------------------------------------------------------------
  9056. _auth_cleanup_task: asyncio.Task | None = None
  9057. _AUTH_CLEANUP_INTERVAL = 3600 # seconds (hourly)
  9058. async def _run_auth_cleanup() -> None:
  9059. """Single cleanup pass: remove stale TOTP records, expired revoked JTIs, and old rate-limit events."""
  9060. from backend.app.core.database import async_session
  9061. from backend.app.models.auth_ephemeral import AuthEphemeralToken, AuthRateLimitEvent
  9062. from backend.app.models.user_totp import UserTOTP
  9063. now = datetime.now(timezone.utc)
  9064. # Remove unconfirmed (is_enabled=False) TOTP records older than 1 hour.
  9065. try:
  9066. async with async_session() as db:
  9067. stale_cutoff = now - timedelta(hours=1)
  9068. result = await db.execute(
  9069. select(UserTOTP).where(
  9070. UserTOTP.is_enabled.is_(False),
  9071. UserTOTP.created_at < stale_cutoff,
  9072. )
  9073. )
  9074. stale_records = result.scalars().all()
  9075. if stale_records:
  9076. for rec in stale_records:
  9077. await db.delete(rec)
  9078. await db.commit()
  9079. logging.info("Auth cleanup: removed %d stale unconfirmed TOTP record(s)", len(stale_records))
  9080. except Exception as e:
  9081. logging.warning("Auth cleanup: failed to purge stale TOTP records: %s", e)
  9082. # Remove expired revoked-JTI entries (they are no longer needed once the
  9083. # original token's exp has passed — the token would be rejected by JWT
  9084. # signature verification regardless).
  9085. try:
  9086. async with async_session() as db:
  9087. await db.execute(
  9088. delete(AuthEphemeralToken).where(
  9089. AuthEphemeralToken.token_type == "revoked_jti",
  9090. AuthEphemeralToken.expires_at < now,
  9091. )
  9092. )
  9093. await db.commit()
  9094. except Exception as e:
  9095. logging.warning("Auth cleanup: failed to purge expired revoked JTIs: %s", e)
  9096. # L-R6-B: Purge AuthRateLimitEvent rows older than the lockout window (15 min).
  9097. # Events outside this window can never affect rate-limit decisions — they only
  9098. # consume DB space. Use the same window constant as the rate limiter so the
  9099. # two are always in sync.
  9100. try:
  9101. from backend.app.api.routes.mfa import LOCKOUT_WINDOW
  9102. async with async_session() as db:
  9103. await db.execute(
  9104. delete(AuthRateLimitEvent).where(
  9105. AuthRateLimitEvent.occurred_at < now - LOCKOUT_WINDOW,
  9106. )
  9107. )
  9108. await db.commit()
  9109. except Exception as e:
  9110. logging.warning("Auth cleanup: failed to purge stale rate-limit events: %s", e)
  9111. async def _auth_cleanup_loop() -> None:
  9112. """Periodic background task: run auth cleanup every hour."""
  9113. while True:
  9114. try:
  9115. await _run_auth_cleanup()
  9116. except asyncio.CancelledError:
  9117. break
  9118. except Exception as e:
  9119. logging.warning("Auth cleanup loop error: %s", e)
  9120. await asyncio.sleep(_AUTH_CLEANUP_INTERVAL)
  9121. def start_auth_cleanup() -> None:
  9122. global _auth_cleanup_task
  9123. if _auth_cleanup_task is None:
  9124. _auth_cleanup_task = asyncio.create_task(_auth_cleanup_loop())
  9125. logging.getLogger(__name__).info("Auth periodic cleanup started")
  9126. def stop_auth_cleanup() -> None:
  9127. global _auth_cleanup_task
  9128. if _auth_cleanup_task:
  9129. _auth_cleanup_task.cancel()
  9130. _auth_cleanup_task = None
  9131. logging.getLogger(__name__).info("Auth periodic cleanup stopped")
  9132. @asynccontextmanager
  9133. async def lifespan(app: FastAPI):
  9134. # Startup
  9135. # Install Windows-only asyncio Proactor cleanup-RST filter (#1113) before
  9136. # anything else can spawn tasks that might trip it.
  9137. from backend.app.core.asyncio_handlers import install_proactor_reset_filter, warn_if_running_on_uvloop
  9138. install_proactor_reset_filter()
  9139. # Before anything opens files or sockets in bulk: a soft limit of 1024 is
  9140. # what turned descriptor exhaustion into a corrupted database (#2883).
  9141. from backend.app.core.fd_limit import raise_open_file_limit
  9142. raise_open_file_limit()
  9143. # Before init_db, so the warning is near the top of the log rather than
  9144. # below a migration run. See warn_if_running_on_uvloop for what is at stake.
  9145. warn_if_running_on_uvloop()
  9146. await init_db()
  9147. # Browser download tokens expire after five minutes. Remove abandoned
  9148. # prepared ZIPs at startup as well as before each new preparation so a
  9149. # quiet appliance cannot retain an unusable bundle indefinitely.
  9150. try:
  9151. from backend.app.services.printer_media import prune_stale_printer_file_bundles
  9152. await prune_stale_printer_file_bundles()
  9153. except Exception as exc:
  9154. logging.warning("Failed to prune stale printer download bundles: %s", exc)
  9155. # After migrations, so the is_env_managed column exists. Never raises --
  9156. # a bad BAMBUDDY_OIDC_* value is logged and skipped rather than blocking
  9157. # startup (see apply_env_oidc_provider).
  9158. from backend.app.core.oidc_env import apply_env_oidc_provider
  9159. async with async_session() as oidc_db:
  9160. await apply_env_oidc_provider(oidc_db)
  9161. # Close out batches that finished before `completed` was a reachable status
  9162. # (#342). Without this the Batches tab opens on every batch created since
  9163. # the feature shipped, all still marked active. Never blocks startup.
  9164. try:
  9165. from backend.app.services.print_batch import backfill_batch_statuses
  9166. async with async_session() as batch_db:
  9167. await backfill_batch_statuses(batch_db)
  9168. except Exception as exc:
  9169. logging.warning("[BATCH] Startup status backfill failed: %s", exc)
  9170. # Register an app-scoped httpx client for Bambu Cloud services so
  9171. # per-request BambuCloudService instances reuse the same connection pool
  9172. # (important for routes like /cloud/filament-info that chain many
  9173. # get_setting_detail calls). The shared client stores no region/token
  9174. # state, so the per-request ownership pattern that fixed the region-bleed
  9175. # bug is preserved.
  9176. import httpx as _httpx
  9177. from backend.app.services.bambu_cloud import set_shared_http_client
  9178. from backend.app.services.model_providers.makerworld.service import (
  9179. set_shared_http_client as set_shared_makerworld_http_client,
  9180. )
  9181. from backend.app.services.orca_cloud import (
  9182. set_shared_http_client as set_shared_orca_http_client,
  9183. )
  9184. _shared_cloud_http_client = _httpx.AsyncClient(timeout=30.0)
  9185. set_shared_http_client(_shared_cloud_http_client)
  9186. # Reuse the same connection pool for MakerWorld — different host, same
  9187. # keep-alive pool saves a TLS handshake per request.
  9188. set_shared_makerworld_http_client(_shared_cloud_http_client)
  9189. # Same for Orca Cloud — without this the per-request OrcaCloudService()
  9190. # each spun up (and never closed) its own client, leaking sockets.
  9191. set_shared_orca_http_client(_shared_cloud_http_client)
  9192. # Fix queue items stuck with invalid "aborted" status (should be "cancelled").
  9193. # This can happen when a print was cancelled mid-print on versions before this fix.
  9194. try:
  9195. async with async_session() as db:
  9196. from backend.app.models.print_queue import PrintQueueItem
  9197. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.status == "aborted"))
  9198. aborted_items = result.scalars().all()
  9199. if aborted_items:
  9200. for item in aborted_items:
  9201. item.status = "cancelled"
  9202. await db.commit()
  9203. logging.info("Fixed %d queue item(s) with invalid 'aborted' status → 'cancelled'", len(aborted_items))
  9204. except Exception as e:
  9205. logging.warning("Failed to fix aborted queue items: %s", e)
  9206. # Restore debug logging state from previous session
  9207. await init_debug_logging()
  9208. # Set up printer manager callbacks
  9209. loop = asyncio.get_event_loop()
  9210. printer_manager.set_event_loop(loop)
  9211. printer_manager.set_status_change_callback(on_printer_status_change)
  9212. printer_manager.set_print_start_callback(on_print_start)
  9213. printer_manager.set_print_complete_callback(on_print_complete)
  9214. printer_manager.set_print_running_observed_callback(on_print_running_observed)
  9215. printer_manager.set_finish_photo_moment_callback(on_finish_photo_moment)
  9216. printer_manager.set_ams_change_callback(on_ams_change)
  9217. printer_manager.set_fts_inlet_change_callback(on_fts_inlet_change)
  9218. # Rehydrate persisted awaiting-plate-clear gate (#961) so prompts survive restarts
  9219. await printer_manager.load_awaiting_plate_clear_from_db()
  9220. # Layer change callback for external camera timelapse
  9221. async def on_layer_change(printer_id: int, layer_num: int):
  9222. """Capture timelapse frame on layer change + first layer notification."""
  9223. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  9224. await tl_layer_change(printer_id, layer_num)
  9225. # #1867: bank a recent in-print frame so the finish-photo path has a
  9226. # pre-End-G-code image to use instead of a live grab of a swapped plate.
  9227. # #2547 added `on_print_progress` as a second driver — this one alone
  9228. # stops firing once the final layer begins.
  9229. await _maybe_bank_inprint_frame(printer_id, layer_num)
  9230. # First layer complete notification (layer_num >= 2 means layer 1 is done).
  9231. # Gate on actual printing state — Bambu firmware ticks layer_num during
  9232. # the pre-print calibration sequence (homing / mesh-level / bed scan /
  9233. # nozzle clean), so a bare layer_num check can fire minutes before the
  9234. # first real extrusion. We require gcode_state == RUNNING and
  9235. # mc_print_sub_stage in (0 = "Printing", None) so calibration sub-stages
  9236. # (1, 9, 14, ...) are excluded. The window widens to [2, 10] because if
  9237. # the layer counter advanced past 2 during PREPARE, the next on_layer_change
  9238. # edge fires later; _first_layer_notified stays clear until we actually send
  9239. # so a deferred re-evaluation can win. See issue #1837.
  9240. if 2 <= layer_num <= 10 and not _first_layer_notified.get(printer_id, False):
  9241. client = printer_manager.get_client(printer_id)
  9242. state = client.state if client else None
  9243. if not state or state.state != "RUNNING":
  9244. return
  9245. if state.mc_print_sub_stage not in (None, 0):
  9246. return
  9247. _first_layer_notified[printer_id] = True
  9248. try:
  9249. async with async_session() as db:
  9250. from backend.app.models.printer import Printer
  9251. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  9252. printer = result.scalar_one_or_none()
  9253. if not printer:
  9254. return
  9255. printer_name = printer.name
  9256. filename = (state.subtask_name or state.gcode_file or "Unknown") if state else "Unknown"
  9257. total_layers = state.total_layers if state else 0
  9258. image_data = await _capture_snapshot_for_notification(
  9259. printer_id, printer, logging.getLogger(__name__)
  9260. )
  9261. await notification_service.on_first_layer_complete(
  9262. printer_id, printer_name, filename, total_layers, db, image_data=image_data
  9263. )
  9264. except Exception as e:
  9265. logging.getLogger(__name__).warning("First layer notification failed: %s", e)
  9266. printer_manager.set_layer_change_callback(on_layer_change)
  9267. async def on_print_progress(printer_id: int, percent: int):
  9268. """#2547: keep the in-print frame bank fresh through the final layer.
  9269. `on_layer_change` stops the moment the last layer starts, which on the
  9270. H2C capture that closed #2547 left the bank stale for the three minutes
  9271. that layer took. Progress is the only field that keeps advancing there,
  9272. and it freezes before the End G-code runs — so banking on it stays
  9273. inside the print and never sees a swapped plate.
  9274. """
  9275. client = printer_manager.get_client(printer_id)
  9276. state = client.state if client else None
  9277. await _maybe_bank_inprint_frame(printer_id, state.layer_num if state else 0)
  9278. printer_manager.set_print_progress_callback(on_print_progress)
  9279. # Event-driven bed cooldown: fires whenever bed_temper arrives via MQTT
  9280. async def on_bed_temp_update(printer_id: int, bed_temp: float):
  9281. waiter = _bed_cool_waiters.get(printer_id)
  9282. if not waiter:
  9283. return
  9284. threshold = waiter["threshold"]
  9285. if bed_temp > threshold:
  9286. return
  9287. # Bed is at or below threshold — fire notification and remove waiter
  9288. waiter_info = _bed_cool_waiters.pop(printer_id, None)
  9289. if not waiter_info:
  9290. return # Another callback already handled it
  9291. bed_cool_logger = logging.getLogger(__name__)
  9292. bed_cool_logger.info(
  9293. "[BED-COOL] Bed cooled to %.1f°C on printer %s (threshold: %.0f°C)",
  9294. bed_temp,
  9295. printer_id,
  9296. threshold,
  9297. )
  9298. try:
  9299. printer_info = printer_manager.get_printer(printer_id)
  9300. p_name = printer_info.name if printer_info else "Unknown"
  9301. async with async_session() as db:
  9302. await notification_service.on_bed_cooled(
  9303. printer_id=printer_id,
  9304. printer_name=p_name,
  9305. bed_temp=bed_temp,
  9306. threshold=threshold,
  9307. filename=waiter_info["filename"],
  9308. db=db,
  9309. )
  9310. except Exception as e:
  9311. bed_cool_logger.warning("[BED-COOL] Failed to send notification: %s", e)
  9312. printer_manager.set_bed_temp_update_callback(on_bed_temp_update)
  9313. async def on_drying_complete(printer_id: int, ams_id: int):
  9314. """Smart-plug auto-off-after-drying trigger (#1349).
  9315. Fires once per AMS unit when ``dry_time`` falls from >0 to 0. The
  9316. manager walks all plugs linked to this printer and turns off only
  9317. the ones with ``auto_off_after_drying`` enabled, after their
  9318. per-plug delay. Multiple AMS units finishing close together (e.g. a
  9319. dual-AMS dry that ends within the same MQTT push) call this once
  9320. per unit — the manager's ``_cancel_pending_off`` collapses
  9321. repeated scheduling on the same plug to one timer, so duplicate
  9322. fires are safe.
  9323. """
  9324. try:
  9325. async with async_session() as db:
  9326. await smart_plug_manager.on_drying_complete(printer_id, db)
  9327. except Exception as e:
  9328. logging.getLogger(__name__).warning(
  9329. "Failed to schedule auto-off-after-drying for printer %d (AMS %d): %s",
  9330. printer_id,
  9331. ams_id,
  9332. e,
  9333. )
  9334. printer_manager.set_drying_complete_callback(on_drying_complete)
  9335. async def on_drying_cycle_end(printer_id: int, cycle):
  9336. """Mark the spools in an AMS that just finished drying as dried (#2863)."""
  9337. from backend.app.services.spool_drying import record_drying_cycle
  9338. try:
  9339. async with async_session() as db:
  9340. await record_drying_cycle(db, printer_id, cycle)
  9341. except Exception as e:
  9342. logging.getLogger(__name__).warning(
  9343. "Failed to record drying for printer %d (AMS %d): %s",
  9344. printer_id,
  9345. cycle.ams_id,
  9346. e,
  9347. )
  9348. printer_manager.set_drying_cycle_end_callback(on_drying_cycle_end)
  9349. async def on_assignment_verified(printer_id: int, ams_id: int, tray_id: int, verified: bool, detail: dict):
  9350. """Surface the read-back result of a spool assignment to the UI (#2582).
  9351. The MQTT client confirms (or fails to confirm) that the tray telemetry
  9352. echoed back the filament id we pushed. We relay that as a websocket
  9353. event so the frontend can toast "loaded" / "assignment didn't take"
  9354. instead of the historic silent fire-and-forget, which made the
  9355. AMS→Studio hand-off feel random to users.
  9356. """
  9357. try:
  9358. from backend.app.services.spool_assignment_notifications import (
  9359. _slot_label_from_global_tray,
  9360. )
  9361. if ams_id == 255:
  9362. global_id = 254 + tray_id
  9363. elif ams_id >= 128:
  9364. global_id = ams_id
  9365. else:
  9366. global_id = ams_id * 4 + tray_id
  9367. slot_label = _slot_label_from_global_tray(global_id)
  9368. printer_info = printer_manager.get_printer(printer_id)
  9369. printer_name = printer_info.name if printer_info else f"Printer {printer_id}"
  9370. await ws_manager.broadcast(
  9371. {
  9372. "type": "spool_assignment_verified",
  9373. "printer_id": printer_id,
  9374. "printer_name": printer_name,
  9375. "ams_id": ams_id,
  9376. "tray_id": tray_id,
  9377. "slot": slot_label,
  9378. "verified": verified,
  9379. # Present on success: False means the filament setting landed
  9380. # but the K-profile (cali_idx) did not — the reporter's exact
  9381. # "loaded but no flow profile" symptom.
  9382. "kprofile_applied": detail.get("kprofile_applied", True),
  9383. # Present on failure: whether any tray telemetry was seen in
  9384. # the window (distinguishes "printer silent" from "printer
  9385. # stored something else").
  9386. "saw_tray": detail.get("saw_tray", False),
  9387. }
  9388. )
  9389. except Exception as e:
  9390. logging.getLogger(__name__).warning(
  9391. "Failed to broadcast assignment verification for printer %d AMS%d-T%d: %s",
  9392. printer_id,
  9393. ams_id,
  9394. tray_id,
  9395. e,
  9396. )
  9397. printer_manager.set_assignment_verified_callback(on_assignment_verified)
  9398. async def on_tray_change(printer_id: int, tray_global: int, layer_num: int):
  9399. """Persist a mid-print tray change for completion-time attribution.
  9400. AMS filament backup switches trays without telling the slicer, so the
  9401. tray-change log is the only record of which spool fed which layers.
  9402. Keeping it only in memory meant a restart mid-print charged everything
  9403. to the tray that finished the job.
  9404. """
  9405. try:
  9406. from backend.app.services.usage_tracker import record_tray_change
  9407. async with async_session() as db:
  9408. await record_tray_change(db, printer_id, tray_global, layer_num)
  9409. except Exception as e:
  9410. logging.getLogger(__name__).warning(
  9411. "Failed to persist tray change for printer %d (tray=%d, layer=%d): %s",
  9412. printer_id,
  9413. tray_global,
  9414. layer_num,
  9415. e,
  9416. )
  9417. printer_manager.set_tray_change_callback(on_tray_change)
  9418. # Initialize MQTT relay from settings
  9419. async with async_session() as db:
  9420. from backend.app.api.routes.settings import get_setting
  9421. mqtt_settings = {
  9422. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  9423. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  9424. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  9425. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  9426. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  9427. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  9428. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  9429. }
  9430. await mqtt_relay.configure(mqtt_settings)
  9431. # Restore MQTT smart plug subscriptions
  9432. if mqtt_settings.get("mqtt_enabled"):
  9433. from backend.app.models.smart_plug import SmartPlug
  9434. from backend.app.services.mqtt_smart_plug import subscribe_plug_to_mqtt
  9435. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  9436. mqtt_plugs = result.scalars().all()
  9437. restored = 0
  9438. for plug in mqtt_plugs:
  9439. if subscribe_plug_to_mqtt(mqtt_relay.smart_plug_service, plug):
  9440. restored += 1
  9441. if restored:
  9442. logging.info("Restored %s MQTT smart plug subscriptions", restored)
  9443. # Connect to all active printers
  9444. async with async_session() as db:
  9445. await init_printer_connections(db)
  9446. # Auto-connect to Spoolman if enabled
  9447. async with async_session() as db:
  9448. from backend.app.api.routes.settings import get_setting
  9449. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  9450. spoolman_url = await get_setting(db, "spoolman_url")
  9451. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  9452. try:
  9453. client = await init_spoolman_client(spoolman_url)
  9454. if await client.health_check():
  9455. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  9456. # Ensure the 'tag' extra field exists for RFID/UUID storage
  9457. field_ok = await client.ensure_tag_extra_field()
  9458. if not field_ok:
  9459. logging.error("Spoolman tag extra field registration failed — NFC tag links may not persist")
  9460. # Register the BambuStudio slicer-preset fields used by the
  9461. # spool-edit / assign flow. Spoolman rejects PATCHes with
  9462. # unknown extra keys, so these must exist before any update
  9463. # that touches them.
  9464. for field_name in ("bambu_slicer_filament", "bambu_slicer_filament_name"):
  9465. if not await client.ensure_extra_field(field_name):
  9466. logging.warning(
  9467. "Spoolman extra field %r registration failed — "
  9468. "spool slicer-preset edits will return 502",
  9469. field_name,
  9470. )
  9471. else:
  9472. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  9473. except Exception as e:
  9474. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  9475. # Start the print scheduler
  9476. spawn_background_task(print_scheduler.run(), name="print-scheduler")
  9477. # Start the smart plug scheduler for time-based on/off
  9478. smart_plug_manager.start_scheduler()
  9479. # Start the Home Assistant sensor poller (#1148)
  9480. ha_sensor_manager.start()
  9481. location_ha_sensor_manager.start()
  9482. # Resume any pending auto-offs that were interrupted by restart
  9483. await smart_plug_manager.resume_pending_auto_offs()
  9484. # Start the notification digest scheduler
  9485. notification_service.start_digest_scheduler()
  9486. notify_live_activities.start()
  9487. notify_widgets.start()
  9488. # Start the Telegram reaction pollers (#3046), one per bot token used by a
  9489. # provider in reactions/both mode; the notification routes resync them.
  9490. # Never fatal: a bad provider row or a DB hiccup here costs reactions
  9491. # until the next provider save, not the whole startup.
  9492. try:
  9493. await telegram_reaction_poller.start()
  9494. except Exception as e:
  9495. logging.warning("Telegram reaction poller did not start: %s", e)
  9496. # Start the GitHub backup scheduler
  9497. await github_backup_service.start_scheduler()
  9498. # Start the local backup scheduler
  9499. await local_backup_service.start_scheduler()
  9500. await obico_detection_service.start()
  9501. # Start the library trash sweeper (#1008)
  9502. await library_trash_service.start_scheduler()
  9503. # Start the archive auto-purge sweeper (#1008 follow-up)
  9504. await archive_purge_service.start_scheduler()
  9505. # Start AMS history recording
  9506. start_ams_history_recording()
  9507. # Start printer sensor (nozzle / bed / chamber) history recording
  9508. start_printer_sensor_history_recording()
  9509. # Start printer runtime tracking
  9510. start_runtime_tracking()
  9511. # Start SpoolBuddy device watchdog
  9512. start_spoolbuddy_watchdog()
  9513. # Start camera stream orphan cleanup
  9514. start_camera_cleanup()
  9515. # Start the backstop for MQTT sessions paho has stopped recovering (#2732)
  9516. start_connection_watchdog()
  9517. # One-shot sweep for timelapse session directories orphaned by a crash
  9518. # or restart that happened mid-print (in-memory session tracking can't
  9519. # survive that, and nothing else reaps the leftover frames/output file)
  9520. try:
  9521. from backend.app.services.layer_timelapse import cleanup_orphaned_timelapse_sessions
  9522. removed = cleanup_orphaned_timelapse_sessions()
  9523. if removed:
  9524. logging.getLogger(__name__).info("Removed %d orphaned timelapse session artifact(s)", removed)
  9525. except Exception as e:
  9526. logging.getLogger(__name__).warning("Orphaned timelapse session cleanup failed: %s", e)
  9527. # Start expected-print TTL eviction (prevents memory leak when prints are
  9528. # registered but on_print_start never fires)
  9529. start_expected_prints_cleanup()
  9530. # L-2: Start periodic auth cleanup (stale TOTP + expired revoked JTIs)
  9531. start_auth_cleanup()
  9532. # Maintainer announcements: a signed feed fetched from GitHub every few hours.
  9533. from backend.app.services import announcements as announcements_service
  9534. announcements_service.start()
  9535. from backend.app.services.printer_media import start_printer_download_cleanup
  9536. start_printer_download_cleanup()
  9537. # Event-loop stall watchdog: dumps all thread stacks to stderr if the loop
  9538. # freezes (#1486 — silent "container hangs after adding a printer" reports).
  9539. from backend.app.services.loop_watchdog import start_loop_watchdog
  9540. start_loop_watchdog()
  9541. # Initialize virtual printer manager and sync from DB
  9542. from backend.app.services.virtual_printer import virtual_printer_manager
  9543. virtual_printer_manager.set_session_factory(async_session)
  9544. virtual_printer_manager.set_printer_manager(printer_manager)
  9545. try:
  9546. await virtual_printer_manager.sync_from_db()
  9547. logging.info("Virtual printer manager synced from database")
  9548. except Exception as e:
  9549. logging.warning("Failed to sync virtual printers: %s", e)
  9550. yield
  9551. # Shutdown
  9552. print_scheduler.stop()
  9553. smart_plug_manager.stop_scheduler()
  9554. ha_sensor_manager.stop()
  9555. location_ha_sensor_manager.stop()
  9556. notification_service.stop_digest_scheduler()
  9557. await notify_live_activities.close()
  9558. await notify_widgets.close()
  9559. await telegram_reaction_poller.aclose()
  9560. github_backup_service.stop_scheduler()
  9561. local_backup_service.stop_scheduler()
  9562. library_trash_service.stop_scheduler()
  9563. archive_purge_service.stop_scheduler()
  9564. obico_detection_service.stop()
  9565. stop_ams_history_recording()
  9566. stop_printer_sensor_history_recording()
  9567. stop_runtime_tracking()
  9568. stop_spoolbuddy_watchdog()
  9569. stop_camera_cleanup()
  9570. stop_connection_watchdog()
  9571. from backend.app.services.loop_watchdog import stop_loop_watchdog
  9572. stop_loop_watchdog()
  9573. # Tear down all camera fan-out broadcasters (#1089) so subscribers exit
  9574. # cleanly rather than waiting on a queue that nothing will ever fill.
  9575. try:
  9576. from backend.app.services.camera_fanout import shutdown_all_broadcasters
  9577. await shutdown_all_broadcasters()
  9578. except Exception as e:
  9579. logging.warning("Failed to shut down camera broadcasters: %s", e)
  9580. stop_expected_prints_cleanup()
  9581. stop_auth_cleanup()
  9582. from backend.app.services import announcements as announcements_service
  9583. announcements_service.stop()
  9584. from backend.app.services.printer_media import stop_printer_download_cleanup
  9585. await stop_printer_download_cleanup()
  9586. printer_manager.disconnect_all()
  9587. slot_unlink_grace.reset()
  9588. await close_spoolman_client()
  9589. # Stop all virtual printer services
  9590. await virtual_printer_manager.stop_all()
  9591. await mqtt_smart_plug_service.disconnect(timeout=2)
  9592. await mqtt_relay.disconnect(timeout=2)
  9593. # Drop the shared Bambu Cloud HTTP client we registered at startup.
  9594. set_shared_http_client(None)
  9595. set_shared_makerworld_http_client(None)
  9596. set_shared_orca_http_client(None)
  9597. await _shared_cloud_http_client.aclose()
  9598. # Checkpoint WAL (SQLite only) and close all database connections
  9599. from backend.app.core.db_dialect import is_sqlite
  9600. if is_sqlite():
  9601. try:
  9602. async with engine.begin() as conn:
  9603. await conn.execute(text("PRAGMA wal_checkpoint(TRUNCATE)"))
  9604. logging.info("WAL checkpoint completed")
  9605. except Exception as e:
  9606. logging.warning("WAL checkpoint failed: %s", e)
  9607. await engine.dispose()
  9608. app = FastAPI(
  9609. title=app_settings.app_name,
  9610. description="Archive and manage Bambu Lab 3MF files",
  9611. version=APP_VERSION,
  9612. lifespan=lifespan,
  9613. )
  9614. # Added first so it sits innermost, next to the routes: a refused header's value
  9615. # (often a stored token) masked in every JSON body. See core.response_redaction.
  9616. app.add_middleware(RefusedHeaderResponseMask)
  9617. # =============================================================================
  9618. # Authentication Middleware - Secures ALL API routes by default
  9619. # =============================================================================
  9620. # Public routes that don't require authentication even when auth is enabled
  9621. PUBLIC_API_ROUTES = {
  9622. # Auth routes needed before/during login
  9623. "/api/v1/auth/status",
  9624. "/api/v1/auth/login",
  9625. "/api/v1/auth/setup", # Needed for initial setup and recovery
  9626. # Advanced auth status needed for login page
  9627. "/api/v1/auth/advanced-auth/status",
  9628. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  9629. "/api/v1/auth/forgot-password/confirm", # Complete password reset with token (H-6)
  9630. # 2FA routes that are called BEFORE a JWT is issued (pre-auth flow)
  9631. "/api/v1/auth/2fa/verify", # Exchange pre_auth_token + 2FA code for JWT
  9632. "/api/v1/auth/2fa/email/send", # Send OTP email (pre_auth_token based)
  9633. # OIDC routes that must be reachable without a JWT
  9634. "/api/v1/auth/oidc/providers", # Public list of enabled providers
  9635. "/api/v1/auth/oidc/callback", # Redirect target from OIDC provider
  9636. "/api/v1/auth/oidc/exchange", # Exchange short-lived OIDC token for JWT
  9637. # Connected apps: the app's server swaps a code for the user's identity,
  9638. # authenticated by its client secret rather than a login token.
  9639. "/api/v1/connect/token",
  9640. # Version check for updates (no sensitive data)
  9641. "/api/v1/updates/version",
  9642. # Metrics endpoint handles its own prometheus_token authentication
  9643. "/api/v1/metrics",
  9644. # Appliance bootstrap (#1589 follow-up): the SPA's i18n setup polls
  9645. # this BEFORE a JWT is available to pick up the firstboot wizard's
  9646. # hostname / timezone / locale and the chrony NTP-gate state. The
  9647. # response contains user-set defaults and a public sync flag — no
  9648. # secrets. Without this entry the global auth middleware returns 401
  9649. # before the route handler runs, regardless of the route's own
  9650. # "no auth required" intent.
  9651. "/api/v1/system/appliance",
  9652. # Cam Wall kiosk feed (#2531): a TV or Pi in kiosk mode has no login, so it
  9653. # authenticates with a long-lived ``camwall``-scoped token in the query
  9654. # string — exactly like the camera streams two lists below, and for the same
  9655. # reason (no header to put a JWT in). "Public" here only means the middleware
  9656. # steps aside; the route still runs RequireCamWallTokenIfAuthEnabled, which
  9657. # rejects an absent, expired, revoked, or wrong-scoped token. In particular a
  9658. # plain ``camera_stream`` token does NOT open this door.
  9659. "/api/v1/camwall/printers",
  9660. # Overlay branding: the route enforces overlay-scoped token authentication.
  9661. "/api/v1/overlay-branding/logo",
  9662. }
  9663. # Route prefixes that are public (for routes with dynamic segments)
  9664. PUBLIC_API_PREFIXES = [
  9665. # WebSocket connections handle their own auth
  9666. "/api/v1/ws",
  9667. # OIDC authorize redirects — include provider_id in path
  9668. "/api/v1/auth/oidc/authorize/",
  9669. # One-tap outcome-verdict links from push notifications (#1898). Tapped on
  9670. # a phone with no session, so no header can carry a JWT — the single-use
  9671. # capability token in the path IS the credential (same reasoning as the
  9672. # /dl/ slicer downloads below). The route grants nothing beyond writing
  9673. # good/reject on the one archive the token was minted for.
  9674. "/api/v1/archives/confirm/",
  9675. ]
  9676. # Route patterns that are public (read-only display data)
  9677. # These are checked with "in path" - needed because browsers load images/videos
  9678. # via <img src> and <video src> which don't include Authorization headers
  9679. PUBLIC_API_PATTERNS = [
  9680. # Thumbnails
  9681. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  9682. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  9683. # Images and media
  9684. "/photos/", # /archives/{id}/photos/{filename}
  9685. "/project-image/", # /archives/{id}/project-image/{path}
  9686. "/qrcode", # /archives/{id}/qrcode
  9687. "/timelapse", # /archives/{id}/timelapse (video)
  9688. "/cover", # /printers/{id}/cover
  9689. "/icon", # /external-links/{id}/icon
  9690. # Camera (streams loaded via <img> tag)
  9691. "/camera/stream", # /printers/{id}/camera/stream
  9692. "/camera/snapshot", # /printers/{id}/camera/snapshot
  9693. # Streaming-overlay status feed (#2613): OBS loads /overlay/{id} with no login
  9694. # and this backs it, authenticated by an ``overlay``-scoped token in the query
  9695. # string (same reasoning as the camera streams above — no header to carry a
  9696. # JWT). "Public" only means the middleware steps aside; the route still runs
  9697. # RequireOverlayTokenIfAuthEnabled, which rejects an absent, expired, revoked,
  9698. # or wrong-scoped token — a camwall or camera_stream token does NOT open it.
  9699. "/overlay-status", # /printers/{id}/overlay-status
  9700. # Slicer token-authenticated downloads — protocol handlers (bambustudioopen://,
  9701. # orcaslicer://) cannot send auth headers. These endpoints validate a short-lived
  9702. # download token in the URL path instead.
  9703. "/dl/", # /archives/{id}/dl/{token}/{filename}, /library/files/{id}/dl/{token}/{filename}
  9704. # Same family, but the segment is "source-dl" — which does NOT contain "/dl/",
  9705. # and these patterns match by substring. Without its own entry the middleware
  9706. # 401s the slicer's header-less request before the route's token check runs,
  9707. # so "Open source 3MF in slicer" failed whenever auth was enabled (#3029).
  9708. "/source-dl/", # /archives/{id}/source-dl/{token}/{filename}
  9709. # Obico ML API fetches JPEG frames by one-shot nonce (issue #172 follow-up).
  9710. # The nonce itself is the credential: 32-byte random, single-use, ~30s TTL.
  9711. "/obico/cached-frame/", # /obico/cached-frame/{nonce}
  9712. ]
  9713. _security_headers_logger = logging.getLogger("backend.app.main.security_headers")
  9714. def _parse_trusted_frame_origins() -> tuple[str, ...]:
  9715. """Parse TRUSTED_FRAME_ORIGINS env var into a validated allowlist (#1191).
  9716. Format: comma-separated list of ``scheme://host[:port]`` origins.
  9717. Used by ``security_headers_middleware`` to relax ``frame-ancestors`` for
  9718. trusted same-LAN deployments (e.g. Home Assistant Webpage panel embedding
  9719. Bambuddy from a different port). Defaults to empty — strict ``'none'``.
  9720. Invalid entries are dropped with a warning rather than failing startup, so
  9721. a typo in one origin doesn't take the whole deployment down.
  9722. """
  9723. raw = os.environ.get("TRUSTED_FRAME_ORIGINS", "").strip()
  9724. if not raw:
  9725. return ()
  9726. valid: list[str] = []
  9727. for item in raw.split(","):
  9728. candidate = item.strip()
  9729. if not candidate:
  9730. continue
  9731. try:
  9732. parsed = urlparse(candidate)
  9733. except ValueError as e:
  9734. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — %s", candidate, e)
  9735. continue
  9736. if parsed.scheme not in ("http", "https"):
  9737. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — must be http(s)", candidate)
  9738. continue
  9739. if not parsed.netloc:
  9740. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — missing host", candidate)
  9741. continue
  9742. if parsed.path and parsed.path != "/":
  9743. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — paths not allowed", candidate)
  9744. continue
  9745. if parsed.query or parsed.fragment:
  9746. _security_headers_logger.warning(
  9747. "TRUSTED_FRAME_ORIGINS: dropping %r — query/fragment not allowed", candidate
  9748. )
  9749. continue
  9750. if "*" in parsed.netloc:
  9751. _security_headers_logger.warning("TRUSTED_FRAME_ORIGINS: dropping %r — wildcards not allowed", candidate)
  9752. continue
  9753. valid.append(f"{parsed.scheme}://{parsed.netloc}")
  9754. if valid:
  9755. _security_headers_logger.info("TRUSTED_FRAME_ORIGINS: %s", ", ".join(valid))
  9756. return tuple(valid)
  9757. _TRUSTED_FRAME_ORIGINS: tuple[str, ...] = _parse_trusted_frame_origins()
  9758. def _frame_ancestors(default_value: str) -> str:
  9759. """Compose the ``frame-ancestors`` CSP directive (#1191).
  9760. ``default_value`` is the strict directive used when the operator has not
  9761. configured ``TRUSTED_FRAME_ORIGINS`` — typically ``'none'`` (catch-all and
  9762. docs) or ``'self'`` (the streaming overlay, embedded same-origin by the
  9763. Settings URL builder's preview). When trusted origins
  9764. are configured, ``'self'`` is always included so same-origin embedding never
  9765. breaks even if an operator forgets to add their own origin to the list.
  9766. """
  9767. if _TRUSTED_FRAME_ORIGINS:
  9768. return "frame-ancestors 'self' " + " ".join(_TRUSTED_FRAME_ORIGINS) + ";"
  9769. return f"frame-ancestors {default_value};"
  9770. # The two Vite-emitted worker assets that compile WebAssembly (#2976). Both
  9771. # patterns are anchored on the exact emitted name so the relaxed policies
  9772. # below can never apply to any other asset.
  9773. # src/workers/stepPreview.worker.ts -> /assets/stepPreview.worker-<hash>.js
  9774. # pdfjs-dist/legacy/build/pdf.worker.min.mjs?worker&url
  9775. # -> /assets/pdf.worker.min-<hash>.js
  9776. # Vite also emits a one-line chunk under the second name that only exports the
  9777. # worker's URL. The page imports it as a module, and a module script is run
  9778. # under the importing document's policy, never its own response's, so it
  9779. # matching as well changes nothing.
  9780. _STEP_WORKER_ASSET_RE = re.compile(r"^/assets/stepPreview\.worker-[\w-]+\.js$")
  9781. _PDF_WORKER_ASSET_RE = re.compile(r"^/assets/pdf\.worker\.min-[\w-]+\.js$")
  9782. @app.middleware("http")
  9783. async def security_headers_middleware(request, call_next):
  9784. """Add standard HTTP security headers to every response."""
  9785. # Per-request nonce stamped into `script-src` (#1460). On its own this
  9786. # changes nothing for Bambuddy's own pages — index.html has no inline
  9787. # scripts since the SW registration moved to /sw-register.js. The reason
  9788. # it's here is Cloudflare: a CF-fronted deployment has the bot-detection
  9789. # script injected into the HTML on the edge, with a fresh hash on every
  9790. # load (so hashes can't be allowlisted). When CF sees a nonce in our CSP,
  9791. # it clones the same nonce onto its injected <script>, and the inline
  9792. # script passes the policy without us needing 'unsafe-inline'. See
  9793. # https://developers.cloudflare.com/cloudflare-challenges/challenge-types/javascript-detections/#if-you-have-a-content-security-policy-csp
  9794. csp_nonce = secrets.token_urlsafe(16)
  9795. # Routes that render their own HTML need it too, or their inline script is
  9796. # blocked by the policy below. The outcome-confirmation page (#1898) is the
  9797. # one that does: it submits its own form so a verdict still costs one tap.
  9798. request.state.csp_nonce = csp_nonce
  9799. response = await call_next(request)
  9800. response.headers["X-Content-Type-Options"] = "nosniff"
  9801. # X-Frame-Options is the legacy cross-origin embedding control. Modern
  9802. # browsers honour CSP frame-ancestors instead, and the legacy
  9803. # `ALLOW-FROM <url>` syntax is deprecated and inconsistent across vendors.
  9804. # When operators have explicitly allowlisted trusted frame origins (#1191
  9805. # — typically Home Assistant on a different port), drop X-Frame-Options
  9806. # and let the CSP-side frame-ancestors directive govern embedding.
  9807. if not _TRUSTED_FRAME_ORIGINS:
  9808. response.headers["X-Frame-Options"] = "SAMEORIGIN"
  9809. response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
  9810. # Content-Security-Policy for the React SPA.
  9811. # Notes:
  9812. # - 'unsafe-inline' for style-src: React and UI libs inject inline styles at runtime.
  9813. # - connect-src ws:/wss:: MQTT/printer WebSocket connections.
  9814. # - img-src data: / blob:: base64 thumbnails and Blob-URL timelapse previews.
  9815. # - media-src blob:: timelapse video player uses Blob URLs.
  9816. # - font-src data:: some icon fonts are embedded as data URIs.
  9817. if request.url.path in ("/docs", "/redoc", "/docs/oauth2-redirect"):
  9818. # FastAPI's built-in Swagger UI / ReDoc pages load assets from
  9819. # cdn.jsdelivr.net and bootstrap with an inline <script>, so the
  9820. # default CSP would render a blank page.
  9821. response.headers["Content-Security-Policy"] = (
  9822. "default-src 'self'; "
  9823. "script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
  9824. "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; "
  9825. "img-src 'self' data: blob: https://fastapi.tiangolo.com https://cdn.redoc.ly; "
  9826. "connect-src 'self'; "
  9827. "font-src 'self' data: https://fonts.gstatic.com; "
  9828. "worker-src 'self' blob:; "
  9829. "object-src 'none'; "
  9830. "base-uri 'self'; " + _frame_ancestors("'none'")
  9831. )
  9832. elif _STEP_WORKER_ASSET_RE.match(request.url.path):
  9833. # The STEP preview worker (#2976) runs OpenCascade compiled to WASM;
  9834. # its emscripten/embind glue generates invoker functions with `new
  9835. # Function(...)`, which needs 'unsafe-eval'. Per CSP3 a dedicated
  9836. # worker is governed by the policy delivered with the WORKER SCRIPT's
  9837. # own response — not the document's — so relaxing it here confines
  9838. # eval to that DOM-less worker context. The document policy below
  9839. # stays nonce-strict, and this response header has no effect when the
  9840. # file is merely fetched (a fetch's CSP is enforced against the
  9841. # requesting document, not the resource's own headers).
  9842. response.headers["Content-Security-Policy"] = (
  9843. "default-src 'self'; "
  9844. "script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
  9845. "connect-src 'self'; "
  9846. "object-src 'none'; "
  9847. "base-uri 'self'; " + _frame_ancestors("'none'")
  9848. )
  9849. elif _PDF_WORKER_ASSET_RE.match(request.url.path):
  9850. # pdf.js decodes JPEG2000/JBIG2 images and ICC colour with WebAssembly
  9851. # and fetches those modules from /assets/pdfjs/wasm/ (#2976). Same CSP3
  9852. # rule as the STEP worker above: the policy that governs a dedicated
  9853. # worker is the one delivered with its own script, so the wasm compile
  9854. # has to be permitted here rather than on the document. Unlike the STEP
  9855. # worker this one needs no JS eval, so it gets 'wasm-unsafe-eval' only.
  9856. response.headers["Content-Security-Policy"] = (
  9857. "default-src 'self'; "
  9858. "script-src 'self' 'wasm-unsafe-eval'; "
  9859. "connect-src 'self'; "
  9860. "object-src 'none'; "
  9861. "base-uri 'self'; " + _frame_ancestors("'none'")
  9862. )
  9863. else:
  9864. # The streaming overlay is embedded same-origin by the URL builder's
  9865. # preview in Settings (#1422), so this branch allows 'self'.
  9866. # Embedding from anywhere else is still refused: 'self'
  9867. # only permits a framer on this origin, which is Bambuddy's own UI, so
  9868. # a clickjacking page on another host is blocked exactly as before.
  9869. # (The overlay draws status over a camera feed and its only interactive
  9870. # element is the logo link, so there is nothing to bait a click into
  9871. # even from a same-origin framer.) Cross-origin embedding of the
  9872. # overlay — Home Assistant on another port — remains what
  9873. # TRUSTED_FRAME_ORIGINS is for, and _frame_ancestors already folds that
  9874. # allowlist in.
  9875. #
  9876. # The connected-app consent page (/connect/authorize) gets the same
  9877. # 'self': an app opened from Bambuddy's sidebar runs in an iframe, and
  9878. # its "Sign in with Bambuddy" navigates that iframe to this page. With
  9879. # 'none' the browser refuses to show it even inside Bambuddy. 'self'
  9880. # requires every ancestor to be this origin, so a foreign page -- a
  9881. # sidebar link's site included -- still cannot frame the consent
  9882. # screen to bait a click.
  9883. embeddable_same_origin = request.url.path.startswith("/overlay/") or request.url.path == "/connect/authorize"
  9884. # No 'wasm-unsafe-eval' here: nothing compiles WebAssembly on the main
  9885. # thread. Both wasm consumers — the STEP preview and pdf.js's image
  9886. # decoders (#2976) — run in dedicated workers, which CSP3 governs by
  9887. # the policy served with their own script, so each gets it in its own
  9888. # branch above and the document policy stays as strict as it was.
  9889. response.headers["Content-Security-Policy"] = (
  9890. "default-src 'self'; "
  9891. f"script-src 'self' 'nonce-{csp_nonce}'; "
  9892. "style-src 'self' 'unsafe-inline'; "
  9893. "img-src 'self' data: blob:; "
  9894. "media-src 'self' blob:; "
  9895. "connect-src 'self' ws: wss:; "
  9896. "font-src 'self' data:; "
  9897. "object-src 'none'; "
  9898. "base-uri 'self'; "
  9899. "frame-src 'self' http: https:; " + _frame_ancestors("'self'" if embeddable_same_origin else "'none'")
  9900. )
  9901. if request.url.scheme == "https":
  9902. response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
  9903. return response
  9904. @app.middleware("http")
  9905. async def auth_middleware(request, call_next):
  9906. """Enforce authentication on all API routes when auth is enabled.
  9907. This middleware provides defense-in-depth by checking auth at the API gateway level,
  9908. regardless of whether individual routes have auth dependencies.
  9909. """
  9910. from starlette.responses import JSONResponse
  9911. path = request.url.path
  9912. # Only apply to API routes
  9913. if not path.startswith("/api/"):
  9914. return await call_next(request)
  9915. # Allow public routes
  9916. if path in PUBLIC_API_ROUTES:
  9917. return await call_next(request)
  9918. # Allow public prefixes
  9919. for prefix in PUBLIC_API_PREFIXES:
  9920. if path.startswith(prefix):
  9921. return await call_next(request)
  9922. # Allow public patterns (read-only display data like thumbnails)
  9923. for pattern in PUBLIC_API_PATTERNS:
  9924. if pattern in path:
  9925. return await call_next(request)
  9926. # Check if auth is enabled. Fail CLOSED on any exception during the
  9927. # probe — GHSA-6mf4-q26m-47pv: the previous fail-open path here let
  9928. # an attacker who could force a DB exception (e.g. file-descriptor
  9929. # exhaustion via login flood) bypass auth on every protected endpoint.
  9930. # Only the probe is guarded: the request itself runs outside the try, so an
  9931. # error in a route surfaces as the 500 it is rather than as an auth outage.
  9932. try:
  9933. async with async_session() as db:
  9934. from backend.app.core.auth import is_auth_enabled
  9935. auth_enabled = await is_auth_enabled(db)
  9936. except Exception:
  9937. logging.getLogger(__name__).exception("auth_middleware: failing closed on auth-probe error from %s", path)
  9938. return JSONResponse(
  9939. status_code=503,
  9940. content={"detail": "Authentication service temporarily unavailable"},
  9941. )
  9942. if not auth_enabled:
  9943. # Auth disabled, allow all requests
  9944. return await call_next(request)
  9945. # Auth is enabled - require valid token
  9946. auth_header = request.headers.get("Authorization")
  9947. x_api_key = request.headers.get("X-API-Key")
  9948. # Check for API key auth first
  9949. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  9950. # API key authentication - let the request through to be validated by route handler
  9951. # API keys are validated per-route since they have different permission levels
  9952. return await call_next(request)
  9953. # Check for JWT auth
  9954. if not auth_header or not auth_header.startswith("Bearer "):
  9955. return JSONResponse(
  9956. status_code=401,
  9957. content={"detail": "Authentication required"},
  9958. headers={"WWW-Authenticate": "Bearer"},
  9959. )
  9960. # Validate JWT token
  9961. import jwt
  9962. try:
  9963. from backend.app.core.auth import (
  9964. ALGORITHM,
  9965. SECRET_KEY,
  9966. _is_token_fresh,
  9967. get_user_by_username,
  9968. is_jti_revoked,
  9969. )
  9970. token = auth_header.replace("Bearer ", "")
  9971. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  9972. username = payload.get("sub")
  9973. if not username:
  9974. raise ValueError("No username in token")
  9975. jti = payload.get("jti")
  9976. if not jti:
  9977. raise ValueError("No jti in token")
  9978. iat = payload.get("iat")
  9979. # Verify user exists, is active, and token is still fresh (L-R8-A).
  9980. # Reject revoked tokens first (defense-in-depth gateway check), reusing
  9981. # this session so the gateway adds a single pooled checkout, not two (#2572).
  9982. async with async_session() as db:
  9983. if await is_jti_revoked(jti, db):
  9984. return JSONResponse(
  9985. status_code=401,
  9986. content={"detail": "Token has been revoked"},
  9987. headers={"WWW-Authenticate": "Bearer"},
  9988. )
  9989. user = await get_user_by_username(db, username)
  9990. if not user or not user.is_active:
  9991. return JSONResponse(
  9992. status_code=401,
  9993. content={"detail": "User not found or inactive"},
  9994. headers={"WWW-Authenticate": "Bearer"},
  9995. )
  9996. if not _is_token_fresh(iat, user):
  9997. return JSONResponse(
  9998. status_code=401,
  9999. content={"detail": "Token no longer valid"},
  10000. headers={"WWW-Authenticate": "Bearer"},
  10001. )
  10002. except jwt.ExpiredSignatureError:
  10003. return JSONResponse(
  10004. status_code=401,
  10005. content={"detail": "Token has expired"},
  10006. headers={"WWW-Authenticate": "Bearer"},
  10007. )
  10008. except (jwt.InvalidTokenError, ValueError):
  10009. return JSONResponse(
  10010. status_code=401,
  10011. content={"detail": "Invalid token"},
  10012. headers={"WWW-Authenticate": "Bearer"},
  10013. )
  10014. except Exception:
  10015. # Not a bad token but a failure checking it (database, pool): refuse,
  10016. # as for the probe above, rather than answer 401 -- the frontend reads
  10017. # a 401 from /auth/me as final and signs the user out.
  10018. logging.getLogger(__name__).exception("auth_middleware: failing closed on token-check error from %s", path)
  10019. return JSONResponse(
  10020. status_code=503,
  10021. content={"detail": "Authentication service temporarily unavailable"},
  10022. )
  10023. return await call_next(request)
  10024. @app.middleware("http")
  10025. async def trace_id_middleware(request, call_next):
  10026. """Stamp every HTTP request with a trace ID and echo it back.
  10027. Decorated AFTER auth_middleware on purpose: Starlette stacks
  10028. @app.middleware decorators LIFO, so the last-decorated runs first
  10029. inbound. Putting the trace stamp last makes it the OUTERMOST layer,
  10030. which means auth-middleware log lines (and every line emitted on the
  10031. way down to and back from the route handler) all carry the same
  10032. trace ID. If we put it before auth, auth's logs would be stamped
  10033. with the *previous* request's ID — useless for correlation.
  10034. Honours an inbound ``X-Trace-Id`` header so callers running their
  10035. own tracing can correlate their span IDs with our log lines, but
  10036. only if the value passes the whitelist gate in
  10037. ``backend.app.core.trace.normalise_inbound_trace_id`` — anything
  10038. rejected (too long, contains control chars, etc.) silently triggers
  10039. a freshly minted server-side ID rather than failing the request.
  10040. The minted (or echoed) ID is set on a ContextVar so that every log
  10041. record emitted during the request — application logs *and* uvicorn's
  10042. access log — carries it via TraceIDFilter, and is also written to
  10043. the ``X-Trace-Id`` response header so clients can pin a server-side
  10044. log search to the exact request they made.
  10045. """
  10046. from backend.app.core.trace import (
  10047. generate_trace_id,
  10048. normalise_inbound_trace_id,
  10049. trace_id_var,
  10050. )
  10051. inbound = normalise_inbound_trace_id(request.headers.get("X-Trace-Id"))
  10052. trace_id = inbound if inbound is not None else generate_trace_id()
  10053. token = trace_id_var.set(trace_id)
  10054. try:
  10055. response = await call_next(request)
  10056. finally:
  10057. # Reset the ContextVar so a record emitted in a totally
  10058. # unrelated background task that just happens to inherit this
  10059. # context doesn't keep referencing this request's ID forever.
  10060. # In practice ContextVar.reset is best-effort under asyncio
  10061. # task-spawn semantics, but the cost is one attribute write so
  10062. # we may as well do it.
  10063. trace_id_var.reset(token)
  10064. response.headers["X-Trace-Id"] = trace_id
  10065. return response
  10066. # API routes
  10067. app.include_router(auth.router, prefix=app_settings.api_prefix)
  10068. app.include_router(mfa.router, prefix=app_settings.api_prefix)
  10069. app.include_router(bug_report.router, prefix=app_settings.api_prefix)
  10070. app.include_router(users.router, prefix=app_settings.api_prefix)
  10071. app.include_router(groups.router, prefix=app_settings.api_prefix)
  10072. app.include_router(printers.router, prefix=app_settings.api_prefix)
  10073. app.include_router(printer_locations.router, prefix=app_settings.api_prefix)
  10074. app.include_router(archives.router, prefix=app_settings.api_prefix)
  10075. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  10076. app.include_router(finance.router, prefix=app_settings.api_prefix)
  10077. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  10078. app.include_router(labels.router, prefix=app_settings.api_prefix)
  10079. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  10080. app.include_router(overlay_branding.router, prefix=app_settings.api_prefix)
  10081. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  10082. app.include_router(orca_cloud.router, prefix=app_settings.api_prefix)
  10083. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  10084. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  10085. app.include_router(ha_sensors.router, prefix=app_settings.api_prefix)
  10086. app.include_router(location_ha_sensors.router, prefix=app_settings.api_prefix)
  10087. app.include_router(print_log.router, prefix=app_settings.api_prefix)
  10088. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  10089. app.include_router(scheduled_dryings.router, prefix=app_settings.api_prefix)
  10090. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  10091. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  10092. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  10093. app.include_router(user_notifications.router, prefix=app_settings.api_prefix)
  10094. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  10095. app.include_router(spoolman_inventory.router, prefix=app_settings.api_prefix)
  10096. app.include_router(updates.router, prefix=app_settings.api_prefix)
  10097. app.include_router(sponsor_prompt.router, prefix=app_settings.api_prefix)
  10098. app.include_router(announcements.router, prefix=app_settings.api_prefix)
  10099. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  10100. app.include_router(camera.router, prefix=app_settings.api_prefix)
  10101. app.include_router(camwall.router, prefix=app_settings.api_prefix)
  10102. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  10103. app.include_router(projects.router, prefix=app_settings.api_prefix)
  10104. app.include_router(library.router, prefix=app_settings.api_prefix)
  10105. app.include_router(library_tags.router, prefix=app_settings.api_prefix)
  10106. app.include_router(library_trash.router, prefix=app_settings.api_prefix)
  10107. app.include_router(library_variants.router, prefix=app_settings.api_prefix)
  10108. app.include_router(slice_jobs.router, prefix=app_settings.api_prefix)
  10109. app.include_router(slicer_pipelines.router, prefix=app_settings.api_prefix)
  10110. app.include_router(pipeline_runs.pipeline_run_create_router, prefix=app_settings.api_prefix)
  10111. app.include_router(pipeline_runs.pipeline_run_router, prefix=app_settings.api_prefix)
  10112. app.include_router(slicer_presets.router, prefix=app_settings.api_prefix)
  10113. app.include_router(archive_purge.router, prefix=app_settings.api_prefix)
  10114. app.include_router(makerworld.router, prefix=app_settings.api_prefix)
  10115. app.include_router(manyfold.router, prefix=app_settings.api_prefix)
  10116. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  10117. app.include_router(connected_apps.router, prefix=app_settings.api_prefix)
  10118. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  10119. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  10120. app.include_router(printer_sensor_history.router, prefix=app_settings.api_prefix)
  10121. app.include_router(system.router, prefix=app_settings.api_prefix)
  10122. app.include_router(support.router, prefix=app_settings.api_prefix)
  10123. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  10124. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  10125. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  10126. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  10127. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  10128. app.include_router(local_backup.router, prefix=app_settings.api_prefix)
  10129. app.include_router(obico.router, prefix=app_settings.api_prefix)
  10130. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  10131. app.include_router(virtual_printers.router, prefix=app_settings.api_prefix)
  10132. app.include_router(spoolbuddy.router, prefix=app_settings.api_prefix)
  10133. # Serve static files (React build)
  10134. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  10135. # Compressed, and cached for good where Vite hashed the name (#3175).
  10136. app.mount(
  10137. "/assets",
  10138. AssetStaticFiles(directory=app_settings.static_dir / "assets"),
  10139. name="assets",
  10140. )
  10141. if (app_settings.static_dir / "img").exists():
  10142. app.mount(
  10143. "/img",
  10144. StaticFiles(directory=app_settings.static_dir / "img"),
  10145. name="img",
  10146. )
  10147. if (app_settings.static_dir / "icons").exists():
  10148. app.mount(
  10149. "/icons",
  10150. StaticFiles(directory=app_settings.static_dir / "icons"),
  10151. name="icons",
  10152. )
  10153. # Self-hosted Inter woff2 files (#1460). Without this mount /fonts/*.woff2
  10154. # falls through to the SPA catch-all and returns index.html, which the
  10155. # browser's font sanitizer rejects ("downloadable font: rejected by
  10156. # sanitizer").
  10157. if (app_settings.static_dir / "fonts").exists():
  10158. app.mount(
  10159. "/fonts",
  10160. StaticFiles(directory=app_settings.static_dir / "fonts"),
  10161. name="fonts",
  10162. )
  10163. @app.get("/")
  10164. async def serve_frontend():
  10165. """Serve the React frontend."""
  10166. index_file = app_settings.static_dir / "index.html"
  10167. if index_file.exists():
  10168. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10169. return {
  10170. "message": "Bambuddy API",
  10171. "docs": "/docs",
  10172. "frontend": "Build and place React app in /static directory",
  10173. }
  10174. # index.html must always be revalidated — Vite emits content-hashed JS/CSS
  10175. # bundles (e.g. `index-JRaF_JhW.js`), so the JS itself is safe to cache
  10176. # forever, but the HTML wrapping it is the only file that knows which hash
  10177. # is current. Without explicit cache-control headers Chromium decides
  10178. # heuristically (typically 10% of the time since Last-Modified) and on
  10179. # long-running kiosks happily serves stale HTML across browser restarts.
  10180. # That stale HTML references an old bundle hash, the old bundle is also
  10181. # in the disk cache, and the user ends up running pre-update JS forever
  10182. # without ever knowing why. ``no-cache`` (revalidate every time, but a
  10183. # 304 is cheap) is the correct setting for an SPA's entry HTML.
  10184. _HTML_CACHE_HEADERS = {"Cache-Control": "no-cache, must-revalidate"}
  10185. @app.get("/health")
  10186. async def health_check():
  10187. """Health check endpoint."""
  10188. return {"status": "healthy"}
  10189. # GET + HEAD on the three PWA bootstrap routes (#1460). Scanners and a plain
  10190. # `curl -I` use HEAD; FastAPI's @app.get only registers GET, so HEAD answers
  10191. # with 405 Method Not Allowed and shows up as a "broken manifest" red herring
  10192. # in deployment debugging.
  10193. @app.api_route("/manifest.json", methods=["GET", "HEAD"])
  10194. async def serve_manifest():
  10195. """Serve PWA manifest."""
  10196. manifest_file = app_settings.static_dir / "manifest.json"
  10197. if manifest_file.exists():
  10198. return FileResponse(manifest_file, media_type="application/manifest+json")
  10199. return {"error": "Manifest not found"}
  10200. @app.api_route("/sw.js", methods=["GET", "HEAD"])
  10201. async def serve_service_worker():
  10202. """Serve service worker."""
  10203. sw_file = app_settings.static_dir / "sw.js"
  10204. if sw_file.exists():
  10205. return FileResponse(
  10206. sw_file,
  10207. media_type="application/javascript",
  10208. headers={"Cache-Control": "no-cache, no-store, must-revalidate"},
  10209. )
  10210. return {"error": "Service worker not found"}
  10211. @app.api_route("/sw-register.js", methods=["GET", "HEAD"])
  10212. async def serve_sw_register():
  10213. """Serve the service-worker registration bootstrap script.
  10214. Served as a real JS file so the strict `script-src 'self'` CSP covers it
  10215. without needing 'unsafe-inline' or per-build hashes on the inline tag.
  10216. """
  10217. reg_file = app_settings.static_dir / "sw-register.js"
  10218. if reg_file.exists():
  10219. return FileResponse(reg_file, media_type="application/javascript")
  10220. return {"error": "sw-register.js not found"}
  10221. # ── GCode viewer static files ────────────────────────────────────────────────
  10222. # Catch-all route for React Router (must be last)
  10223. @app.get("/{full_path:path}")
  10224. async def serve_spa(full_path: str):
  10225. """Serve React app for client-side routing."""
  10226. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  10227. if full_path.startswith("api/"):
  10228. from fastapi import HTTPException
  10229. raise HTTPException(status_code=404, detail="Not found")
  10230. index_file = app_settings.static_dir / "index.html"
  10231. if index_file.exists():
  10232. return FileResponse(index_file, headers=_HTML_CACHE_HEADERS)
  10233. return {"error": "Frontend not built"}